Ansible基本使用
- 安装
[root@localhost ~]# rpm Uvh http://mirrors.ustc.edu.cn/epel/epel-release-latest-7.noarch.rpm
[root@localhost ~]# yum -y install epel-release
[root@localhost ~]# yum -y install ansible
-
重要文件
ansible的安装目录是/etc/ansible
ansible.cfg //配置文件 hosts //inventory,ansible需要连接的主机列表,可以填ip或者域名
[root@localhost ~]# vi /etc/ansible/hosts # This is the default ansible 'hosts' file. # # It should live in /etc/ansible/hosts [web] 192.168.56.44 192.168.56.45 192.168.56.42 192.168.56.43 [client] 192.168.56.100
- 实战
- ping模块 判断远程客户端主机是否在线,ping服务器本身
[root@localhost ~]# ansible -k all -m ping SSH password: 192.168.56.45 | SUCCESS => { "changed": false, "ping": "pong" } 192.168.56.44 | SUCCESS => { "changed": false, "ping": "pong" } 192.168.56.42 | SUCCESS => { "changed": false, "ping": "pong" } 192.168.56.100 | SUCCESS => { "changed": false, "ping": "pong" } 192.168.56.43 | SUCCESS => { "changed": false, "ping": "pong" }
- command模块 默认是command模块,所以可以不 -m command指定模块
[root@localhost ~]# ansible -k all -a "date" SSH password: 192.168.56.100 | SUCCESS | rc=0 >> Thu Jun 21 22:58:18 CST 2018 192.168.56.42 | SUCCESS | rc=0 >> Thu Jun 21 14:58:20 CST 2018 192.168.56.43 | SUCCESS | rc=0 >> Thu Jun 21 14:58:17 CST 2018 192.168.56.44 | SUCCESS | rc=0 >> Thu Jun 21 14:58:17 CST 2018 192.168.56.45 | SUCCESS | rc=0 >> Thu Jun 21 14:58:18 CST 2018
实例:修改网卡网管并重启网络
[root@localhost ~]# ansible -k all -a " sed -i '/GATEWAY/s/192.168.56.2/192.168.56.1/g' /etc/sysconfig/network-scripts/ifcfg-ens33 " SSH password: [WARNING]: Consider using the replace, lineinfile or template module rather than running sed. If you need to use command because replace, lineinfile or template is insufficient you can add warn=False to this command task or set command_warnings=False in ansible.cfg to get rid of this message. 192.168.56.100 | FAILED | rc=2 >> sed: can't read /etc/sysconfig/network-scripts/ifcfg-ens33: No such file or directorynon-zero return code 192.168.56.45 | SUCCESS | rc=0 >> 192.168.56.43 | SUCCESS | rc=0 >> 192.168.56.42 | SUCCESS | rc=0 >> 192.168.56.44 | SUCCESS | rc=0 >> [root@localhost ~]# ansible -k all -a "systemctl restart network " SSH password: 192.168.56.45 | SUCCESS | rc=0 >> 192.168.56.43 | SUCCESS | rc=0 >> 192.168.56.44 | SUCCESS | rc=0 >> 192.168.56.42 | SUCCESS | rc=0 >> 192.168.56.100 | SUCCESS | rc=0 >>
- ping模块 判断远程客户端主机是否在线,ping服务器本身
-
报错处理
-
第一次执行ansible命令,但是管控机从来没有登录过被管控机,会报如下错误
[root@localhost ~]# ansible -k all -m ping SSH password: 192.168.56.100 | FAILED! => { "msg": "Using a SSH password instead of a key is not possible because Host Key checking is enabled and sshpass does not support this. Please add this host's fingerprint to your known_hosts file to manage this host." }
解决方案:
[root@localhost ~]# vim /etc/ansible/ansible.cfg ....... # uncomment this to disable SSH key host checking host_key_checking = False
验证:
[root@localhost ~]# ansible -k all -m ping SSH password: 192.168.56.100 | SUCCESS => { "changed": false, "ping": "pong" }
-