04-Ansible Inventory,04-ansible


一、概述

由01节可知,当安装完 Ansible 以后,会提供一个默认的管理清单( Inventory ),即 /etc/ansible/hosts 文件。除默认文件外,我们还可以同时使用多个 Inventory 文件,也可以从动态源或云上拉取 Inventory 配置信息。本节介绍 Inventory 文件的书写方法。

二、主机和组

Inventory 是一个静态的 INI 格式的文件,中括号中的字符为组名。其支持将同一主机同时分到多个不同组中。此外,若被管理主机使用了非默认的 SSH 端口,还可以在主机名称之后使用冒号加端口号来标明。

下面为示例:

# 可以直接为IP地址
192.168.128.83

# 同样支持hostname的方式
ansible-demo3

# 同一主机可以分到不同组中
web1.ding.com

ntp.ding.com

# 如果有主机的 SSH 端口不是标准的 22 端口,可在主机名之后加上端口号,用冒号分隔
proxy.ding.com:2222

# [01:50] 表示 01-50 之间的所有数字。即表示 www01.ding.com,www02.ding.com,......, www50.ding.com 的所有主机
www[01:50].ding.com

# [a:f] 表示 a 到 f 之间的所有字母。即表示 db-a.ding.com,db-b.ding.com,......,db-f.ding.com 的所有主机
db-[a:f].ding.com

# 方括号中是组名,用于对主机进行分类管理
[webservers]
web1.ding.com
web2.ding.com

[dbservers]
db1.ding.com
db2.ding.com
db3.ding.com

三、主机变量

可以在定义主机时为其添加主机变量,以便在 Playbook 中使用。

下面为示例:

[webservers]
# 自定义 http_port 的端口号为 801,maxRequestsPerChild 值为 808
web1.ding.com http_port=801 maxRequestsPerChild=808

四、组变量

可以指定组内的所有主机在 Playbook 中使用的变量,等同于逐一给该组下的所有主机赋予这些变量。

下面为示例:

[webservers]
web1.ding.com
web2.ding.com

[webservers:vars]
# 定义 webservers 组下所有主机 ntp_server 的值为 ntp.ding.com
ntp_server=ntp.ding.com
# 定义 webservers 组下所有主机 proxy 的值为 proxy.ding.com
proxy=proxy.ding.com

五、组嵌套和组变量

可以把一个组作为另一个组的子成员(嵌套),以及分配变量给整个组使用。这些变量可以给 ansible-playbook 命令使用,但不能给 ansible 命令使用。

下面为示例:

[apache]
web1.ding.com
web2.ding.com

[nginx]
web3.ding.com
web4.ding.com

# children 表示当前组中存在子组,当我们操作 webservers 组时,相当于同时操作 apache 组和 nginx 组的所有主机
[webservers:children]
apache
nginx

# webservers 组的所有变量,也同时是子组 apache 和 nginx 的变量
[webservers:vars]
ntp_server=ntp.ding.com

关于组嵌套的补充说明:

  • 任何属于子组的成员都自动成为父组的成员。
  • 子组的变量将具有更高的优先级(覆盖父组的变量)。
  • 组可以有多个父母和孩子,但不是循环关系。
  • 主机也可以在多个组中,但只有一个主机实例,合并来自多个组的数据。

六、默认组

有两个默认组:all 和 ungrouped 。

all 包含每个主机。
ungrouped 包含所有没有在分组中的主机。

下面为示例,配置清单包含 3 个主机:

ansible-demo1
[groupA]
ansible-demo2
ansible-demo3

all 包含了所有主机:

[root@ansible-manager ~]# ansible all -m ping
ansible-demo3 | SUCCESS => {
    "changed": false, 
    "ping": "pong"
}
ansible-demo2 | SUCCESS => {
    "changed": false, 
    "ping": "pong"
}
ansible-demo1 | SUCCESS => {
    "changed": false, 
    "ping": "pong"
}

ungrouped 包含了未分组的主机:

[root@ansible-manager ~]# ansible ungrouped -m ping
ansible-demo1 | SUCCESS => {
    "changed": false, 
    "ping": "pong"
}

七、总结

本节介绍了管理清单 Inventory 的书写方法,介绍了如何定义主机、主机组、组变量、组嵌套等。下一节我们学习 Ansible 模块的基本使用。

参考文档:
http://www.ansible.com.cn/docs/intro_inventory.html
http://www.zsythink.net/archives/2509
https://anoyi.com/p/3dfa1ae67c32
《Ansible自动化运维:技术与最佳实践》
《Ansible 权威指南》

相关内容

    暂无相关文章