ansible

Posted xuqidong

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了ansible相关的知识,希望对你有一定的参考价值。

1.安装ansible
wget -O /etc/yum.repos.d/epel.repo http://mirrors.aliyun.com/repo/epel-7.repo
yum install ansible -y
      
      
    
2.管理被控端,管理机先生成秘钥,然后推送公钥
[root@demo ~]# ssh-keygen
[root@demo ~]# for i in {11..12};do ssh-copy-id -i ~/.ssh/id_rsa.pub root@10.0.0.$i;done


3.配置被管理的主机清单
[root@demo ~]# cat /etc/ansible/hosts
[web]
10.0.0.11
10.0.0.12

4.使用ansible的ad-hoc测试
[root@demo ~]# ansible all -m ping
10.0.0.12 | SUCCESS => {
    "changed": false, 
    "ping": "pong"
}
10.0.0.11 | SUCCESS => {
    "changed": false, 
    "ping": "pong"
}

#执行远程命令
[root@demo ~]# ansible all -m shell -a "df -h"
10.0.0.12 | CHANGED | rc=0 >>
Filesystem      Size  Used Avail Use% Mounted on
/dev/sda3        98G  3.4G   95G   4% /
devtmpfs        477M     0  477M   0% /dev
tmpfs           488M     0  488M   0% /dev/shm
tmpfs           488M  7.7M  480M   2% /run
tmpfs           488M     0  488M   0% /sys/fs/cgroup
/dev/sda1       197M  102M   96M  52% /boot
tmpfs            98M     0   98M   0% /run/user/0

10.0.0.11 | CHANGED | rc=0 >>
Filesystem      Size  Used Avail Use% Mounted on
/dev/sda3        98G  1.6G   97G   2% /
devtmpfs        981M     0  981M   0% /dev
tmpfs           992M  124K  992M   1% /dev/shm
tmpfs           992M  9.6M  982M   1% /run
tmpfs           992M     0  992M   0% /sys/fs/cgroup
/dev/sda1       197M  102M   96M  52% /boot
tmpfs           199M     0  199M   0% /run/user/0


5.ansible playbook自动化安装nginx
[root@demo ~]# cat playbook_nginx.yml 
- hosts: web
  remote_user: root
  vars:
    http_port: 80
  tasks:
    - name: Add Nginx Yum Repository
      yum_repository:
        name: nginx
        description: Nginx Repository
        baseurl: http://nginx.org/packages/centos/7/$basearch/
        gpgcheck: no

    - name: Install Nginx Server
      yum: name=nginx state=present

    - name: Configure Nginx Server
      template: src=./default.conf.template dest=/etc/nginx/conf.d/default.conf
      notify: Restart Nginx Server

    - name: Start Nginx Server
      service: name=nginx state=started enabled=yes


  handlers:
    - name: Restart Nginx Server
      service: name=nginx state=restarted
      
      
6.default.conf.template文件如下
[root@demo ~]# cat default.conf.template 
server {
    listen       {{ http_port }};
    server_name  localhost;

    location / {
        root   /usr/share/nginx/html;
        index  index.html index.htm;
    }
}

7.执行ansible-playbook
检查语法
[root@demo ~]# ansible-playbook --syntax playbook_nginx.yml     

模拟执行
[root@demo ~]# ansible-playbook -C playbook_nginx.yml 

执行
[root@demo ~]# ansible-playbook playbook_nginx.yml       

 
     

 

以上是关于ansible的主要内容,如果未能解决你的问题,请参考以下文章

从jenkinsfile启动包含vault文件引用的Ansible playbook

ansible代码分析第一篇--主文件—ansible分析

python代码调用ansible

Ansible

基于ansible的zabbix源代码安装

需要代码来使用 Ansible 检查服务器连接