Ansible Inventory(主机清单)YAML 格式
参考文档:
- 什么是 Ansible Inventory
- YAML 格式 Inventory 基础写法
- 分组、子组、嵌套结构
- 主机变量 / 组变量 写法
- 组变量优先级
- host_vars / group_vars
- 动态 Inventory(简要)
- 生产级 YAML Inventory 模板(含多环境、多机房、多角色)
- 最佳实践十条
- 常见坑(以及怎么避免)
Inventory 是 Ansible 连接目标主机的“清单”,包含:
- 主机 IP / Hostname
- 组(group)与子组(children)
- 变量(host_vars / group_vars)
- SSH 参数、端口、认证方式
- 自定义变量(业务变量)
YAML 格式(inventory.yml)比 INI 格式更直观、层级清晰,是生产推荐格式。
all:
hosts:
web1:
ansible_host: 10.1.1.11
web2:
ansible_host: 10.1.1.12
最小结构:
all:
hosts:
all:
children:
web:
hosts:
web1:
ansible_host: 10.1.1.11
web2:
ansible_host: 10.1.1.12
all:
children:
prod:
children:
web:
hosts:
web1:
ansible_host: 10.1.1.11
db:
hosts:
db1:
ansible_host: 10.1.1.21
在 playbook 或 ad-hoc 中可以用:
ansible web -m ping
ansible db -m ping
ansible prod -m ping
all:
hosts:
node1:
ansible_host: 192.168.1.10
ansible_port: 2222
ansible_user: deploy
all:
children:
web:
vars:
nginx_port: 80
ansible_user: www
hosts:
web1:
ansible_host: 10.1.1.11
web2:
ansible_host: 10.1.1.12
Ansible 变量优先级(高 -> 低):
- Extra vars(-e)
- Host vars(inventory 主机变量)
- Host vars(host_vars/ 目录)
- Group vars(group_vars/ 目录)
- Group vars(inventory)
- Role defaults
- 👉 越“具体”优先级越高
- 👉 ad-hoc 的 -e 永远最高
主机:
host_vars/web1.yml
host_vars/db1.yml
组:
group_vars/all.yml
group_vars/web.yml
group_vars/db.yml
nginx_port: 80
ansible_user: nginx
nginx_port: 8080
host_vars 会覆盖 group_vars。
如果你的主机是动态生成(Kubernetes、OpenStack、AWS、自动扩缩),使用:
- inventory.aws_ec2.yml
- inventory.k8s.yml
- inventory.gcp.yml
例如 EC2:
plugin: amazon.aws.ec2
regions:
- ap-east-1
hostnames:
- tag:Name
执行:
ansible-inventory -i inventory.aws.yml --graph
下面给你 企业级推荐结构模板(支持多环境 + 多机房 + 多角色)。
inventory/
├── prod/
│ ├── inventory.yml
│ ├── group_vars/
│ │ ├── all.yml
│ │ ├── web.yml
│ │ └── db.yml
│ └── host_vars/
│ ├── web1.yml
│ └── db1.yml
├── staging/
└── dev/
all:
vars:
ansible_user: deploy
ansible_ssh_private_key_file: ~/.ssh/id_rsa
timezone: Asia/Shanghai
children:
# ------------------ 多机房结构 ------------------
idc_a:
children:
web:
hosts:
web1:
ansible_host: 10.10.1.11
web2:
ansible_host: 10.10.1.12
db:
hosts:
db1:
ansible_host: 10.10.1.21
idc_b:
children:
web:
hosts:
web3:
ansible_host: 10.20.1.11
cache:
hosts:
redis1:
ansible_host: 10.20.1.31
# ------------------ 按角色分组 ------------------
web:
vars:
service_port: 8080
nginx_worker: 4
db:
vars:
mysql_port: 3306
cache:
vars:
redis_port: 6379
timezone: Asia/Shanghai
ulimit_nofile: 65535
nginx_port: 80
nginx_user: www
nginx_port: 8081
ansible_user + ansible_ssh_private_key_file
- 环境层:prod/staging/dev
- 地域层:idc_a / idc_b
- 角色层:web/db/cache
例如:
- timezone
- mirrors
- ntp servers
如:group_vars/web.yml 放 nginx 变量
如 web1 端口不同
只放主机结构、主机 IP
例如:
common:
children:
web:
db:
AWS/阿里云/K8s 工具自动同步
ansible-inventory -i inventory/prod --graph
错误:
web1: 10.1.1.11
正确:
web1:
ansible_host: 10.1.1.11
变量不能写在 hosts 下:
❌ 错误:
hosts:
vars:
❌:
children:
web:
web1:
必须:
children:
web:
hosts:
web1:
注意名称必须和 inventory 主机名一致。