注本文仅针对 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_listexampledev@192.168.1.20,注意这里要有逗号script脚本形式,参考 dynamic inventoryyamlyaml,yml 参考 inventoryiniini 文件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)