Ansible

/etc/ansible/hosts资产文件


ssh秘钥

各主机直接ssh秘钥复制

[root@master ~]# ssh-keygen -t rsa -P ''
Generating public/private rsa key pair.
Enter file in which to save the key (/root/.ssh/id_rsa):
Created directory '/root/.ssh'.
Your identification has been saved in /root/.ssh/id_rsa.
Your public key has been saved in /root/.ssh/id_rsa.pub.
The key fingerprint is:
SHA256:/HdFpoNofEK4fWZJuWc8H4jkcCM6cCD1UZwOQS6DlCE root@master
The key's randomart image is:
+---[RSA 2048]----+
| E ++o.++.. |
| o.o +..+ . |
| . + ++o.+o o|
| =..**oo=.+ |
| oS *oO.B..|
| .o * o =.|
| . . . .|
| . . |
| |
+----[SHA256]-----+

安装ansible

yum install epel-release 

yum install ansible -y


ssh-copy-id -i ~/.ssh/id_rsa.pub root@192.168.101.97

ssh-copy-id -i ~/.ssh/id_rsa.pub root@192.168.101.83


资源清单文件

vim /etc/ansible/hosts
写法1
[test]
192.168.101.83
192.168.101.97


写法2
ansible_ssh_pass执行用户密码,当前执行ansible为root用户,所以用户默认不写
192.168.101.97 ansible_ssh_pass=redhat


192.168.101.97 ansible_ssh_user=root ansible_ssh_pass=redhat ansible_ssh_port=22


直接定义test资产组的密码变量
[test]
192.168.101.83
192.168.101.97
[test:vars]
ansible_ssh_pass=redhat


[test]
直接写域名


children子项目,web和db都属于test的子项目
[web]
192.168.101.83
[db]
192.168.101.97
[test:children]
web
db


shell模块使用管道符|截取/

[root@master opt]# ansible test -m shell -a 'df -h | grep /$'
192.168.101.83 | CHANGED | rc=0 >>
/dev/mapper/centos-root 29G 2.4G 27G 9% /
192.168.101.97 | CHANGED | rc=0 >>
/dev/mapper/centos-root 29G 2.4G 27G 9% /


ping模块

[root@master ~]# ansible test -m ping
192.168.101.97 | SUCCESS => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": false,
"ping": "pong"
}
192.168.101.83 | SUCCESS => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": false,
"ping": "pong"
}


raw命令模块

[root@master opt]# ansible test -m raw -a 'df -h'
192.168.101.83 | CHANGED | rc=0 >>
Filesystem Size Used Avail Use% Mounted on
devtmpfs 908M 0 908M 0% /dev
tmpfs 919M 0 919M 0% /dev/shm
tmpfs 919M 8.6M 911M 1% /run
tmpfs 919M 0 919M 0% /sys/fs/cgroup
/dev/mapper/centos-root 29G 2.4G 27G 9% /
/dev/sda1 1014M 150M 865M 15% /boot
tmpfs 184M 0 184M 0% /run/user/0
Shared connection to 192.168.101.83 closed.

192.168.101.97 | CHANGED | rc=0 >>
Filesystem Size Used Avail Use% Mounted on
devtmpfs 908M 0 908M 0% /dev
tmpfs 919M 0 919M 0% /dev/shm
tmpfs 919M 8.6M 911M 1% /run
tmpfs 919M 0 919M 0% /sys/fs/cgroup
/dev/mapper/centos-root 29G 2.4G 27G 9% /
/dev/sda1 1014M 150M 865M 15% /boot
tmpfs 184M 0 184M 0% /run/user/0
Shared connection to 192.168.101.97 closed.