Ansible Inventory 主机清单的作用、使用方法及示例详解

在 Ansible 中,inventory 主机清单是一个文件包含了由管理工具 ansible
进行操作的远程主机列表。它定义了要对哪些主机执行操作,以及如何连接到这些主机。Ansible 支持多种不同的 inventory 格式,例如
INI 格式和 YAML 格式。
我的博客 https://blog.itwk.cc/

使用 inventory 主机清单的好处有:

  1. 提供了一个中心化的配置文件,可以方便地对大量主机执行操作,便于管理和维护。

  2. 可以为不同的主机组定义不同的配置,以便为特定的主机或主机组指定不同的变量和任务。

  3. 可以使用动态 inventory 脚本,根据外部数据源(如云服务提供商)动态生成 inventory 清单,实现更灵活的主机管理。

使用 inventory 主机清单的方法有:

  1. INI 格式清单文件

在 ini 格式文件中,使用每个主机作为 header,为每个主机配置相应的变量。以下是一个基本的示例:

[webservers]
web1.example.com
web2.example.com

[dbservers]
db1.example.com
db2.example.com
  1. YAML 格式清单文件

使用 YAML 文件格式,可以更加灵活地定义 inventory 主机清单,以下是一个示例:

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:
  1. 动态 inventory

除了静态清单文件之外,Ansible 支持动态 inventory 脚本,使用这种方式可以按需生成主机列表,以下是一个示例:

#!/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))

以上是使用 Ansible inventory 主机清单的基本内容,通过定义适当的 inventory 文件可以更加灵活地控制远程主机的管理和操作。

猜你喜欢

转载自blog.csdn.net/qq_34185638/article/details/131079330