Python + Ansible 动态主机

1,283次阅读
没有评论

共计 1522 个字符,预计需要花费 4 分钟才能阅读完成。

Python + Ansible 动态主机

承接上文 Python+Mongodb 提供服务器信息,基本实现根据项目标签过滤主机,本篇文章则聊聊如何对接 Ansible

Ansible动态主机列表

动态主机 Demo

#!/usr/bin/env python2

'''
Example custom dynamic inventory script for Ansible, in Python.
'''

import os
import sys
import argparse

try:
    import json
except ImportError:
    import simplejson as json

class ExampleInventory(object):

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

        # Called with `--list`.
        if self.args.list:
            self.inventory = self.example_inventory()
        # Called with `--host [hostname]`.
        elif self.args.host:
            # Not implemented, since we return _meta info `--list`.
            self.inventory = self.empty_inventory()
        # If no groups or vars are present, return empty inventory.
        else:
            self.inventory = self.empty_inventory()

        print json.dumps(self.inventory);

    # Example inventory for testing.
    def example_inventory(self):
        return {
            'groupname1': {
                'hosts': ['192.168.77.129', '192.168.77.130'],
                'vars': {
                    'ansible_ssh_user': 'root',
                    'ansible_ssh_pass': '123456',
                    'example_variable': 'value'
                }
            },
            '_meta': {
                'hostvars': {
                    '192.168.77.129': {
                        'host_specific_var': 'foo'
                    },
                    '192.168.77.130': {
                        'host_specific_var': 'bar'
                    }
                }
            }
        }

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

    # Read the command line args passed to the script.
    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.
ExampleInventory()

测试主机信息

# 将上述代码保存为myinventory.py,且赋予执行权限
[root@node1 ansible]# chmod +x myinventory.py
[root@node1 ansible]# ansible -i myinventory.py groupname1 --list-host
  hosts (2):
    192.168.77.129
    192.168.77.130
[root@node1 ansible]# 

正文完
 
xadocker
版权声明:本站原创文章,由 xadocker 2020-12-27发表,共计1522字。
转载说明:除特殊说明外本站文章皆由CC-4.0协议发布,转载请注明出处。
评论(没有评论)