1. 程式人生 > 其它 >ansible之資源清單

ansible之資源清單


一、清單檔案語法

ansible安裝完成後,在/etc/ansible/目錄下有個hosts檔案,這個檔案就是ansible預設的主機清單的配置檔案,在清單檔案中,可以指定主機名或IP地址,一行一個,也可以是組的形式,組下面包含一個或多個主機,組還可以巢狀,方式很靈活。下面的例子會向你展示這個檔案的寫法。

 #表示單個主機,不屬於任何組
 web.frank.com   
 ​
 #組名為:db-server,組內包含db1.frank.com,db2.frank.com 2個主機
 [db_server]     
 db1.frank.com
 db2.frank.com
 ​
 #組名為:ha,組內有3臺主機,可以寫域名,也可以寫IP地址
 [ha]            
 ha1.frank.com
 192.168.100.10
 192.168.100.11
 ​
 [k8s_master]
 master1.frank.com
 master2.frank.com
 master3.frank.com
 ​
 [k8s_nodes]
 node1.frank.com
 node2.frank.com
 node3.frank.com
 ​
 #通過範圍來簡化,組內包含3臺主機,分別為:etcd1.frank.com,etcd2.frank.com,etcd3.frank.com 使用方法:[start:end]
 [k8s_etcd_cluster]
 etcd[1:3].frank.com 
 ​
 #巢狀組寫法,固定格式:[組名:children]
 [k8s_all:children]      
 master
 nodes
 etced-cluster

這裡有一點需要注意的地方:檔案中的組名儘量用下劃線_代替中橫線-,不然ansible會報警告。 以上介紹了ansible清單檔案的基本寫法和語法格式,是直接寫在了/etc/ansible/hosts檔案裡的,一般來說並不推薦這樣做,而是建個ansible的工作目錄,在這個目錄裡建立一個叫inventory的檔案,把主機清單寫到inventory中,在呼叫時在通過-i INVENTORY指定相應資源。

二、清單檔案相關操作

  • 建立ansible工作目錄

[root@master ansible]# pwd
 /root/ansible
 [root@master ansible]# ls
 ansible.cfg  copy_repo.yml  inventory  pushsshkey.yaml  remove_k8s.yaml  update_kernel.yml  update_vim8.yml  yum_install_etcd_3.yml
  • 編寫inventory

[root@master ansible]# cat inventory 
 [k8s_master]
 master
 node[1:2]
 ​
 [k8s_etcd_cluster]
 master
 node[1:2]
 ​
 [k8s_nodes]
 node[1:3]
  • 驗證主機是否在清單中

    使用 ansible host-or-group -i inventory --list-hosts列出檔案中的受管主機和組

[root@master ansible]# ansible k8s_etcd_cluster -i inventory --list-hosts hosts (3): master node1 node2

使用 ansible all -i inventory --list-hosts 列出所有受管主機

[root@master ansible]# ansible all -i inventory --list-hosts
  hosts (4):
    master
    node1
    node2
    node3

使用 ansible ungrouped -i inventory --list-hosts 列出不屬於某個組的受管主機

[root@master ansible]# ansible ungrouped -i inventory --list-hosts
 [WARNING]: No hosts matched, nothing to do
  hosts (0):

=======================================================================

知識無邊界,交流以長進

如需轉載,請註明出處,謝謝

=======================================================================