ansible使用

本文介绍如何在CentOS 6.8 x64系统中安装Ansible,并演示了基本的应用示例,包括配置管理、软件包管理、服务管理等模块的使用方法。此外,还介绍了Playbooks的基本用法及高级特性。
系统centos6.8x64IP
Master192.168.195.210
Node1192.168.195.211
Node2192.168.195.212

1.安装

[root@localhost ~]# yum -y install python-jinja2 PyYAML python-paramiko python-babel python-crypto
[root@localhost ~]# yum install python-setuptools # 安装python安装工具
[root@localhost ~]# yum groupinstall "Development tools" # 安装gcc编译组件
[root@localhost ~]# rpm -ivh python-crypto2.6-2.6.1-2.el6.x86_64.rpm # 解决依赖关系
[root@localhost ~]# rpm -Uvh ansible-2.2.1.0-1.el6.src.rpm
[root@localhost ~]# cd rpmbuild/SOURCES/
[root@localhost SOURCES]# tar xf ansible-2.2.1.0.tar.gz
[root@localhost SOURCES]# cd ansible-2.2.1.0
[root@localhost ansible-2.2.1.0]# python setup.py build
[root@localhost ansible-2.2.1.0]# python setup.py install
[root@localhost ansible-2.2.1.0]# mkdir /etc/ansible
[root@localhost ansible-2.2.1.0]# cp -r examples/* /etc/ansible

2.简单应用

[root@localhost ~]# cd /etc/ansible/
[root@localhost ansible]# vim hosts # 增加被控节点
[webservers]
node1
[dbservers]
node2
[root@localhost ansible]# vim /etc/hosts # 域名解析
192.168.195.211 node1
192.168.195.212 node2
[root@localhost ansible]# ssh-keygen -t rsa -P '' # 密钥认证
[root@localhost ansible]# ssh-copy-id -i /root/.ssh/id_rsa.pub root@node1
The authenticity of host 'node1 (192.168.195.211)' can't be established.
RSA key fingerprint is 1b:bb:92:76:3c:30:49:85:3c:58:b0:08:09:03:6f:24.
Are you sure you want to continue connecting (yes/no)? yes
Warning: Permanently added 'node1,192.168.195.211' (RSA) to the list of known hosts.
root@node1's password: 
Now try logging into the machine, with "ssh 'root@node1'", and check in:

  .ssh/authorized_keys

to make sure we haven't added extra keys that you weren't expecting.
[root@localhost ~]# ssh-copy-id -i /root/.ssh/id_rsa.pub root@node2
[root@localhost ~]# ansible all -m ping # 命令所有节点执行ping命令
node1 | SUCCESS => {
    "changed": false, 
    "ping": "pong"
}
node2 | SUCCESS => {
    "changed": false, 
    "ping": "pong"
}

3.模块使用

# 修改selinux
[root@localhost ~]# ansible all -m selinux -a "policy=targeted state=disabled"
node2 | FAILED! => {
    "changed": false, 
    "failed": true, 
    "msg": "libselinux-python required for this module"
}
node1 | FAILED! => {
    "changed": false, 
    "failed": true, 
    "msg": "libselinux-python required for this module"
}
[root@localhost ~]# yum install libselinux-python
[root@localhost ~]# ansible all -m yum -a "name=libselinux-python"
[root@localhost ~]# ansible all -m selinux -a "policy=targeted state=disabled"
node2 | SUCCESS => {
    "changed": false, 
    "configfile": "/etc/selinux/config", 
    "msg": "", 
    "policy": "targeted", 
    "state": "disabled"
}
node1 | SUCCESS => {
    "changed": true, 
    "configfile": "/etc/selinux/config", 
    "msg": "runtime state temporarily changed from 'enforcing' to 'permissive', state change will take effect next reboot, config state changed from 'enforcing' to 'disabled'", 
    "policy": "targeted", 
    "state": "disabled"
}
[root@localhost ~]# ansible all -a "tail -l /etc/selinux/config"
[root@localhost ~]# ansible --help # 查看ansible命令格式
[root@localhost ~]# ansible-doc -l # 列出ansible模块
# copy模块
[root@localhost ~]# ansible-doc -s copy # 列出模块参数
[root@localhost ~]# ansible dbservers -m copy -a "src=/root/test.txt dest=/tmp/"
node2 | SUCCESS => {
    "changed": true, 
    "checksum": "d84946dfa5750a1b3375aa960c377824049654ef", 
    "dest": "/tmp/test.txt", 
    "gid": 0, 
    "group": "root", 
    "md5sum": "3493e5b77f7443dde989b82d6d0e3e6e", 
    "mode": "0644", 
    "owner": "root", 
    "size": 14, 
    "src": "/root/.ansible/tmp/ansible-tmp-1489963116.88-189159680912730/source", 
    "state": "file", 
    "uid": 0
}
[root@localhost ~]# ansible dbservers -a "ls /tmp"
node2 | SUCCESS | rc=0 >>
ansible_50yCWX
test.txt
yum.log
# cron模块
[root@localhost ~]# ansible-doc cron -s
[root@localhost ~]# ansible all -m cron -a 'name="custom job" minute=*/3 hour=* day=* month=* weekday=* job="/usr/sbin/ntpdate 192.168.195.210"'
node2 | SUCCESS => {
    "changed": true, 
    "envs": [], 
    "jobs": [
        "custom job"
    ]
}
node1 | SUCCESS => {
    "changed": true, 
    "envs": [], 
    "jobs": [
        "custom job"
    ]
}
[root@localhost ~]# ansible all -a "crontab -l"
node1 | SUCCESS | rc=0 >>
#Ansible: custom job
*/3 * * * * /usr/sbin/ntpdate 192.168.195.210

node2 | SUCCESS | rc=0 >>
#Ansible: custom job
*/3 * * * * /usr/sbin/ntpdate 192.168.195.210
# group模块
[root@localhost ~]# ansible all -m group -a "gid=306 system=yes name=mysql"
node1 | SUCCESS => {
    "changed": true, 
    "gid": 306, 
    "name": "mysql", 
    "state": "present", 
    "system": true
}
node2 | SUCCESS => {
    "changed": true, 
    "gid": 306, 
    "name": "mysql", 
    "state": "present", 
    "system": true
}
[root@localhost ~]# ansible all -a "tail -1 /etc/group"
node2 | SUCCESS | rc=0 >>
mysql:x:306:

node1 | SUCCESS | rc=0 >>
mysql:x:306:
# yum
[root@localhost ~]# ansible-doc -s yum
[root@localhost ~]# ansible all -m yum -a "state=present name=corosync"
[root@localhost ~]# ansible all -a "rpm -q corosync"
node2 | SUCCESS | rc=0 >>
corosync-1.4.7-5.el6.x86_64

node1 | SUCCESS | rc=0 >>
corosync-1.4.7-5.el6.x86_64
# service模块
[root@localhost ~]# ansible all -a "service httpd status"
node2 | FAILED | rc=1 >>
httpd: 未被识别的服务

node1 | FAILED | rc=1 >>
httpd: 未被识别的服务
[root@localhost ~]# ansible all -m yum -a "name=httpd"
[root@localhost ~]# ansible all -a "service httpd status"
node2 | FAILED | rc=3 >>
httpd 已停

node1 | FAILED | rc=3 >>
httpd 已停
[root@localhost ~]# ansible all -a "chkconfig --list httpd"
node1 | SUCCESS | rc=0 >>
httpd          	0:关闭	1:关闭	2:关闭	3:关闭	4:关闭	5:关闭	6:关闭

node2 | SUCCESS | rc=0 >>
httpd          	0:关闭	1:关闭	2:关闭	3:关闭	4:关闭	5:关闭	6:关闭
[root@localhost ~]# ansible all -m service -a "state=started name=httpd enabled=yes"
node2 | SUCCESS => {
    "changed": true, 
    "enabled": true, 
    "name": "httpd", 
    "state": "started"
}
node1 | SUCCESS => {
    "changed": true, 
    "enabled": true, 
    "name": "httpd", 
    "state": "started"
}
[root@localhost ~]# ansible all -a "service httpd status"
node2 | SUCCESS | rc=0 >>
httpd (pid  2532) 正在运行...

node1 | SUCCESS | rc=0 >>
httpd (pid  2609) 正在运行...

[root@localhost ~]# ansible all -a "chkconfig --list httpd"
node2 | SUCCESS | rc=0 >>
httpd          	0:关闭	1:关闭	2:启用	3:启用	4:启用	5:启用	6:关闭

node1 | SUCCESS | rc=0 >>
httpd          	0:关闭	1:关闭	2:启用	3:启用	4:启用	5:启用	6:关闭

4.playbooks

[root@localhost ~]# vim test.yaml
# 缩进一致
- host: all
  remote_user: root
  tasks:
  - name: add a group
    group: gid=1000 name=testgroup system=no
  - name: excute a command
    command: /bin/date
[root@localhost ~]# ansible-playbook test.yaml 

PLAY [all] *********************************************************************

TASK [setup] *******************************************************************
ok: [node2]
ok: [node1]

TASK [add a group] *************************************************************
changed: [node2]
changed: [node1]

TASK [excute a command] ********************************************************
changed: [node2]
changed: [node1]

PLAY RECAP *********************************************************************
node1                      : ok=3    changed=2    unreachable=0    failed=0   
node2                      : ok=3    changed=2    unreachable=0    failed=0

    remote_user也可用于各task中。也可以通过指定其通过sudo的方式在远程主机上执行任务,其可用于play全局或某任务;此外,甚至可以在sudo时使用sudo_user指定sudo时切换的用户

- hosts: webnodes
  remote_user: 
  tasks:
  - name: test connection
    ping:
    remote_user: 
    sudo: yes

    play的主体部分是task list。task list中的各任务按次序逐个在hosts中指定的所有主机上执行,即在所有主机上完成第一个任务后再开始第二个。在运行自下而下某playbook时,如果中途发生错误,所有已执行任务都将回滚,因此,在更正playbook后重新执行一次即可。

    tasks的目的是使用指定的参数执行模块,而在模块参数中可以使用变量。模块执行是幂等的,这意味着多次执行是安全的,因为其结果均一致。

    每个task都应该有其name,用于playbook的执行结果输出,建议其内容尽可能清晰地描述任务执行步骤。如果未提供name,则action的结果将用于输出。

    定义task的可以使用“action: module options”或“module: options”的格式,推荐使用后者以实现向后兼容。如果action一行的内容过多,也中使用在行首使用几个空白字符进行换行。
        tasks:
          - name: make sure apache is running
            service: name=httpd state=running

        在众多模块中,只有command和shell模块仅需要给定一个列表而无需使用“key=value”格式,例如:
            tasks:
              - name: disable selinux
                command: /sbin/setenforce 0

        如果命令或脚本的退出码不为零,可以使用如下方式替代:
            tasks:
              - name: run this command and ignore the result
                shell: /usr/bin/somecommand || /bin/true        

        或者使用ignore_errors来忽略错误信息:
            tasks:
              - name: run this command and ignore the result
                shell: /usr/bin/somecommand
                ignore_errors: True    

    handlers 用于当关注的资源发生变化时采取一定的操作,“notify”这个action可用于在每个play的最后被触发,这样可以避免多次有改变发生时每次都执行指定的操作,取而代之,仅在所有的变化发生完成后一次性地执行指定操作。在notify中列出的操作称为handler,也即notify中调用handler中定义的操作。

[root@localhost ~]# cp /etc/httpd/conf/httpd.conf .
[root@localhost ~]# vim httpd.conf 
Listen 8080
[root@localhost ~]# vim handlers.yaml
- hosts: all
  remote_user: root
  tasks:
   - name: ensure httpd
     yum: state=latest name=httpd
   - name: copy configure file
     copy: src=/root/httpd.conf dest=/etc/httpd/conf/httpd.conf force=yes
     notify:
      - restart httpd
  handlers:
   - name: restart httpd
     service: name=httpd state=restarted
[root@localhost ~]# ansible-playbook handlers.yaml 

PLAY [all] *********************************************************************

TASK [setup] *******************************************************************
ok: [node2]
ok: [node1]

TASK [ensure httpd] ************************************************************
ok: [node2]
ok: [node1]

TASK [copy configure file] *****************************************************
changed: [node2]
changed: [node1]

RUNNING HANDLER [restart httpd] ************************************************
changed: [node2]
changed: [node1]

PLAY RECAP *********************************************************************
node1                      : ok=4    changed=2    unreachable=0    failed=0   
node2                      : ok=4    changed=2    unreachable=0    failed=0
- hosts: hbhosts
  remote_user: root
  tasks:
  - name: ensure heartbeat latest version
    yum: name=heartbeat state=present
  - name: authkeys configure file
    copy: src=/root/hb_conf/authkeys dest=/etc/ha.d/authkeys
  - name: authkeys mode 600
    file: path=/etc/ha.d/authkeys mode=600
    notify:
     - restart heartbeat
  - name: ha.cf configure file
    opy: src=/root/hb_conf/ha.cf dest=/etc/ha.d/ha.cf
    notify: 
     - restart heartbeat
  handlers:
   - name: restart heartbeat
	 service: name=heartbeat state=restarted

 

转载于:https://my.oschina.net/charlock/blog/862675

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符  | 博主筛选后可见
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值