使用其他字典值在字典中传递变量

Ansible pass variable within dictionary using other dictionary value

当使用另一个字典值作为参数时,如何将包含变量的值分配给字典键。

例子

---
- name: Test vars
  hosts: ['localhost']
  vars:
    foo:
      a: "foo a value"
      b: "{{ a }}"
  tasks:
  - name: Fix owneship and permission issue with sudoers file
    debug:
      msg: Print {{ foo.b }}

我试过以下方法:

vars:
  foo:
    a: " foo a value"
    b: "{{ foo.a }}"
vars:
  foo:
    a: " foo a value"
    b: "{{ foo['a'] }}"
vars:
  foo:
    a: " foo a value"
    b: "{{ a }}"

None 以上作品。

您可以仅使用 YAML 来满足此要求,方法是 node anchor / alias node

在 YAML 语法中,您可以在值前添加一个锚点,然后您可以通过别名节点引用它。

锚由 & 指示符表示:

some_key: $anchor_name value

虽然别名由 * 指示符表示:

some_other_key: *anchor_name

因此,鉴于任务:

- debug:
    var: foo.b
  vars:
    foo:
      a: &foo_a "foo a value"
      b: *foo_a

这会产生预期的结果:

ok: [localhost] => 
  foo.b: foo a value