Ansible - 清單定義


清單(Inventory)

主機清單(Inventory)

Ansible通過Inventory(可管理的主機集合)對遠端服務器或者主機進行統一操作和管理,默認將主機列在一個文本文件中,這個文件稱爲Inventory文件。

  • 默認的路徑和文件爲:/etc/ansible/hosts
  • 可以通過ANSIBLE_HOSTS環境變量、ansible.cfg文件中inventory參數來指定,或者運行ansible和ansible-playbook時使用-i參數臨時指定
  • 可以有多個 inventory 文件,也可以通過 Dynamic Inventory 動態生成
  • inventory文件爲 INI文件格式,中括號中的字符爲組名。可以將同一個主機同時歸併到多個不同的組中
  • 組名建議使用"_"來連接字符,例如“aaa_bbb_ccc”

Inventory文件

192.168.56.1    # 未分組
test.example.com  
127.0.0.1 ansible_connection=local  # 直接訪問本地主機,而不是通過SSH

[Test]  # 已分組名稱
192.168.56.1
192.168.56.2
192.168.56.[3:4]  # 通過列表方式通配地址
192.168.56.[5:6]  # 多個通配地址
anliven-[a:d].example.com  # 通配主機域名

[Test:vars]  # 定義組變量
ansible_ssh_user="anliven"
ansible_ssh_pass="anliven"
ansible_ssh_port="22"

[Test2]  # 在分組中指定變量
192.168.56.[1:2] ansible_ssh_user=anliven ansible_ssh_pass=Anliven
192.168.56.[3:4] ansible_ssh_user=anliven ansible_ssh_pass=Anliven
192.168.56.[3:4]

[Test3]  # 在分組中切換root用戶 
192.168.56.[1:2] ansible_ssh_port="22" ansible_ssh_user="anliven" ansible_ssh_pass="anliven"  ansible_become_pass="Anliven" 

[Temp]
192.168.56.1:2222  # 指定端口
192.168.56.2 http_port=8080 var1=test1 var2=test2   # 定義主機時爲其添加主機變量以便於在playbook中使用

[Temp:vars]
ansible_ssh_user="anliven"
ansible_ssh_pass="anliven"

[TestGroup:children]  # 嵌套組,TestGroup爲名稱,其他爲固定格式 
Test1
Test2
Test3

[TestGroup:vars]  # 嵌套組的變量只能在ansible-playbook中使用
var1="test1"
var2="123"

[all:vars]  # 類似全局變量,對inventory文件中所有節點都有效
ansible_ssh_port="22"

Inventory內置參數

Ansible Inventory文件中可使用的行爲參數

可以在ansible.cfg中的[defaults]部分更改一些Inventory行爲參數的默認值

Dynamic Inventory

  • 動態Inventory也就是Ansible所有的Inventory文件裏面的主機列表和變量信息都支持從外部拉取,例如CMDB等。
  • 避免主機列表不準確和頻繁大量的手動更新的問題
  • 也可以通過設置ansible.cfg文件中的inventory參數爲一個可執行腳本,將CMDB等其他系統的主機信息同步至Ansible中。
  • 對動態Inventory腳本的參數和輸出必須遵循格式規則

Inventory分割

通過Inventory分割滿足如下需要

  • 按不同業務/系統分割成的多個Inventory文件
  • 同時使用常規Inventory文件和動態Inventory腳本

實現方式

  • 配置ansible.cfg文件的hostfile參數,指定放置inventory文件目錄作爲Inventory,Ansible將合併目錄裏所有文件爲一個完整的Inventory
  • 也可以在命令行中使用-i命令來指定特定的Inventory文件
[defaults]

hostfile = /etc/ansible/inventory  # 指定目錄作爲Inventory

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章