inventory file 與hosts patterns (ansible 機器清單 與 主機匹配模式)


Ansible配置:

ansible有兩個核心配置文件: ansible.cfg 配置文件和Inventory配置文件

  • Ansible.cfg配置文件
  • Inventory機器列表配置

這里介紹Inventory配置文件

Inventory file:

Inventory file 機器清單,ansible用於管理機器節點的配置文件,類似系統的/etc/hosts文件。

默認的配置文件為:/etc/ansible/hosts (新版本默認的Inventory文件好像是 /home/ansible/ansible_hosts)。

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

#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 

ansible ad-hoc 命令的用法為: ansible <host_pattern> [options]
這里先討論host_pattern部分的用法。 [options]部分用簡單的 -m ping來檢測網絡的連通性

Inventory文件的使用例子:

定義好Inventory文件后,通過:

  1. 命令行ansible <host-pattern> [options]
  2. playbook - hosts: <host-pattern>

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

以ansible命令行命令為例:

#使用默認的inventory文件
ansible 121.28.13.100 -m ping # 檢測13.100是否存活(必須在inventory文件中) 
ansible all -m ping           # 檢測所有主機是否存活 
ansible targets1 -m ping      # 檢測組targets1的主機是否存活

#使用指定的inventory文件
ansible all -i my_hosts_list -m ping # -i參數指定inventory文件 

ansible不能操作 沒有在Inventory中定義過的主機**

主機列表的正則匹配

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 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM