首页 > 解决方案 > 使用 ansible api 时将字典传递给复制模块

问题描述

我正在使用 ansible API 来自动化一些任务。该脚本将主机列表作为参数

使用本地python库将生成一些主机独有的内容,然后使用复制模块创建播放,并希望将字典键传递给内容以避免在控制ansible主机上创建临时文件

不知何故,复制模块无法正确扩展变量inventory_hostname甚至ansible_nodename

我想我已经尝试了所有单引号,没有,有/没有大括号。

from custom lib import generate_content
file_content = {}
for hostname in hostnames:
    file_content[hostname] = generate_content(hostname)

loader = DataLoader()
passwords = { }

context.CLIARGS = ImmutableDict(tags={}, listtags=False, listtasks=False, listhosts=False, syntax=False, connection='ssh',
                    module_path=None, forks=100,  private_key_file=None,
                    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=True, check=False, start_at_task=None)


Inventory = InventoryManager(loader=loader, sources=my_inv)

variable_manager = VariableManager(loader=loader, inventory=Inventory, version_info=CLI.version_info(gitinfo=False))

play_source =  dict(
        name = "Ansible Play",
        hosts = 'all',
        gather_facts = 'yes',
        tasks = [
            dict(action=dict(module='debug', args=dict(msg='{{inventory_hostname}}'))),
            dict(action=dict(module='copy', content=file_content[inventory_hostname], dest='/etc/content', backup='yes'))
         ]
    )

play = Play().load(play_source, variable_manager=variable_manager, loader=loader)


tqm = None
try:
    tqm = TaskQueueManager(
              inventory=Inventory,
              variable_manager=variable_manager,
              loader=loader,
              passwords=passwords,
              stdout_callback="default",
          )
    result = tqm.run(play)
finally:

    if tqm is not None:
        tqm.cleanup()
    shutil.rmtree(C.DEFAULT_LOCAL_TMP, True)

调试模块确实正确地扩展了inventory_hostname变量,但在作为内容或复制模块的键传递时却没有。

有没有办法做到这一点?如果我把inventory_hostname 没有single_quotes 我得到这个错误:

    dict(action=dict(module='copy', content=file_content[inventory_hostname], dest='/etc/content', backup='yes'))
NameError: name 'inventory_hostname' is not defined

如果我使用单引号或双引号,我会得到一个 KeyError:

    dict(action=dict(module='copy', content=file_content["inventory_hostname"], dest='/etc/content', backup='yes'))
KeyError: u'inventory_hostname'

有大括号的事实不会改变问题和错误。

使用 python 2.7

标签: pythonansible

解决方案


推荐阅读