Inventario dinámico de Ansible

1. La función del inventario dinámico

En las aplicaciones de producción reales, a menudo nos encontramos con situaciones como un rápido desarrollo comercial o un rápido aumento del tráfico. Es necesario agregar docenas o incluso cientos de servidores a la arquitectura en poco tiempo para mejorar la capacidad de procesamiento de toda la arquitectura. En este momento tiempo, la gestión manual de archivos de inventario no solo es ineficaz, sino también muy general.

Dos, código python de inventario dinámico

#! /usr/bin/env python3
import os
import sys
import argparse

try:
    import json
except ImportError:
    import simplejson as json

class ExampleInventory(object):
    # 读取并分析读入的选项和参数
    def read_cli_args(self):
        parser = argparse.ArgumentParser()
        parser.add_argument('--list', action='store_true')
        parser.add_argument('--host', action='store')
        self.args = parser.parse_args()

    # 用于展示效果的JSON格式的Inventory文件内容
    def example_inventory(self):
        return {
            'songxin': {
                'hosts': ['10.3.150.199', '10.3.150.200','10.3.150.201','10.3.152.78'],
            },
            '_meta': {
                'hostvars': {
                    '10.3.150.199': {
                        "ansible_ssh_user": "cedar",
                        "ansible_ssh_port": "52222"
                    },
                    '10.3.150.200': {
                        "ansible_ssh_user": "cedar",
                        "ansible_ssh_port": "52222"
                    },
                    '10.3.150.201': {
                        "ansible_ssh_user": "cedar",
                        "ansible_ssh_port": "52222"
                    },
                    '10.3.152.78': {
                        "ansible_ssh_user": "root",
                        "ansible_ssh_port": "22"
                    }
                }
            }
        }

    # 返回仅用于测试的空Inventory
    def empty_inventory(self):
        return {'_meta': {'hostvars': {}}}

    def __init__(self):
        self.inventory = {}
        self.read_cli_args()

        #定义'--list'选项
        if self.args.list:
            self.inventory = self.example_inventory()
        #定义'--host[hostname]'先项
        elif self.args.host:
            self.inventory = self.empty_inventory()
        #如果没有主机组或变量要设置,就返回一个空Inventory
        else:
            self.inventory = self.empty_inventory()

        print(json.dumps(self.inventory))

ExampleInventory()

Supongo que te gusta

Origin blog.51cto.com/12965094/2608200
Recomendado
Clasificación