Ansible:从 YAML 文件中读取带有键的单个值

Gar*_*521 8 ansible

我有一个 yaml 文件,内容如下

abc: 123
def: 456
ddd: {{ eee }}
xyz: 789
Run Code Online (Sandbox Code Playgroud)

我尝试避免将整个文件加载到 vars 空间中,但我需要在我的剧本中使用“def”的值。我想我可以使用查找来解决问题。但是之后

lookup('file', 'path/to/file.yaml')
Run Code Online (Sandbox Code Playgroud)

我不知道如何使用 Ansible 解析文件内容以获取其密钥的值。我尝试了 include_vars,但这迫使我将 yaml 文件值修改为“{{ eee }}”,从而修改了实际值。有没有一种简单的方法来读取 YAML 文件键值?

Vla*_*tka 10

更新

给定文件

shell> cat /tmp/file.yaml 
abc: 123
def: 456
ddd: {{ eee }}
xyz: 789
Run Code Online (Sandbox Code Playgroud)

和变量

eee: 999
Run Code Online (Sandbox Code Playgroud)

查找插件文件

  d1: "{{ lookup('file', '/tmp/file.yaml') }}"
Run Code Online (Sandbox Code Playgroud)

给出

  d1: |-
    abc: 123
    def: 456
    ddd: {{ eee }}
    xyz: 789
Run Code Online (Sandbox Code Playgroud)

您必须使用查找插件模板来扩展Jinja模板

  d1: "{{ lookup('template', '/tmp/file.yaml') }}"
Run Code Online (Sandbox Code Playgroud)

给出文字块

  d1: |-
    abc: 123
    def: 456
    ddd: 999
    xyz: 789
Run Code Online (Sandbox Code Playgroud)

使用过滤器from_yaml将其转换为 YAML

  d1: "{{ lookup('template', '/tmp/file.yaml')|from_yaml }}"
Run Code Online (Sandbox Code Playgroud)

给出 YAML 字典

  d1:
    abc: 123
    ddd: 999
    def: 456
    xyz: 789
Run Code Online (Sandbox Code Playgroud)

如果需要,可以声明变量

  _def: "{{ d1.def }}"
  _ddd: "{{ d1.ddd }}"
Run Code Online (Sandbox Code Playgroud)

并显示结果

    - debug:
        msg: |

          def: {{ _def }}
          ddd: {{ _ddd }}
          def: {{ _def|type_debug }}
          ddd: {{ _ddd|type_debug }}

          d1.def: {{ d1.def }}
          d1.ddd: {{ d1.ddd }}
          d1.def: {{ d1.def|type_debug }}
          d1.ddd: {{ d1.ddd|type_debug }}
Run Code Online (Sandbox Code Playgroud)

给出

  msg: |-

    def: 456
    ddd: 999
    def: str
    ddd: str

    d1.def: 456
    d1.ddd: 999
    d1.def: int
    d1.ddd: int
Run Code Online (Sandbox Code Playgroud)

您可以看到属性是整数,但变量是字符串。这是因为扩展必须被引用。如果要将DEFAULT_JINJA2_NATIVEpreserve variable types during template operations设置为True

然后,你得到

  msg: |-

    def: 456
    ddd: 999
    def: int
    ddd: int
  
    d1.def: 456
    d1.ddd: 999
    d1.def: int
    d1.ddd: int
Run Code Online (Sandbox Code Playgroud)

起源

使用模板读取文件,例如

    - set_fact:
        _def: "{{ (lookup('template', 'path/to/file.yaml')|from_yaml).def }}"
      vars:
        eee: 'default'
Run Code Online (Sandbox Code Playgroud)

给出

  _def: '456'
Run Code Online (Sandbox Code Playgroud)

必须定义变量eee 。请参阅线程。


也许,您可能想先设置一本字典,例如

    - set_fact:
        d1: "{{ lookup('template', 'path/to/file.yaml')|from_yaml }}"
      vars:
        eee: 'default'
    - set_fact:
        _def: d1.def
Run Code Online (Sandbox Code Playgroud)