ad-hoc 简而言之就是"临时命令",执行完即结束,并不会保存,也就是执行完一个模块就结束了,如果想让她反复运行,就不行了。不像将多个命令写到文件,可以反复运行。
[root@master ~]# ansible webservers -m shell -a "ps -aux | grep nginx" -i /etc/ansible/hosts
[root@master ~]# ansible webservers -m shell -a "touch /root/ansible.txt" -i /etc/ansible/hosts
命令示例∶ansible 'groups' -m command -a 'df -h',含义如下图所示;

shell模块其实可以解决很多问题,但是只用这个模块肯定是不行的,而且shell模块无法保证幂等性,同时其他模块还包含其他的功能。
- [root@master ~]# ansible webservers -m shell -a "sleep 10" -i /etc/ansible/hosts
-
- [root@node1 tmp]# ls ansible-tmp-1656102874.99-71725-64844177037053/
- AnsiballZ_command.py
- [root@node1 tmp]# pwd
- /root/.ansible/tmp
使用 ad-hoc 执行一次远程命令,注意观察返回结果的颜色;
- [root@master ~]# mkdir -p project
- [root@master ~]# cd project/
- [root@master project]# cp /etc/ansible/ansible.cfg .
- [root@master project]# cp /etc/ansible/hosts .
- [root@master project]# ls
- ansible.cfg hosts
现在项目读取的配置为 /root/project/ansible.cfg
- [root@master project]# ansible --version
- ansible 2.9.27
- config file = /root/project/ansible.cfg
- configured module search path = [u'/root/.ansible/plugins/modules', u'/usr/share/ansible/plugins/modules']
- ansible python module location = /usr/lib/python2.7/site-packages/ansible
- executable location = /usr/bin/ansible
- python version = 2.7.5 (default, Nov 16 2020, 22:23:17) [GCC 4.8.5 20150623 (Red Hat 4.8.5-44)]
- [root@master project]# vim ansible.cfg
- inventory = /root/project/hosts #这里可以写绝对路径,也可以写相对路径/hosts
这里还可以调整forks,1代表一台一台的执行,5代表并发执行5台
forks = 5 #调整并行主机的数量
这个参数在优化的时候可以加大一点,机器是多少台调整为多少台,这样会让执行效果更加快,否则一个一个来
- [root@master project]# ansible webservers -m shell -a "sleep 3" -f 1
- 192.168.111.6 | CHANGED | rc=0 >>
-
- 192.168.111.7 | CHANGED | rc=0 >>
-
- 192.168.111.8 | CHANGED | rc=0 >>
-
-
- [root@master project]# ansible webservers -m shell -a "sleep 3" -f 5
- 192.168.111.8 | CHANGED | rc=0 >>
-
- 192.168.111.7 | CHANGED | rc=0 >>
-
- 192.168.111.6 | CHANGED | rc=0 >>
ansible有着诸多的模块,虽然模块众多,但最为常用的模块也就 20-30个左右
常用ad-hoc: 模块:
0.测试 shell | command
0.下载 get_url
1.安装 yum | yum_repository
2.配置 copy | template
3.初始化 file 创建文件,创建目录,授权
4.用户|组 user group
4.启动 systemd
6.挂载 mount
7.定时任务 cron
8.防火墙 firewalld | iptables
9.文件内容修改 lineinfile