官网:https://docs.ansible.com/ansible/latest/index.html
1.ssh免密登录
[root@ansible ~]# ssh-keygen -t rsa -f /root/.ssh/id_rsa -N ''
[root@ansible ~]# ssh-copy-id 192.168.100.111
[root@ansible ~]# cat /root/.ssh/id_rsa
id_rsa id_rsa.pub
#验证
[root@host1 ~]# ls /root/.ssh/
authorized_keys
[root@host1 ~]# cat /root/.ssh/authorized_keys
ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDoUUN1es8TUpwbcK5g0kJZ3FG6Kikk/ZIWnZCTD/27ZlIANdlpJdXo2er4JwIgxBGl35fwN0zrT9yEKQjMfolk3W49z5KtH6DTSKZtfZJ7jmmFgQBRWDKSTDsXx3Y6nk0Bqbw3+nEr6BLJc2YpCic5dvsdI9G/Imqqu7ktRAF464wG68kzTY2yGBA4dv4FDYGKUf5wlKykDkmVtlnz72bjyfEAJY7v4KMMqf8B1NDKPSPZKSGzv9VrsdkBQ6Hp64JjbQ7k9F/9I9h84lLNpWSto58MzH93yql2EJfHpQw5CwBmR9fV3MhhaceN98FDOr0yK0eg6VV1BhYqFUkRr05d root@ansible
[root@host1 ~]# md5sum /root/.ssh/authorized_keys
2.ansible ping模块
#定义主机清单
vi /etc/ansible/hosts
## db-[99:101]-node.example.com
192.168.100.111
192.168.100.112
#验证
[root@ansible ~]# ansible 192.168.100.111 -m ping
192.168.100.111 | SUCCESS => {
"changed": false,
"ping": "pong"
}
[root@ansible ~]# ansible 192.168.100.112 -m ping
192.168.100.112 | SUCCESS => {
"changed": false,
"ping": "pong"
}
[root@ansible ~]# ansible all -m ping
192.168.100.111 | SUCCESS => {
"changed": false,
"ping": "pong"
}
192.168.100.112 | SUCCESS => {
"changed": false,
"ping": "pong"
}
3.ansible cron模块
[root@ansible ~]# yum install ntpdate -y
#同步阿里云时钟源
[root@ansible ~]# ntpdate time1.aliyun.com
[root@ansible ~]# ansible 192.168.100.111 -m cron -a 'name="cron1" job="ntpdate time1.aliyun.com" minute=0 hour=*/1'
192.168.100.111 | SUCCESS => {
"changed": true,
"envs": [],
"jobs": [
"cron1"
]
}
#主机验证
[root@host1 ~]# crontab -l
#Ansible: cron1
0 */1 * * * ntpdate time1.aliyun.com
4.ansible copy模块
[root@ansible ~]# cat /etc/hosts
127.0.0.1 localhost localhost.localdomain localhost4 localhost4.localdomain4
::1 localhost localhost.localdomain localhost6 localhost6.localdomain6
192.168.100.110 ansible
192.168.100.111 host1
192.168.100.112 host2
[root@ansible ~]# ansible 192.168.100.111 -m copy -a "src=/etc/hosts dest=/etc/hosts"
192.168.100.111 | SUCCESS => {
"changed": true,
"checksum": "793ab40e5b2e1d24322160c2d6048cff6934ed64",
"dest": "/etc/hosts",
"gid": 0,
"group": "root",
"md5sum": "76f6f44d672b8b6e2cde6e3bd42e3d72",
"mode": "0644",
"owner": "root",
"secontext": "system_u:object_r:net_conf_t:s0",
"size": 227,
"src": "/root/.ansible/tmp/ansible-tmp-1626252862.93-70640710365287/source",
"state": "file",
"uid": 0
}
#验证
[root@host1 ~]# cat /etc/hosts
127.0.0.1 localhost localhost.localdomain localhost4 localhost4.localdomain4
::1 localhost localhost.localdomain localhost6 localhost6.localdomain6
192.168.100.110 ansible
192.168.100.111 host1
192.168.100.112 host2
[root@host1 ~]# ping ansible
PING ansible (192.168.100.110) 56(84) bytes of data.
64 bytes from ansible (192.168.100.110): icmp_seq=1 ttl=64 time=0.303 ms
copy模块参考链接:https://docs.ansible.com/ansible/latest/collections/ansible/builtin/copy_module.html