Ansible 是一个开源的自动化平台,用于配置管理和部署应用程序。在 Ansible 中,主机列表(也称为清单文件)是一个重要的组成部分,它定义了 Ansible 可以控制的主机。主机列表可以以多种方式编写,以下是一些常见的写法:
INI 格式
– 使用
.ini
文件格式,这是 Ansible 最早支持的格式。
“`ini
[webservers]
server1 ansible_host=192.168.1.101
server2 ansible_host=192.168.1.102
[dbservers]
db1 ansible_host=192.168.1.201
db2 ansible_host=192.168.1.202
2. **YAML 格式** – 使用 `.yml` 或 `.yaml` 文件格式,这是 Ansible 推荐的格式。
“`yaml
all:
children:
webservers:
hosts:
server1:
ansible_host: 192.168.1.101
server2:
ansible_host: 192.168.1.102
dbservers:
hosts:
db1:
ansible_host: 192.168.1.201
db2:
ansible_host: 192.168.1.202
主机范围
– 你可以指定一个 IP 地址范围。
“`yaml
webservers:
{name: server1, ip: 192.168.1.101}
{name: server2, ip: 192.168.1.102}
{name: server3, ip: 192.168.1.103}
”`
使用变量
– 可以在主机列表中使用变量。
“`yaml
webservers:
hosts:
“{{ item }}.yourdomain.com”:
ansible_host: “{{ item }}.yourdomain.com”
with_items:
– server1
– server2
– server3
”`
使用外部文件
– 可以引用外部文件来定义主机。
“`yaml
hosts: !include hosts.yml
”`
使用Ansible Tower/AWX变量
– 如果你使用 Ansible Tower 或 AWX,你可以使用它们的变量。
“`yaml
hosts: “{{ extra_groups.web }}”
”`
使用Ansible Vault加密
– 你可以加密主机列表文件。
$ ansible-vault create hosts.yml
使用Ansible命令行参数
– 也可以在命令行中直接指定主机。
ansible -i “192.168.1.101,192.168.1.102” all -m ping
确保你的主机列表文件路径正确,并且 Ansible 的配置文件
ansible.cfg
中指定了正确的清单文件路径。