Inventory文件

Inventory文件

主机与组

/etc/ansible/hosts 文件的格式与windows的ini配置文件类似:

方括号[]中的是组名,用于对系统进行分类,便于对不同系统进行个别的管理。


一个系统可以属于不同的组,比如一台服务器可以同时属于webserver组合dbserver租。

这时属于两个组的变量都可以这台主机所用,至于变量的优先级关系将于以后的章节中讨论

[root@node01 ~]# cat /etc/ansible/hosts 
[webservers]
192.168.137.3
192.168.137.1
115.236.19.4:9998
[database]
192.168.137.3
[root@node01 ~]# ansible -i /etc/ansible/hosts webservers  -m raw -a 'hostname'
[DEPRECATION WARNING]: DEFAULT_SUDO_USER option, In favor of become which is a generic framework . This feature will be removed in version 2.8. Deprecation 
warnings can be disabled by setting deprecation_warnings=False in ansible.cfg.
192.168.137.3 | SUCCESS | rc=0 >>
node2
Shared connection to 192.168.137.3 closed.


115.236.19.4 | SUCCESS | rc=0 >>
yun-bak
Shared connection to 115.236.19.4 closed.


192.168.137.1 | SUCCESS | rc=0 >>
TLCB-PC
Shared connection to 192.168.137.1 closed.

按行webservers组执行


如果有主机的SSH端口不是标准的22端口,可在主机名之后加上端口号,用冒号分割。

SSH 配置文件中列出的端口号不会在paramiko 连接中使用,会在openssh连接中使用:

端口号不是默认设置时,可明确的表示为:

badwolf.example.com:5309

[root@node01 ~]# ansible 192.168.137.3 -m command -a "hostname"
192.168.137.3 | SUCCESS | rc=0 >>
node2

[root@node01 ~]# ansible -i /etc/ansible/hosts webservers  -m raw -a 'hostname'
192.168.137.3 | SUCCESS | rc=0 >>
node2
Shared connection to 192.168.137.3 closed.


115.236.19.4 | SUCCESS | rc=0 >>
yun-bak
Shared connection to 115.236.19.4 closed.


192.168.137.1 | SUCCESS | rc=0 >>
TLCB-PC
Shared connection to 192.168.137.1 closed.


假设你有一些静态IP地址,希望设置一些别名,但不是在系统的 host 文件中设置,又或者你是通过隧道在连接,那么可以设置如下:

jumper ansible_ssh_port=5555 ansible_ssh_host=192.168.1.50




[root@node01 ~]# cat /etc/ansible/hosts 
[webservers]
192.168.137.3
192.168.137.1
115.236.19.4:9998
[database]
192.168.137.3
192.168.137.1
jumper01 ansible_ssh_port=22 ansible_ssh_host=192.168.137.3
jumper02 ansible_ssh_port=9998 ansible_ssh_host=115.236.19.4
[root@node01 ~]# ansible jumper01 -m command -a "hostname"
jumper01 | SUCCESS | rc=0 >>
node2

[root@node01 ~]# ansible jumper02 -m command -a "hostname"
jumper02 | SUCCESS | rc=0 >>
yun-bak


一组相似的hostname,可简写如下:

[webservers]
www[01:50].example.com
数字的简写模式中,01:50 也可写为 1:50,意义相同.你还可以定义字母范围的简写模式:


[tlcb]
192.168.137.[1:3]
[root@node01 ~]# ansible -i /etc/ansible/hosts tlcb  -m raw -a 'hostname'
192.168.137.1 | SUCCESS | rc=0 >>
TLCB-PC
Shared connection to 192.168.137.1 closed.


192.168.137.2 | SUCCESS | rc=0 >>
node01
Shared connection to 192.168.137.2 closed.


192.168.137.3 | SUCCESS | rc=0 >>
node2
Shared connection to 192.168.137.3 closed.


主机变量:




执行perl 脚本:

[root@node01 ~]#  ansible 192.168.137.3 -m command -a "test.pl"
192.168.137.3 | SUCCESS | rc=0 >>
deff


执行python 脚本:
[root@node01 ~]#  ansible 192.168.137.3 -m command -a "test.py"
192.168.137.3 | SUCCESS | rc=0 >>
py33333

原文地址:https://www.cnblogs.com/hzcya1995/p/13349385.html