一、概述
由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
hostname
192.168.1.200
[dbservers]
db1.ding.com
db2.ding.com
db3.ding.com
[IDC]
192.168.1.[100:190]
三、主機變量
可以在定義主機時為其添加主機變量,以便在 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"
}