Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ansible/Jinja2 How to format a list into fields for my config file?

I have the following and keep in mind I do not know how many ips will be in this incoming variable but I am starting with 2 for simplicity.

vars:
  host_ips: ['10.0.0.100', '10.0.0.200']

I'm trying to format them in a file using a template with Ansible.

- targets: ['10.0.0.100:9090', '10.0.0.200:9090']

What syntax in Jinja2 do I use to make the host ips look like the above targets line? I KNOW I have to iterate for sure.

like image 311
RedBloodMage Avatar asked Oct 21 '25 08:10

RedBloodMage


2 Answers

-targets: [{% for ip in host_ips %}'{{ ip }}:5051'{{ "," if not loop.last else "" }} {% endfor %}]
like image 162
Arbab Nazar Avatar answered Oct 23 '25 07:10

Arbab Nazar


-targets: [{% for ip in host_ips %}'{{ ip }}:5051',{% endfor %}]

test.yml playbook:

vars:
  host_ips: ['10.0.0.100', '10.0.0.200','10.0.0.300']
tasks:
  - debug: msg=[{% for ip in host_ips %}'{{ ip }}:5051',{% endfor %}]

ansible-playbook -i localhost test.yml

TASK [debug] *******************************************************************************************
ok: [localhost] => {
    "msg": [
        "10.0.0.100:5051", 
        "10.0.0.200:5051", 
        "10.0.0.300:5051"
    ]
}
like image 45
Christina A Avatar answered Oct 23 '25 07:10

Christina A