Search code examples
ansibleansible-2.xansible-inventoryansible-facts

Ansible : evaluate variable inside a variable with register


I have a task where i need to evaluate a variable attribute , where the name is already a vaiable.

here is the scenario :

i'm executing a shell command ( docker ps ) and i'm registering the output in a variable , where the name is already dynamic:

- name : Display running containers for {{apiType}}
  shell: docker ps
  register: docker_containers_{{apiType}}
  when:
    - '"containers" in type'

no i want to display the content of that ouput and not only the string itself , so i need to do something like this:

- name: Display running containers for {{apiType}}
  debug:
   msg: {{docker_containers_{{apiType}}.stdout}}
  when:
    - '"containers" in type'

of course , this : {{docker_containers_{{apiType}}.stdout}} is syntaxically refused

i ve tried this : {{docker_containers_[apiType].stdout}}

but it fails.

Suggestions?


Solution

  • This is a FAQ. You can build a string and use that to index the hostvars for your current host:

    - name: Display running containers for {{apiType}}
      debug:
       msg: "{{ hostvars[inventory_hostname]['docker_containers_' + apiType].stdout}}"
      when:
        - '"containers" in type'
    

    ...this assumes that your docker_containers_... variable is a host fact, rather than, say, something set via group_vars or a vars stanza in your playbook.

    Here's a runnable example:

    - hosts: localhost
      gather_facts: false
      vars:
        apiType: foo
    
      tasks:
        - set_fact:
            docker_containers_foo:
              stdout: "this is foo"
        - set_fact:
            docker_containers_bar:
              stdout: "this is bar"
    
        - name: Display running containers for {{apiType}}
          debug:
            msg: "{{ hostvars[inventory_hostname]['docker_containers_' + apiType].stdout}}"