1.?主機定義
主機是 Ansible 管理的最小單元,可以是 IP 或域名,支持直接定義或附加參數。
基礎語法
# 直接定義主機(IP 或域名)
192.168.1.10
example.com# 定義主機并指定連接參數(如端口、用戶等)
web1.example.com ansible_port=2222 ansible_user=admin
特殊參數(常用)
-
ansible_port
: SSH 端口(默認 22) -
ansible_user
: SSH 用戶名 -
ansible_ssh_private_key_file
: 私鑰路徑 -
ansible_python_interpreter
: 指定 Python 解釋器路徑(如系統默認非 Python3)
2.?主機組
主機組用于邏輯分類,方便批量操作。組名用?[]
?定義,下方列成員。
示例
[web_servers]
web1.example.com
web2.example.com[db_servers]
db1.example.com
db2.example.com ansible_user=postgres # 覆蓋組變量
操作組
# 僅對 web_servers 組執行命令
ansible web_servers -m ping
3.?變量
變量可分配給?主機?或?組,優先級:主機變量 > 子組變量 > 父組變量。
主機變量
# 直接附加到主機行
web1.example.com http_port=80 max_requests=100# 或在下方縮進定義
web1.example.comhttp_port=80max_requests=100
組變量
[web_servers:vars] # 定義組變量
http_port=80
backup_dir=/var/www[all:vars] # 全局變量(所有主機生效)
ansible_python_interpreter=/usr/bin/python3
4.?子組
子組通過?:children
?定義,繼承父組的變量,支持嵌套層級。
示例
# 定義父組 app_servers,包含 web_servers 和 db_servers 子組
[app_servers:children]
web_servers
db_servers# 子組可繼承父組變量
[app_servers:vars]
environment=production
完整示例
# 主機定義
controller ansible_connection=local# 主機組
[web_servers]
web1.example.com
web2.example.com[db_servers]
db1.example.com ansible_user=postgres# 子組
[app_servers:children]
web_servers
db_servers# 組變量
[web_servers:vars]
http_port=80[app_servers:vars]
deploy_env=prod# 全局變量
[all:vars]
ansible_python_interpreter=/usr/bin/python3
注意事項
-
變量優先級:主機變量 > 當前組變量 > 父組變量 >?
all
?組變量。 -
建議將復雜變量拆分到?
group_vars/
?和?host_vars/
?目錄。 -
使用?
ansible-inventory --graph
?可視化查看主機組結構。