在Ansible中,将可管理的服务器集合成为Inventory。因此,Inventory管理便是服务器管理。

hosts文件位置

我们知道,Ansible在执行操作时,首先需要确定对哪些服务器执行操作。默认情况下,Ansible读取/etc/ansible/hosts文件中的服务器配置,获取需要操作的服务器列表。Ansible定义与获取服务器列表的方式比这个要灵活的多。

在Ansible中,有三种方式指定hosts文件:

  1)默认读取/etc/ansible/hosts文件

  2)通过命令行参数的 -i 指定hosts文件

  3)通过ansible.cfg文件的inventory选项

ansible命令的--list-hosts选项用来显示匹配的服务器列表,我们可以通过该参数验证服务器的匹配情况

[heboan@c1 ~]$ ansible test --list-hosts
  hosts (2):
    192.168.88.2
    192.168.88.3

我们在家目录下创建个hosts,然后用-i指定这个hosts

[heboan@c1 ~]$ cat hosts
[test]
192.168.20.1
192.168.20.2
[heboan@c1 ~]$ 
[heboan@c1 ~]$ ansible test -i hosts --list-hosts
  hosts (2):
    192.168.20.1
    192.168.20.2
[heboan@c1 ~]$ 
[heboan@c1 ~]$ ansible test --list-hosts   #默认情况
  hosts (2):
    192.168.88.2
    192.168.88.3

我们也可以在ansible.cfg中通过inventory选项指定hosts文件路径

[heboan@c1 ~]$ cat /etc/ansible/ansible.cfg 
[defaults]
remote_port = 2202
remote_user = heboan
inventory = /home/heboan/hosts
[heboan@c1 ~]$ 
[heboan@c1 ~]$ ansible test --list-hosts
  hosts (2):
    192.168.20.1
    192.168.20.2

灵活定义hosts文件内容

Ansible支持更加灵活的方式定义hosts文件,例如将服务器进行分组,以便对不同的服务器类型进行不同的操作, 如下

mail.heboan.com    #不属于任何一个组

[webservers]
foo.heboan.com
bar.heboan.com

[dbserver]
one.heboan.com
two.heboan.com
three.heboan.com

在服务器匹配时,all或星号是一个特殊的名称,用于匹配所有的服务器

[heboan@c1 ~]$ ansible '*' --list-hosts
  hosts (6):
    mail.heboan.com
    foo.heboan.com
    bar.heboan.com
    one.heboan.com
    two.heboan.com
    three.heboan.com
匹配所有服务器

相关文章: