python - 使用 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
解决方案
推荐阅读
- javascript - 如何根据 URL 和 SQL 数据库中的相关值将访问者重定向到特定页面?
- python - 在 Slack 中将链接展开为图像
- drupal-8 - Drupal 8.5.4 所有链接都给出 404 Not Found
- java - 在 TAB 1 的 RecyclerView 中添加数据时更新 TAB 2 Recyclerview
- powershell - Powershell:使用 New-Object cmdlet 创建 PSCredential 对象时出错
- javascript - 具有不同滚动方向的部分
- bash - 如何使用 bash 脚本添加某些单词或单词部分来复制文件的名称?
- java - 端口无效。通过 Selenium 使用 ChromeDriver 和 Chrome 退出 ...org.openqa.selenium.os.OsProcess checkForError
- php - 子查询在 MySQL 工作台中工作,但不是 PHP
- javascript - 循环遍历 HTML 表并添加到数据库