1. 程式人生 > >ansible資產配置

ansible資產配置

參考連結:https://www.cnblogs.com/iois/p/6403761.html

 

ansible主機組的使用,我們在對一個叢集進行管理的時候叢集會有很多角色,在執行統一命令操作的時候我們需要對所有組進行批量操作,這個時候就需要我們的主機組了

 

1)主機組怎麼配置呢?

Inventory檔案遵循ini檔案風格,[]標記分組,方便對機器列表的管理

 

vim /etc/ansible/hosts檔案

#inventory file例子,可在這裡新增主機名hostname或者ip地址

#未分組的主機,新增在最前面

122.19.45.201

hostname1

122.19.45.[1:10] #[1:10]表示所有1~10之間的數字,表示一組ip地址45.1、45.2、... #分組管理的主機,以便對不同主機進行不同的管理,同一主機可同時屬於不同組

[test0] #組名

122.28.13.100

122.19.61.68:5030 #如果主機ssh埠不是22,可在地址後加:指定

[targets1]

localhost ansible_connection=local 122.28.13.10 ansible_connection=ssh ansible_ssh_user=user #指定連線型別和連線使用者名稱

 

[targets2] #可配置主機變數

host1 http_port=80 host2 http_port=80 var2=xxx var3=xxx

 

[targets2:var] #新增關鍵字var,配置組變數,對屬於該組的所有主機都適用

var4=xxx

var5=xxx

 

[targets3:children] #新增關鍵字children,把組作為其他組的子成員

targets1

targets2

 

2)主機組配置後怎麼使用呢?

定義好inventory(資產)檔案後,通過

1. 命令列: ansible <host-pattern> [options]

2. playbook: - hosts <host-pattern>

 

其中<host-pattern>部分指定對哪些機器或分組執行任務

ansible targets1 -m shell -a "hostname"

 

3)主機類別的正則匹配有哪些呢?

ansible支援主機列表的正則匹配

  • 全量: all/*
  • 邏輯或: :
  • 邏輯非: !
  • 邏輯與: &
  • 切片: []
  • 正則匹配: 以~開頭

 

ansible all -m ping #所有預設inventory檔案中的機器

ansible "*" -m ping #同上

ansible 121.28.13.* -m ping #所有122.28.13.X機器

ansible web1:web2 -m ping #所有屬於組web1或屬於web2的機器

ansible web1:!web2 -m ping #屬於組web1,但不屬於web2的機器

ansible web1&web2 -m ping #屬於組web1又屬於web2的機器

ansible webserver[0] -m ping #屬於組webserver的第1臺機器

ansible webserver[0:5] -m ping #屬於組webserver的第1到4臺機器

ansible "~(beta|web)\.example\.(com|org)" -m ping