1. 程式人生 > 實用技巧 >Ansible主機和組變數定義

Ansible主機和組變數定義

主機變數

[atlanta]
host1 http_port=80 maxRequestsPerChild=808
host2 http_port=303 maxRequestsPerChild=909

組變數

[atlanta]
host1
host2

[atlanta:vars]
ntp_server=ntp.atlanta.example.com
proxy=proxy.atlanta.example.com

# 把一個組作為另一個組的子成員
[atlanta]
host1
host2

[raleigh]
host2
host3

[southeast:children]
atlanta
raleigh

[southeast:vars]
some_server=foo.southeast.example.com
halon_system_timeout=30
self_destruct_countdown=60
escape_pods=2

[usa:children]
southeast
northeast
southwest
northwest

分檔案定義 Host 和 Group 變數

在 inventory 主檔案中儲存所有的變數並不是最佳的方式.還可以儲存在獨立的檔案中,這些獨立檔案與 inventory 檔案保持關聯. 不同於 inventory 檔案(INI 格式),這些獨立檔案的格式為 YAML.詳見 YAML 語法 .

假設 inventory 檔案的路徑為:

/etc/ansible/hosts

假設有一個主機名為 ‘foosball’, 主機同時屬於兩個組,一個是 ‘raleigh’, 另一個是 ‘webservers’. 那麼以下配置檔案(YAML 格式)中的變數可以為 ‘foosball’ 主機所用.依次為 ‘raleigh’ 的組變數,’webservers’ 的組變數,’foosball’ 的主機變數:

/etc/ansible/group_vars/raleigh
/etc/ansible/group_vars/webservers
/etc/ansible/host_vars/foosball

舉例來說,假設你有一些主機,屬於不同的資料中心,並依次進行劃分.每一個數據中心使用一些不同的伺服器.比如 ntp 伺服器, database 伺服器等等. 那麼 ‘raleigh’ 這個組的組變數定義在檔案 ‘/etc/ansible/group_vars/raleigh’ 之中,可能類似這樣:

---
ntp_server: acme.example.org
database_server: storage.example.org

這些定義變數的檔案不是一定要存在,因為這是可選的特性.

還有更進一步的運用,你可以為一個主機,或一個組,建立一個目錄,目錄名就是主機名或組名.目錄中的可以建立多個檔案, 檔案中的變數都會被讀取為主機或組的變數.如下 ‘raleigh’ 組對應於 /etc/ansible/group_vars/raleigh/ 目錄,其下有兩個檔案 db_settings 和 cluster_settings, 其中分別設定不同的變數:

/etc/ansible/group_vars/raleigh/db_settings
/etc/ansible/group_vars/raleigh/cluster_settings

‘raleigh’ 組下的所有主機,都可以使用 ‘raleigh’ 組的變數.當變數變得太多時,分檔案定義變數更方便我們進行管理和組織. 還有一個方式也可參考,詳見 Ansible Vault 關於組變數的部分. 注意,分檔案定義變數的方式只適用於 Ansible 1.4 及以上版本.

Tip: Ansible 1.2 及以上的版本中,group_vars/ 和 host_vars/ 目錄可放在 inventory 目錄下,或是 playbook 目錄下. 如果兩個目錄下都存在,那麼 playbook 目錄下的配置會覆蓋 inventory 目錄的配置.
Tip: 把你的 inventory 檔案 和 變數 放入 git repo 中,以便跟蹤他們的更新,這是一種非常推薦的方式.