Ansible 的 Inventory 文件编写起来比较随意,支持很多种定义方式,下面简单记录一下支持的定义方式,方便大家日常更灵活的使用。
Inventory 常用定义方式
1.最常用的写法
[gpdb]
mdw ansible_ssh_host=192.168.0.10 ansible_ssh_user="root" ansible_ssh_pass="123456" ansible_ssh_port=22
sdw1 ansible_ssh_host=192.168.0.11 ansible_ssh_user="root" ansible_ssh_pass="123456" ansible_ssh_port=22
最顶上的方括号 gpdb 表示分组,这种写法分别定义了服务器的别名、主机ip、ssh 用户、ssh 密码、ssh 端口。
2.不指定别名的写法
[all]
10.211.55.122 hostname=sdw2
10.211.55.120 hostname=mdw ansible_ssh_port=22
10.211.55.121 hostname=sdw1 ansible_ssh_port=22
172.16.25.129 hostname=app1
这种写法分别定义了主机ip、定义了变量 hostname 这里代表后面要修改成的主机名,ssh 端口,部分定义。
3.连续 IP 的写法
[gpdb]
gpdbgroup ansible_ssh_host=192.168.1.[10:20] ansible_ssh_user="root" ansible_ssh_pass="1234" ansible_ssh_port=22
4.带参数群组的写法
[gpdb]
gpdbgroup ansible_ssh_host=192.168.1.[10:20]
[gpdb:vars]
ansible_ssh_user=root
ansible_ssh_pass="1234"
testvar="test"
这种写法在 gpdb 群组下面定义了一组变量 vars,vars 中分别给固定变量 ansible_ssh_user 和 ansible_ssh_pass 赋值,又定义了一个 自定义变量 testvar,可以看出特别灵活。
5.多群组定义
[gpdb]
name1 ansible_ssh_host=192.168.1.[10:20] ansible_ssh_user="root" ansible_ssh_pass="1234" ansible_ssh_port=22
[web]
name2 ansible_ssh_host=192.168.2.[10:20] ansible_ssh_user="root" ansible_ssh_pass="1234" ansible_ssh_port=22
[test:children]
gpdb
web
定义了三部分,test群组下直接包含了 gpdb 和 web 两个子群组,在两个子群组中,分别定义了各自的服务器信息。
调用方式
1.调用两个主机组的写法
以下 gpdb 和 web 都会被调用
ansible gpdb:web -m ping
2.在一个组不在另一个的写法
以下表示调用在 gpdb 但不在 web 组中的服务器
ansible gpdb:!web -m ping
3.两个组都在的写法
以下表示调用在 gpdb 也在 web 组中的服务器
ansible gpdb:&web -m ping
其他组合方式,可以根据上面的规则自行制定。
End~