ansible中的inventory.ini 文件详解
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
可视化查看主机组结构。