【问题标题】:Ansible: How to preserve facts across executions?Ansible:如何在执行过程中保存事实?
【发布时间】:2021-12-25 18:26:42
【问题描述】:

我试图了解如何在多个剧本运行中保留事实。 我有这样的事情:

- name: Host Check
  block:
  - name: Host Check | Obtain System UUID
    shell:
      cmd: >
        dmidecode --string system-uuid
        | head -c3
    register: uuid

  - name: Host Check | Verify EC2
    set_fact:
      is_ec2: "{{ uuid.stdout == 'ec2' }}"
      cacheable: yes

那段代码将is_ec2 保存为事实,并由更大的剧本执行,比如说setup.yml

ansible-playbook -i cloud_inventory.ini setup.yml

但是如果我想运行另一个剧本,比如说test.yml 并尝试访问is_ec2(在同一主机上),我会收到以下错误:

fatal: [factTest]: FAILED! => {"msg": "The task includes an option with an undefined variable. The error was: 'is_ec2' is undefined\n\nThe error appears to be in '/path/to/playbooks/test.yml': line 9, column 7, but may\nbe elsewhere in the file depending on the exact syntax problem.\n\nThe offending line appears to be:\n\n  tasks:\n    - name: Print isEC2\n      ^ here\n"}

我有点困惑,因为虽然我在文档中看到这是可能的,但我无法让它发挥作用。

如果启用了事实缓存,此布尔值会将变量转换为实际的“事实”,该事实也将添加到事实缓存中。 通常此模块创建“主机级变量”并具有更高的优先级,此选项更改创建的变量的性质和优先级(通过 7 个步骤)。 https://docs.ansible.com/ansible/latest/user_guide/playbooks_variables.html#variable-precedence-where-should-i-put-a-variable 这实际上创建了变量的 2 个副本,一个具有高优先级的普通“set_fact”主机变量和一个较低的“ansible_fact”,可通过事实缓存插件进行持久化。这可能会造成与 meta: clear_facts 的交互混淆,因为它会删除 'ansible_fact' 但不会删除主机变量。

【问题讨论】:

    标签: ansible ansible-facts


    【解决方案1】:

    我解决了!

    虽然上面的代码没有任何问题,但为了让它工作,我需要启用事实缓存并指定我想使用的插件。这可以在ansible.cfg 文件中通过添加以下行来完成:

    fact_caching = jsonfile
    fact_caching_connection = /path/to/cache/directory/where/a/json/will/be/saved
    

    之后,我能够在执行过程中访问那些缓存的事实。

    我很想知道 JSON 文件会是什么样子,它似乎包含您可以从 setup 模块和缓存的事实收集的事实:

    ...
    ...
    
        "ansible_virtualization_tech_host": [],
        "ansible_virtualization_type": "kvm",
        "discovered_interpreter_python": "/usr/bin/python3",
        "gather_subset": [
            "all"
        ],
        "is_ec2": true,
        "module_setup": true
    }
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-01-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多