Ansible: Read a single value with key from YAML file

Viewed 2985

I have a yaml file with content like

abc: 123
def: 456
ddd: {{ eee }}
xyz: 789

I try to avoid to load the whole file into vars space, but I need value of 'def' in my playbook. I thought I could use lookup to resolve the problem. But after

lookup('file', 'path/to/file.yaml')

I don't know how to parse the content of file with Ansible to get a value with its key. I tried include_vars, but that one forced me to modify yaml file value like that {{ eee }} to "{{ eee }}", which modified the actual value. Is there a simple way to just read YAML file key values?

1 Answers

Use template to read the file, e.g.

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

gives

  _def: '456'

The variable eee must be defined. See the thread.


Probably, you might want to set a dictionary first, e.g.

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