【问题标题】:How to update nested variables in Ansible如何更新 Ansible 中的嵌套变量
【发布时间】:2016-05-05 06:21:09
【问题描述】:

我在 /etc/ansible/facts.d/environment.fact 中存储了一些额外的信息,例如数据库连接详细信息等。

这些作为变量提供,例如ansible_local.environment.database.name。更新数据库名称的最佳方法是什么?

我尝试了 set_fact 模块,但无法正确更新嵌套变量。它只是覆盖了整个 ansible_local 哈希。

- name: Update database name
  set_fact:
  args:
    ansible_local:
      environment:
        database:
          name: "{{ db_name }}"

【问题讨论】:

标签: python ansible


【解决方案1】:

这应该会有所帮助,假设您使用的是 Ansible 2.0 或更早版本。

- set_fact:
    test:
      app:
        in: 1
        out: 2

- set_fact:
    test_new:
      app:
        transform: 3

- set_fact:
    test: "{{test|combine(test_new,recursive=True)}}"

- debug: var=test

combine 是 Ansible 附带的 Jinja2 过滤器。确保在这种情况下使用recursive 参数。

【讨论】:

    【解决方案2】:

    这是默认的 Ansible 行为——在更改部分哈希时覆盖整个哈希。请参阅 ansible.conf:

    # if inventory variables overlap, does the higher precedence one win
    # or are hash values merged together?  The default is 'replace' but
    # this can also be set to 'merge'.
    #hash_behaviour = replace
    

    因此,如果您将其更改为 hash_behaviour = merge,它将按您的预期工作。

    【讨论】:

    • 我刚刚检查了它,它不起作用。这确实适用于变量文件,但不适用于“set_fact”模块。 (v2.1.1.0)
    猜你喜欢
    • 1970-01-01
    • 2015-08-10
    • 1970-01-01
    • 1970-01-01
    • 2020-12-09
    • 2021-03-05
    • 1970-01-01
    • 1970-01-01
    • 2020-09-22
    相关资源
    最近更新 更多