DarthShiznit
DarthShiznit

Reputation: 13

Ansible need to make a json list with variables substituted

I have this json file:

}
  "retry_join": ["192.168.100.11","192.168.100.12","192.168.100.14"],
  "server": true,
  "data_dir": "/var/lib/consul",
  "log_level": "INFO",
  "enable_syslog": false,
  "datacenter": "Morrisville",
  "rejoin_after_leave": true,
  "client_addr": "0.0.0.0",
  "bind_addr": "{{ ansible_host }}",
  "advertise_addr": "{{ ansible_host }}"
}

I need to replace this line here with an indeterminate number of hosts from an ansible inventory file like this one from the top header (mville):

    [mville]
swarm000 ansible_host=192.168.100.11
swarm001 ansible_host=192.168.100.12
swarm002 ansible_host=192.168.100.14

[000servers]
swarm000 ansible_host=192.168.100.11

[001servers]
swarm001 ansible_host=192.168.100.12

[002-00xservers]
swarm002 ansible_host=192.168.100.14

So this line here:

"retry_join": ["192.168.100.11","192.168.100.12","192.168.100.14"],

would need to get filled by ansible but I don't know how many hosts their could be so it would need to have the commas in the right place.

I know how to do a for loop like this in ansible:

{% for host in groups['000servers'] %}
*.info;mail.none;authpriv.none;cron.none   @{{ hostvars[host]['ansible_host'] }}
{% endfor %}

how could I apply that?

Thanks!

Upvotes: 1

Views: 18038

Answers (2)

shaps
shaps

Reputation: 1179

I had very much the same issue when building consul. One thing ( A bit off topic, but it's worth sharing ) I would suggest to you is: build small templates, say you have 1 template for the consul servers and one for the list of joins. It will make your life easier and it's a bit more flexible. Consul will include the files in alphabetical order.

To answer your question here's what I did:

// Join local DC agents
{ 
    "start_join": [ {%for host in groups.dc1 %} {% if hostvars[host]['inventory_hostname'] != inventory_hostname %} "{{hostvars[host]['inventory_hostname']}}" {% if not loop.last %}, {%endif%}{%endif%}{%endfor%}]
}

Note, I used the hostnames, but you can simply change inventory_hostname with ansible_host

Hope that helps, let me know if you want me to be more specific on something.

Upvotes: 6

Joshua Conner
Joshua Conner

Reputation: 912

Take a look at the filters available in Ansible. In particular the to_json filter

{{ some_variable | to_json }}

or the join filter

{{ list | join(" ") }}

should be able to help you template those values correctly.

Upvotes: 7

Related Questions