【发布时间】:2022-08-24 02:10:37
【问题描述】:
我正在使用 set_fact 和 hostvars 在剧本中的剧本之间传递变量。我的代码看起来像这样:
- name: Staging play
hosts: localhost
gather_facts: no
vars_prompt:
- name: hostname
prompt: \"Enter hostname or group\"
private: no
- name: vault
prompt: \"Enter vault name\"
private: no
- name: input
prompt: \"Enter input for role\"
private: no
tasks:
- set_fact:
target_host: \"{{ hostname }}\"
target_vault: \"{{ vault }}\"
for_role: \"{{ input }}\"
- name: Execution play
hosts: \"{{ hostvars[\'localhost\'][\'target_host\'] }}\"
gather_facts: no
vars_files:
- \"vault/{{ hostvars[\'localhost\'][\'target_vault\'] }}.yml\"
tasks:
- include_role:
name: target_role
vars:
param: \"{{ hostvars[\'localhost\'][\'for_role\'] }}\"
这种安排几个月来一直没有问题。但是,我们的环境发生了变化,现在我需要获取时间戳并将其传递给角色以及其他变量,因此我进行了以下更改(由 cmets 表示):
- name: Staging play
hosts: localhost
gather_facts: yes # Changed from \'no\' to \'yes\'
vars_prompt:
- name: hostname
prompt: \"Enter hostname or group\"
private: no
- name: vault
prompt: \"Enter vault name\"
private: no
- name: input
prompt: \"Enter input for role\"
private: no
tasks:
- set_fact:
target_host: \"{{ hostname }}\"
target_vault: \"{{ vault }}\"
for_role: \"{{ input }}\"
current_time: \"{{ ansible_date_time.iso8601 }}\" # Added fact for current time
- name: Execution play
hosts: \"{{ hostvars[\'localhost\'][\'target_host\'] }}\"
gather_facts: no
vars_files:
- \"vault/{{ hostvars[\'localhost\'][\'target_vault\'] }}.yml\"
tasks:
- include_role:
name: target_role
vars:
param: \"{{ hostvars[\'localhost\'][\'for_role\'] }}\"
timestamp: \"{{ hostvars[\'localhost\'][\'current_time\'] # Passed current_time to
Execution Play via hostvars
现在,当我执行时,我收到错误,即在执行播放中未定义 \'vault\' hostvars 变量。经过一些实验,我发现在 Staging Play 中设置 \'gather_facts: yes\' 是触发问题的原因。但是,我需要启用gather_facts 才能使用ansible_time_date。我已经通过调试验证了事实正在正确记录,并且可以由分阶段播放中的主机变量调用;只是不在下面的执行播放中。经过数小时的研究,我找不到任何理由来解释为什么在 Staging Play 中收集事实会影响 Execution Play 的 hostvars 或任何关于如何修复它的想法。
归根结底,我需要的只是传递给包含角色的当前时间。任何能够提出在此用例中实际可行的解决方案的人都将赢得本月员工奖。如果您可以使用gather_facts 解释最初的问题,则可以加分。
谢谢!
标签: ansible timestamp ansible-facts hostvars