python Ansible动态库存

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python Ansible动态库存相关的知识,希望对你有一定的参考价值。

#!/usr/bin/env python

'''
This is a python script used for an example of a dynamic inventory script
for use with Ansible.

call it with --list to show list.
call it with --host [hostname] for specific hosts


'''

import os
import argparse
import sys

try:
    import json
except ImportError:
    import simplejson as json


class OurInventory(object):

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

        # This section is called with `--list`.
        if self.args.list:
            self.inventory = self.our_inventory()
        # this section is called with `--host [hostname]`.
        elif self.args.host:
            # We return _meta info `--list` so not complete.
            self.inventory = self.empty_inventory()

        # No vars or group? Return as an empty inventory.
        else:
            self.inventory = self.empty_inventory()

        print json.dumps(self.inventory);

    # This is an example used simply for testing and so we can run a dymanic script without actualy setting up a server
    # 

    def our_inventory(self):
        return {
            'group': {
                'hosts': ['YOURHOST1', 'YOURHOST2', 'YOURHOST3'],
                'vars': {
                    'ansible_user': 'ansible',
                    'test_variable': 'nonspecific_value'
                }
            },
            '_meta': {
                'hostvars': {
                    'YOURHOST1': {
                        'logs_folder': '/var/log'
                    },
                    'YOURHOST2': {
                        'logs_folder': '/var/log2'
                    }
                }
            }
        }

    # Empty inventory for testing.
    def empty_inventory(self):
        return {'_meta': {'hostvars': {}}}

    # Lets take the args passed to us via the command line.

    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()

# Get the inventory.
OurInventory()

以上是关于python Ansible动态库存的主要内容,如果未能解决你的问题,请参考以下文章

python Ansible的Vagrant动态库存脚本

python Ansible动态库存

为啥 Ansible 无法解析我的 azure 动态库存配置文件?

如何在Ansible中使用静态和动态库存

text Ansible基于单个整数动态生成ipam +库存名称

Ansible 清单可以包含另一个清单吗?