3

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.

techraf
  • 64,883
  • 27
  • 193
  • 198
RedBloodMage
  • 77
  • 1
  • 1
  • 5
  • - targets: [{% for ip in host_ips %}'{{ ip }}:5051'{% endfor %}] That got me a little closer the output is: - targets: ['10.0.0.100:9090''10.0.0.200:9090'] I just need the comma in between them so I need to figure that out – RedBloodMage Dec 14 '17 at 18:00

3 Answers3

10
-targets: [{% for ip in host_ips %}'{{ ip }}:5051'{{ "," if not loop.last else "" }} {% endfor %}]
Arbab Nazar
  • 22,378
  • 10
  • 76
  • 82
1
-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"
    ]
}
Christina A
  • 390
  • 1
  • 10
0

There is no need to struggle with Jinja2 loops here. All you need is to apply a transformation for the list elements (for example with map and regex_replace filters):

host_ips | map('regex_replace', '(.*)', '\\1:9090')

With the above construct you can:

  • use it to set a new variable in Ansible:

    - set_fact:
        targets: "{{ host_ips | map('regex_replace', '(.*)', '\\1:9090') | list }}"
    

or "format them in a file using a template" which per your request is a JSON representation of a list:

  • With double quotes in the output:

    - targets: {{ host_ips | map('regex_replace', '(.*)', '\\1:9090') | list | to_json }}
    

    procudes:

    - targets: ["10.0.0.100:9090", "10.0.0.200:9090"]
    
  • If you really need single quotes in the output simply replace them:

    - targets: {{ host_ips | map('regex_replace', '(.*)', '\\1:9090') | list | to_json | regex_replace('"', '\'') }}
    

    produces:

    - targets: ['10.0.0.100:9090', '10.0.0.200:9090']
    
techraf
  • 64,883
  • 27
  • 193
  • 198