Inventory 是 Ansible 的"通讯录"。本文讲静态清单的组织艺术与动态清单,结尾附多环境清单小案例。
一、INI 格式(经典)
# hosts
[web]
web1 ansible_host=192.168.1.10
web2 ansible_host=192.168.1.11
[db]
db1 ansible_host=192.168.1.20
[prod:children] # 子组(合并 web + db)
web
db
[web:vars] # 组变量
http_port=80
二、YAML 格式(推荐)
# hosts.yml
all:
children:
web:
hosts:
web1: { ansible_host: 192.168.1.10 }
web2: { ansible_host: 192.168.1.11 }
vars:
http_port: 80
db:
hosts:
db1: { ansible_host: 192.168.1.20 }
prod:
children:
web:
db:
三、变量优先级
主机变量 > 组变量(后定义的组 > 先定义的)
常见内置变量:
ansible_host 连接地址
ansible_user SSH 用户
ansible_port SSH 端口
ansible_ssh_private_key_file 私钥
ansible_become 是否 sudo
ansible_python_interpreter Python 路径
四、inventory 目录(多文件合并)
inventory/
├── hosts.yml # 主机
├── group_vars/
│ ├── all.yml # 全局变量
│ └── web.yml # web 组变量
└── host_vars/
└── web1.yml # 单机变量
group_vars / host_vars 目录是变量组织的最佳实践(比 :vars 段清晰)。
五、动态清单
ansible-inventory -i ./hosts.yml --list # 查看解析结果
ansible web --list-hosts # 看组内主机
#!/usr/bin/env python3
# dynamic_inv.py:动态清单脚本(输出 JSON)
import json
inv = {
"web": {
"hosts": ["10.0.0.1", "10.0.0.2"],
"vars": { "http_port": 80 }
},
"_meta": { "hostvars": { "10.0.0.1": { "role": "master" } } }
}
print(json.dumps(inv))
# 使用动态清单
[defaults]
inventory = ./dynamic_inv.py
云环境常用现成插件:aws_ec2、aliyun_ecs、openstack —— 主机增减自动同步。
六、注意
- 主机名只是别名,真实地址用 ansible_host;
- 组名区分环境(prod/staging)比按用途更实用;
- 敏感变量别写清单里(见 Vault 篇);
- 动态清单脚本要有 --list 和 --host 两个输出模式(旧格式)。
七、小案例:多环境清单组织
inventory/
├── prod/
│ ├── hosts.yml
│ ├── group_vars/all.yml # 服务器时区、NTP
│ └── group_vars/web.yml # nginx worker 数
├── staging/
│ ├── hosts.yml
│ └── group_vars/all.yml
└── test_inv.sh
# prod/hosts.yml
all:
children:
web:
hosts:
web-prod-1: { ansible_host: 10.0.1.10 }
web-prod-2: { ansible_host: 10.0.1.11 }
db:
hosts:
db-prod-1: { ansible_host: 10.0.1.20 }
# prod/group_vars/web.yml
http_port: 80
nginx_worker_processes: 4
deploy_env: production
# 按环境跑
ansible all -i inventory/prod/hosts.yml -m ping
ansible-playbook -i inventory/staging/hosts.yml site.yml
ansible-playbook -i inventory/prod/hosts.yml site.yml --check # 演练
目录隔离环境 + group_vars 分层变量 + -i 按环境切换 —— 多环境运维的标准组织。
八、总结
INI/YAML 两格式(YAML 推荐);:children 合组、group_vars/host_vars 目录管变量;ansible-inventory --list 验证;云环境用动态清单插件;按环境分目录。