Search code examples
ansiblejinja2

How to loop over Ansible variable names


I'd like to find all variables with the myvar_ prefix and make a shell script that uses their names and contents.

---
- set_fact:
   myvar_a: "a"
   myvar_b: "b"
   myvar_c: "c"

- name: Format Django webapp parameters
  shell: |
    truncate -s0 out.txt
    {% for param in lookup('ansible.builtin.varnames', '^myvar_.+') %}
    echo {{ param }}  >> out.txt
    {% endfor %}

The output is:

m
y
v
a
r
_
a
,
m
y
v
a
r
_
b
,
m
y
v
a
r
_
c

It iterates a string character by character for some reason.

How to get variable names into out.txt?
How to get the contents of these variables to out.txt? (ok, it'll be {{ lookup("vars", param) }})


Solution

  • This happens because the lookup return you a comma separated list of variable names, not a list.

    As demonstrated by the task:

    - debug:
        var: lookup('ansible.builtin.varnames', '^myvar_.+')
      vars:
        myvar_a: a
        myvar_b: b
        myvar_c: c
    

    Which yields:

    ok: [localhost] => 
      lookup('ansible.builtin.varnames', '^myvar_.+'): myvar_a,myvar_b,myvar_c
    

    There are three fixes possible:

    1. use the wantlist=true named argument of the lookup:
      {% for param in lookup(
           'ansible.builtin.varnames', 
           '^myvar_.+', 
           wantlist=true
         ) 
      %}
      
    2. use a query instead of a lookup, as query always returns a list:
      {% for param in query(
           'ansible.builtin.varnames', 
           '^myvar_.+'
         ) 
      %}
      
    3. split the string:
      {% for param in lookup(
           'ansible.builtin.varnames', 
           '^myvar_.+'
         ).split(',') 
      %}