pyramid13
pyramid13

Reputation: 286

How to create array template in Ansible?

I have a template file config.j2:

 {% for host in groups['dbs'] %}
 ips= {{ hostvars[host].ansible_default_ipv4.address }}
 {% endfor %}

My output is:

   ips= 192.168.231.91
   ips= 192.168.231.92
   ips= 192.168.231.93

I want save in array variable like this:

ips=['192.168.231.91','192.168.231.92','192.168.231.93']

How can do this?

Upvotes: 0

Views: 1948

Answers (1)

techraf
techraf

Reputation: 68469

Solution

ips=[{{ groups['dbs'] | map("regex_replace", "(.*)", "'\\1'") | join(",") }}]

Explanation

  1. Strings ips[ and ] are printed directly in the template;

  2. The Jinja2 expression processes the groups['dbs'] list:

    1. map filter applies a filter (regex_replace) to individual elements of the list;

    2. regex_replace filter surrounds each list element (string) in single quotes;

    3. join filter converts the resulting list to comma-delimited string in the output.

Upvotes: 1

Related Questions