Chen A.
Chen A.

Reputation: 11280

Build variable name dynamically and access its content with Ansible

I have an ansible playbook, which I need to compare values returned from a task to a variable loaded from metadata file.

This metadata can be in any format, and I decided to go with YAML.

What I'm trying to achieve is to build a variable name from another variable + extra stuff and then lookup this value.

I've searched for answers over the web but I couldn't find any. There are also some similar questions here on SO, but they don't address exactly my issue.

Here's the code:

temp_task.yml

---
  - name: Temp task
    hosts: xenservers
    gather_facts: no
    vars_files:
      - vars/xenservers_metadata.yml

    tasks:
      - command: ls /home  # just a dummy task..
        ignore_errors: yes

      - set_fact: nic={{ inventory_hostname }}.network
      - debug: msg={{ nic }}
      - debug: msg={{ xen_perf.network }}

xenservers_metadata.yml

---
  - xen:
      network:
        - xenbr0: "9b8be49c-....-....-...-..."

I'm trying to get the two debug messages print the same thing. One was constructed dynamically by {{ inventory_hostname }}.network while the other is explicit variable I loaded.

TASK [debug] ********************************************************************************************************************************************************
ok: [xen_perf] => {
    "msg": "xen.network"
}

TASK [debug] ********************************************************************************************************************************************************
ok: [xen] => {
    "msg": [
        {
            "xenbr0": "9b8be49c-....-....-...-..."
        }
    ]
}

The first debug just prints the string. The second prints the actual data I need. How can I achieve the second data output by constructing the variable/attribute dynamically?

Upvotes: 0

Views: 1326

Answers (1)

techraf
techraf

Reputation: 68459

You don’t build the variable name dynamically in your example.

All variables (not facts) are stored in vars structure and you can access them this way:

- debug:
    msg: "{{ vars[inventory_hostname].network }}"

Upvotes: 2

Related Questions