首先在 inventory 的配置文件 / etc/ansible/hosts 里定义一个主机组, 内容如下:
vim /etc/ansible/hosts
(1) 我们先来 ping 一下, 看下两台主机的连通情况
ansible web_server -m ping
(2) 查看 web_server 组下有哪些主机
ansible web_server --list
(3) 查看一台主机的内存使用情况
命令格式: ansible < 主机或主机组 > -a "shell 命令"
注: 执行一条命令使用 - a 参数, 后面跟 shell 命令
ansible 192.168.2.205 -a "free -h"
(4) 在 web_server 组批量创建一个普通用户
ansible web_server -a "useradd andy"
(5) 重启所有主机的 httpd 服务
命令格式: ansible < 主机组 > -m < 模块名称 > -a < 指定执行参数 >
注: 使用 all 参数就是对 hosts 文件里配置的所有主机执行命令
ansible all -m service -a "name=httpd state=restarted"
也可以使用 ansible all -a "systemctl restart httpd" 语句, 结果是一样的, 但输出信息不同, 可自行测试看看.
(6) 查看多个组下各主机指定用户的 UID 和 GID
命令格式: ansible < 主机组 1>:< 主机组 2>:< 主机组 3> -a "shell 命令"
ansible http1:http2 -a "id andy"
(7) 排除一个特定组, 在 web_server 组下的不属于 http1 组的主机的 / tmp 目录下新建一个文件
命令格式: ansible '< 主机组 1>:!< 主机组 2>' -a "shell 命令"
注: 执行命令的主机属于 webserver 组, 但不属于 http1 组
ansible 'web_server:!http1' -a "touch /tmp/test.txt"
此时 ansible 会给出一个警告信息, 意思是说 ansible 已经内置有 file 模块, 建议使用 file 模块创建文件, 如果想取消警告信息, 可以修改配置文件 ansible.cfg, 把 command_warnings 参数改成 False, 就不会再给出警告信息了. 其实创建文件可以使用下面这条命令, 结果是一样的, 关于模块的使用后面会讲到.
ansible 'web_server:!http1' -m file -a "dest=/tmp/test.txt state=touch"
(8) 指定两个组的交集, 查看属于 web_server 组又属于 http1 组的主机的负载情况
注:! 表示属于前面的组但不属于后面的组;& 表示即属于前面的组也属于后面的组.
ansible 'web_server:&http1' -a "uptime"
(9) 在即属于 web_server 组又属于 http2 组但不属于 http1 组的主机删除 / tmp/test.txt 文件内容
ansible 'web_server:!http1:&http2' -a "rm -f /tmp/test.txt"
(10) 通配符使用, 查看以 http 开头的所有组的主机的字符编码
ansible http* -a "cat /etc/locale.conf"
(11) 查看以 http 开头的所有组和 web_server 组的所有主机的磁盘使用情况
ansible http*:web_server -a "df -h"
(12) 查看 web_server 组的第一台主机的 hostname
ansible web_server[0] -a "hostname"
(13) 查看 web_server 组的前 5 台主机的当前日期和时间
ansible web_server[0:4] -a "date'+%Y-%m-%d %H:%M:%S'"
(14) 正则表达式使用, 查看以 web 或者 http 开头的组的主机的 httpd 服务的进程 PID
ansible '~(web|http)*' -a "pidof httpd"
(15) 其它正则表达式例子
来源: http://blog.51cto.com/andyxu/2147856