New to Ansible - need to pull hostname and ip from facts for template.

222 views
Skip to first unread message

Owen Corcoran

unread,
May 1, 2017, 4:18:24 PM5/1/17
to Ansible Project

Hey all,

Im trying to pull the hostname and ip of the hosts in a specific host group from the facts gathered when the ansibe playbook runs to gather it facts.

Im trying to use the hostname and ip for both my two target hosts to dynamically populate a haproxy config file using the jinja2 templating support

Ive got the templating working perfectly but i cannot find a way to reference these facts and interate over them within the template.

I know in the template we can do

    {% for item in hosts %}
        server name {{ host.name }} {{ host.ip }} check
    {% endfor %}

How can i get the facts i need into either array or dictionary so i can iterate through them and populate the template.

Owen

Dick Davies

unread,
May 2, 2017, 3:21:23 AM5/2/17
to ansible list
You can iterate over the group and access hostvars['server name'].
Assuming your backends are in a group called 'backends'
something like this should work:

{% for host in groups['backends'] %}
{% set h = hostvars[host] %}
server name {{ h.name }} {{ h.ip }} check
{% endfor %}
> --
> You received this message because you are subscribed to the Google Groups
> "Ansible Project" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to ansible-proje...@googlegroups.com.
> To post to this group, send email to ansible...@googlegroups.com.
> To view this discussion on the web visit
> https://groups.google.com/d/msgid/ansible-project/14f3f918-d267-48d2-a242-28d158e960c3%40googlegroups.com.
> For more options, visit https://groups.google.com/d/optout.
Reply all
Reply to author
Forward
0 new messages