ansible是Python语言(Python2)编写的一款批量管理linux主机的工具,适用于数十台、百台机器的管理,无需安装agent,非常方便。
1 主要依赖的Python模块
paramiko、PyYAML、jinjia2
2 ansible特性
部署简单:agentless
主从模式
默认使用ssh
支持自定义模块
支持各种编程语言
支持playbook
注意:ansible是基于各种模块来完成任务的
3 安装
在epel源中提供
yum install -y ansible
4 配置文件
/etc/ansible/ansible.cfg Invertary: /etc/ansible/hosts
/etc/ansible/hosts:配置主机列表:
[cent]
# 支持正则 10.129.206.[96:97] 10.129.205.151 [rh] 10.129.206.98
5 配置公钥免密登录
在安装ansible的机器上执行ssh-keygen -t rsa;接着分别拷贝公钥到各个主机(需要输入这些主机密码)。
ssh-keygen -t rsa ssh-copy-id -i /root/.ssh/id_rsa.pub root@10.129.206.98 ssh-copy-id -i /root/.ssh/id_rsa.pub root@10.129.206.97 ssh-copy-id -i /root/.ssh/id_rsa.pub root@10.129.206.96 ssh-copy-id -i /root/.ssh/id_rsa.pub root@10.129.205.151
6 查看模块帮助
ansible-doc -l ansible-doc -s MODULE
7 用法
# ansible <host-pattern> -f [fork] -m [module] -a [args] # host-pattern: /etc/ansible/hosts 配置文件中配置的 [主机或者主机组] # -f fork: 并发线程数数 # -m module: 使用哪个模块 # -a args: 使用模块所支持的参数,如果是[command]模块就是接命令。
以command模块为例:
# ansible cent -f 3 -m command -a ‘df -h‘
得到的结果:
[@tc_57_161 ~]# ansible cent -f 3 -m command -a ‘df -h‘ 10.129.206.97 | SUCCESS | rc=0 >> Filesystem Size Used Avail Use% Mounted on /dev/sda3 8.9G 4.5G 4.0G 54% / tmpfs 499M 0 499M 0% /dev/shm /dev/sda1 190M 27M 154M 15% /boot 10.129.206.96 | SUCCESS | rc=0 >> Filesystem Size Used Avail Use% Mounted on /dev/mapper/centos-root 27G 3.3G 24G 13% / devtmpfs 897M 0 897M 0% /dev tmpfs 912M 0 912M 0% /dev/shm tmpfs 912M 9.2M 903M 1% /run tmpfs 912M 0 912M 0% /sys/fs/cgroup /dev/sda1 1014M 179M 836M 18% /boot tmpfs 183M 4.0K 183M 1% /run/user/42 tmpfs 183M 40K 183M 1% /run/user/1000 /dev/sr0 8.1G 8.1G 0 100% /run/media/odin/CentOS 7 x86_64 tmpfs 183M 0 183M 0% /run/user/0 10.129.205.151 | SUCCESS | rc=0 >> Filesystem Size Used Avail Use% Mounted on /dev/mapper/cl-root 17G 6.8G 11G 40% / devtmpfs 897M 0 897M 0% /dev tmpfs 912M 84K 912M 1% /dev/shm tmpfs 912M 17M 895M 2% /run tmpfs 912M 0 912M 0% /sys/fs/cgroup /dev/sda1 1014M 173M 842M 18% /boot tmpfs 183M 16K 183M 1% /run/user/42 tmpfs 183M 0 183M 0% /run/user/0
还可以以all代表对所有主机;如果不指定模块,默认使用command模块。
# ansible all -a ‘uname -a‘
返回的结果:
[@tc_57_161 ~]# ansible all -a ‘uname -a‘ 10.129.206.97 | SUCCESS | rc=0 >> Linux liuyouyuan 2.6.32-642.el6.x86_64 #1 SMP Tue May 10 17:27:01 UTC 2016 x86_64 x86_64 x86_64 GNU/Linux 10.129.206.96 | SUCCESS | rc=0 >> Linux liuyouyuan 3.10.0-693.el7.x86_64 #1 SMP Tue Aug 22 21:09:27 UTC 2017 x86_64 x86_64 x86_64 GNU/Linux 10.129.206.98 | SUCCESS | rc=0 >> Linux liuyouyuan 2.6.32-696.3.1.el6.x86_64 #1 SMP Tue May 30 19:52:55 UTC 2017 x86_64 x86_64 x86_64 GNU/Linux 10.129.205.151 | SUCCESS | rc=0 >> Linux liuyouyuan 3.10.0-514.el7.x86_64 #1 SMP Tue Nov 22 16:42:41 UTC 2016 x86_64 x86_64 x86_64 GNU/Linux