In Ansible, an inventory host list is a file containing a
list of remote hosts to be manipulated by the management tool ansible. It defines which hosts to perform operations on and how to connect to them. Ansible supports several different inventory formats, such as
INI format and YAML format.
My blog https://blog.itwk.cc/
The benefits of using the inventory host list are:
-
Provides a centralized configuration file that can easily perform operations on a large number of hosts for easy management and maintenance.
-
Different configurations can be defined for different host groups to specify different variables and tasks for specific hosts or host groups.
-
Dynamic inventory scripts can be used to dynamically generate inventory lists based on external data sources (such as cloud service providers) to achieve more flexible host management.
The methods of using the inventory host list are:
- INI format manifest file
In the ini format file, use each host as a header and configure corresponding variables for each host. Here's a basic example:
[webservers]
web1.example.com
web2.example.com
[dbservers]
db1.example.com
db2.example.com
- YAML format manifest file
Using the YAML file format, the inventory host list can be defined more flexibly, the following is an example:
all:
hosts:
webserver1:
ansible_host: 192.168.1.1
ansible_user: root
ansible_ssh_private_key_file: /path/to/private_key
webserver2:
ansible_host: 192.168.1.2
ansible_user: root
ansible_ssh_private_key_file: /path/to/private_key
children:
webservers:
hosts:
webserver1:
webserver2:
dbservers:
hosts:
db1.example.com:
db2.example.com:
- dynamic inventory
In addition to static inventory files, Ansible supports dynamic inventory scripts, which can be used to generate host lists on demand. Here is an example:
#!/usr/bin/env python3
import json
inventory_data = {
}
# 获取主机列表
hosts = get_host_list()
# 将主机列表添加到动态清单中
inventory_data['_meta'] = {
'hostvars': {
}
}
for host in hosts:
inventory_data['_meta']['hostvars'][host['name']] = {
'ansible_host': host['ip_address'],
'ansible_user': 'ubuntu',
'ansible_ssh_private_key_file': '~/.ssh/id_rsa',
}
inventory_data['all'] = {
'hosts': [host['name'] for host in hosts],
'vars': {
'ansible_connection': 'ssh',
'ansible_ssh_common_args': '-o StrictHostKeyChecking=no'
}
}
# 输出清单数据
print(json.dumps(inventory_data))
The above is the basic content of using Ansible inventory host list. By defining appropriate inventory files, you can more flexibly control the management and operation of remote hosts.