【问题标题】:Create host-specific facts with an ansible custom module使用 ansible 自定义模块创建特定于主机的事实
【发布时间】:2018-07-03 22:20:59
【问题描述】:

我正在编写一个 ansible 自定义模块,它与 URI 模块具有一些附加功能。 特别是,我希望返回的数据可以作为全局变量或主机特定变量 (其中主机是运行任务的清单主机)。 基于传递给模块的值。

但是,无论我做什么似乎都只能创建一个全局变量。 假设我为 N 个主机运行 playbook,并且只执行一次自定义模块(run_once:是)。

[...]
   - name: Run the custom module and generate output in custom_var
     run_once: yes
     custom_module:
       field1: ...
       field2: ...
       global_data: yes -> yes, to create a global fact called: custom_var

   - name: DEBUG - Print the content of custom_var
     debug: msg="{{ custom_var }}"

这很好用,所有 N 个主机都可以看到 custom_var。 有没有办法只为执行任务的实际主机定义 custom_var?

奇怪的是,我还尝试注册第一个任务的结果如下:

[...]
   - name: Run the custom module and generate output in custom_var
     run_once: yes
     custom_module:
       field1: ...
       field2: ...
       global_data: no -> no, if I don't create any global fact
     register: register_task

   - name: DEBUG - Print the content of custom_var
     debug: msg="{{ register_task }}"

但看起来这也适用于清单中的所有主机(具有相同的内容)。这是预期的行为吗? 还有关于如何使 custom_var 仅可用于实际运行任务的主机的任何想法?

提前致谢!

【问题讨论】:

标签: ansible ansible-facts


【解决方案1】:

是的,这是 run_once: yes 的预期行为,因为它会覆盖主机循环。

设置此选项后,任务仅执行一次(在批次中的第一台主机上),但结果会复制到同一批次中的所有主机。所以你最终会为每个主机定义custom_var/register_task

如果您想要相反,您可以将run_once: yes 更改为条件语句,如:

    when: play_hosts.index(inventory_hostname) == 0

这将只在第一台主机上执行任务,但不会覆盖主机循环(由于条件,仍然跳过其他主机的任务);这种方式注册的事实将仅适用于第一个主机。

【讨论】:

  • 嗨康斯坦丁,谢谢我不知道!我以为我正在从模块创建一个全局事实,但实际上是使用 run_once 使其全局可用。
猜你喜欢
  • 1970-01-01
  • 2015-05-15
  • 2020-02-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-09-08
  • 2021-06-27
  • 1970-01-01
相关资源
最近更新 更多