ansible inventory plugin 简单开发

注本文仅针对 ansible2.7.x 不适用 2.8+版本,因为 2.8+ 版本 ansible 做了较大的改动。

ansible python api 主要两个 runner Adhoc, playbook, 其他cli 工具只是锦上添花

options 可用选项:

play_context 文件:
默认 become, become_method, check_mode, become_user, timeout, tags, skip_tags + OPTION_FLAGS
OPTION_FLAGS = ('connection', 'remote_user', 'private_key_file', 'verbosity', 'force_handlers', 'step', 'start_at_task', 'diff',
                'ssh_common_args', 'docker_extra_args', 'sftp_extra_args', 'scp_extra_args', 'ssh_extra_args')

inventory 默认加载以下几个 plugin:

  • host_list example dev@192.168.1.20, 注意这里要有逗号
  • script 脚本形式,参考 dynamic inventory
  • yaml yaml,yml 参考 inventory
  • ini ini 文件
  • auto 如: /etc/ansible/hosts
  • 更多模块请查看 ansible ansible/plugins/inventory 文件夹下的文件
# inventory 实例
sources = ['dev@192.168.1.20,']
sources = ['path/hosts']
sources = ['path/inventory.yml']
inventory = InventoryManager(loader, sources)

写一个简单 inventory plugin, 加载 string yaml,这样我们就可以把 inventory 存在数据库

class ContentInventoryPlugin(InventoryModule):
    NAME = 'yaml'
    def __init__(self):
        super(ContentInventoryPlugin, self).__init__()
        self._original_path = '.'
        self._load_name = 'content_inventory'
    def verify_file(self, path):
        return True
    def parse(self, inventory, loader, path, cache=True):
        try:
            path = path.replace(config.app_root + '/', '')
            super(InventoryModule, self).parse(inventory, loader, path)
            self.set_options()
            try:
                data = yaml.load(path)
                print('paesrser', data)
            except Exception as e:
                raise AnsibleParserError(e)
            if not data:
                raise AnsibleParserError('Parsed empty YAML file')
            elif not isinstance(data, MutableMapping):
                raise AnsibleParserError('YAML inventory has invalid structure, it should be a dictionary, got: %s' % type(data))
            elif data.get('plugin'):
                raise AnsibleParserError('Plugin configuration YAML file, not YAML inventory')
            if isinstance(data, MutableMapping):
                for group_name in data:
                    self._parse_group(group_name, data[group_name])
            else:
                raise AnsibleParserError("Invalid data from file, expected dictionary and got:\n\n%s" % to_native(data))
        except Exception as err:
            print(err)

inventoryManager 特殊处理一下

class Inventory(InventoryManager):
    "这里传的 sources 是文本"
    def __init__(self, loader, sources=None):
        super().__init__(loader=loader, sources=sources)
    def _setup_inventory_plugins(self):
        plugin = ContentInventoryPlugin()
        self._inventory_plugins.append(plugin)

https://juejin.im/post/5e854cbcf265da47c35d6f7f

「点点赞赏,手留余香」

    还没有人赞赏,快来当第一个赞赏的人吧!
0 条回复 A 作者 M 管理员
    所有的伟大,都源于一个勇敢的开始!
欢迎您,新朋友,感谢参与互动!欢迎您 {{author}},您在本站有{{commentsCount}}条评论