Templete statement that can qualify mulitiple inventory_hostname

21 views
Skip to first unread message

Mike Johnston

unread,
Dec 12, 2017, 5:56:39 PM12/12/17
to Ansible Project
I'm trying to figure out how to pass statement that will match multiple hostnames instead of just one.  I know how to do it with a group in the hosts file, but I need it to be something I set in the defaults part of the role.  I'm sure sure the answer is really easy but I'm just getting used to Jinja.   Here's my example...

hosts file:
[group1]
system1
system2
system3

roles/fubar/templates/mytest.j2

{% if inventory_hostname == "server1" %}
This is a test
{% endif %}

This works... but what if I want this line on server1 and server3?  Preferably something a role assigned in defaults/main.yml file like:

ImportantServers: [ 'server1' , 'server3' ]

{% if inventory_hostname in groups[ 'ImportantServers'] %}
This is a test
{% endif %}

That doesn't work however.  I think it's because the groups is referring to the hosts file and not looking at the defaults.   If someone could tell me what I'm doing wrong and not shame me too badly that would be great.

Kai Stian Olstad

unread,
Dec 13, 2017, 12:42:54 AM12/13/17
to ansible...@googlegroups.com
On 12.12.2017 23:56, Mike Johnston wrote:
> *hosts file:*
> [group1]
> system1
> system2
> system3
>
> roles/fubar/templates/mytest.j2
>
> {% if inventory_hostname == "server1" %}
> This is a test
> {% endif %}
>
> This works... but what if I want this line on server1 and server3?
> Preferably something a role assigned in defaults/main.yml file like:
>
> ImportantServers: [ 'server1' , 'server3' ]
>
> {% if inventory_hostname in groups[ 'ImportantServers'] %}
> This is a test
> {% endif %}
>
> That doesn't work however. I think it's because the groups is
> referring to
> the hosts file and not looking at the defaults. If someone could tell
> me
> what I'm doing wrong and not shame me too badly that would be great.

Since ImportantServers is in defaults it's a variable and not a group,
so just lose the groups.
Groups is something you define in inventory or with the module group_by
and add_host.

{% if inventory_hostname in ImportantServers %}
This is a test
{% endif %}

--
Kai Stian Olstad

Mike Johnston

unread,
Dec 13, 2017, 2:13:35 PM12/13/17
to Ansible Project
That was it!  I knew it would be simple...just not that simple.  Thank you Stian. :)
Reply all
Reply to author
Forward
0 new messages