繁体   English   中英

如何仅在需要时在角色内部收集 ansible_facts?

[英]How to gather ansible_facts inside of a role only when needed?

我有这个示例角色,我安装了一些基于操作系统和 package 管理器的软件包:

# THIS IS IN tasks/main.yml
- name: Ensure archlinux-keyring is updated
  community.general.pacman:
    name: archlinux-keyring
    state: latest
    update_cache: yes
  when: ansible_pkg_mgr == "pacman"

如果这个角色作为剧本的一部分运行,Ansible 将收集事实,一切都很好。 但是,如果我将其作为独立角色运行:

ansible localhost -m include_role -a name=examplerole

我收到这个错误

localhost | FAILED! => {
    "msg": "The conditional check 'ansible_pkg_mgr == \"pacman\"' failed. The error was: error while evaluating conditional (ansible_pkg_mgr == \"pacman\"): 'ansible_pkg_mgr' is undefined

我知道我可以强制 Ansible 在角色中收集这些事实,但是一遍又一遍地收集事实会非常慢(因为这是我在多个角色中反复出现的问题,我不能总是将它们包含在剧本中,而且,如果它们在剧本中,则不需要)。

有没有办法检查事实是否已经收集,并仅在需要时将它们收集到角色内部?

关于

...有什么方法可以检查事实是否已经收集...仅在需要时将它们收集到角色内部?

如果您只想根据条件收集事实,您可以查看以下示例

- hosts: localhost
  become: false

  gather_facts: false

  tasks:

  - name: Show Gathered Facts
    debug:
      msg: "{{ hostvars['localhost'].ansible_facts }}"

  - name: Gather date and time only
    setup:
      gather_subset:
        - "date_time"
        - "!min"
    when: ansible_date_time is not defined

  - name: Show Gathered Facts
    debug:
      msg: "{{ ansible_facts }}"

仅收集日期和时间,如果之前未定义。

这意味着,关于

一遍又一遍地收集事实会超级慢

建议熟悉收集到的事实的数据结构和可能的子集,以便只收集需要的信息。 以及缓存事实

更多文档

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM