Ansible主機和組變數定義

2022-08-18 06:09:12 字數 2226 閱讀 1563

# 把乙個組作為另乙個組的子成員

[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在 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 中,以便跟蹤他們的更新,這是一種非常推薦的方式.

ansible中變數和主機名

groups 資產檔案中的組和主機 group names 用於標識當前正在執行task的目標主機位於的組 inventory hostname 是指inventory資產檔案中的主機的名稱,常用來修改主機名與資產檔案中一致,由於其它一些神秘原因你不想使用自發現的主機名 ansible hostna...

ansible 變數定義和引用 sudo 執行命令

cat etc ansible hosts nodes 10.2.1.232key 232 10.2.1.43 key 43 cat debug.yaml name test how to use command module hosts nodes remote user root gather ...

變數宣告和定義

變數宣告 如果我們沒有特別寫出signed 有符號 或unsigned 無符號 變數預設為signed。所以我們要使用的變數都必須事先宣告過。和 語言的乙個重要區別是,在c 語言中我們可以在源程式中任何地方宣告變數,甚至可以在兩個可執行 excutable 語句的中間宣告變數,而不象在c語言中變數宣...