How to reference host variable in Ansible template?

I have the following Ansible project structure:

โ”œโ”€โ”€ demo.yml
โ”œโ”€โ”€ hosts
โ”œโ”€โ”€ group_vars
โ”‚   โ””โ”€โ”€ all
โ””โ”€โ”€ roles
    โ”œโ”€โ”€ common
    โ”‚   โ”œโ”€โ”€ tasks
    โ”‚   โ”‚   โ””โ”€โ”€ main.yml
    โ”‚   โ””โ”€โ”€ templates
    โ”‚       โ””โ”€โ”€ init.j2

      

Inside the "hosts" I have:

[primary]
server1
[secondary]
server2

      

Casting /common/templates/init.j2 I want to be able to reference the [primary] group variable . As Ansible uses Jinja2 for its module template . I was directed to this Jinja2 doc .

I tried:

print("{{ group['primary'] }}")

      

But it will return:

['server1']

      

Right now I can only get it in a loop:

{% for host in groups['primary'] %}
    print("{{ host }}")
{% endfor %}

      

It will return what I want:

server1

      

But how do you get this result without using a loop?

+3


source to share


1 answer


Try it...

groups['primary'][0]

      



or just print the group and you can see how the data is stored.

Hope this helps!

+3


source







All Articles