如何在Ansible v2中运行playbook api

时间:2016-06-13 06:34:01

标签: python ansible ansible-playbook ansible-api

我想通过Ansible V2 python api运行ansible playbook。这是我的方式:

from ansible.parsing.dataloader import DataLoader
from ansible.vars import VariableManager
from ansible.inventory import Inventory
from ansible.executor.playbook_executor import PlaybookExecutor
variable_manager = VariableManager()

loader = DataLoader()

inventory = Inventory(loader=loader, variable_manager=variable_manager,                 host_list='/path/to/inventory')
playbook_path = '/path/to/playbook'

Options = namedtuple('Options', ['listtags', 'listtasks', 'listhosts', 'syntax', 'connection','module_path', 'forks', 'remote_user', 'private_key_file', 'ssh_common_args', 'ssh_extra_args', 'sftp_extra_args', 'scp_extra_args', 'become', 'become_method', 'become_user', 'verbosity', 'check'])

options = Options(listtags=False, listtasks=False, listhosts=False, syntax=False, connection='ssh', module_path=None, forks=100, remote_user='ubuntu', private_key_file=ssh_key_file, ssh_common_args=None, ssh_extra_args=None, sftp_extra_args=None, scp_extra_args=None, become=True, become_method='sudo', become_user='root', verbosity=None, check=False)
variable_manager.extra_vars = {'hosts': 'mywebserver'} 

passwords = {}

pbex = PlaybookExecutor(playbooks=[playbook_path], inventory=inventory,     variable_manager=variable_manager, loader=loader, options=options,     passwords=passwords)
results = pbex.run()

但它无法正常运行并给出错误消息,如下所示:

TASK [jetty : Create default variables for jetty] ******************************
fatal: [172.17.21.52]: FAILED! => {"changed": false, "failed": true, "msg": "AnsibleUndefinedVariable: 'groups' is undefined"}

在此TASKtemplate中有一个变量groups['xxxx']的Jinja2文件。我认为这是Ansible内置的组变量。任何人都可以告诉它为什么会发生以及如何解决它。提前谢谢。

1 个答案:

答案 0 :(得分:4)

加载广告资源后,请将variable_manager设置为使用该广告资源。

来自Python API - Ansible(第19行):

variable_manager.set_inventory(inventory)