Ansible's Dynamic Inventory

1. The role of dynamic inventory

In actual production applications, we often encounter situations such as rapid business development or rapid increase in traffic. It is necessary to add dozens or even hundreds of servers to the architecture in a short time to improve the processing capacity of the entire architecture. At this time, manually Managing Inventory files is not only inefficient, but also very general.

Two, dynamic inventory python code

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

Guess you like

Origin blog.51cto.com/12965094/2608200