How to pass a group value in inventory file to jinja2 template file in ansible

6,177

If you are absolutely certain that the group only contains a single value, you can use the first() filter on the variable to get the first element from the list:

swarm_hostname: "{{ groups['dockerSwarmManager'] | first }}"

If it is possible that there are multiple hosts you could also use join():

swarm_hostname: "{{ groups['dockerSwarmManager'] | join(',') }}"

This would create a comma separated list, which I assume would be acceptable from your example.

And of course, this also works directly in your JSON template:

"wellKnownUrl": "https://{{ groups['dockerSwarmManager'] | first }}/my-configuration",
Share:
6,177
AnujAroshA
Author by

AnujAroshA

෴ http://anujarosha.lk/ ෴

Updated on September 18, 2022

Comments

  • AnujAroshA
    AnujAroshA over 1 year

    I have an inventory file named hospital.inventory and it contains following group with a single value.

    [dockerSwarmManager]
    hp2-3.mydomain.com
    

    Then I have a file name security.json.j2 inside the folder call templates. In there I want to refer above mentioned value in below placeholder.

    "wellKnownUrl": "https://_placeholder_value_/my-configuration",
    

    Is there any direct way of doing that?

    As an alternative, how I did was declare a variable in main.yml file inside defaults directory and use it.

    swarm_hostname: "\
       {% for host in groups['dockerSwarmManager'] -%}\
       {{host}}\
       {%- if not loop.last %}, {% endif -%}\
       {%- endfor %}"
    

    I don't think it's nice to use a loop just to extract a single value from a group inside the inventory file even though I get the expected output.

  • AnujAroshA
    AnujAroshA almost 4 years
    Thanks for the answer, but in my case this does not work. The reason is, I'm running this script in a cluster (10.16.0.22/23/24) only one time. If I explain more, this script will run on the host 10.16.0.22 but docker swarm recide on 10.16.0.24 Therefor when I use inventory_hostname magic variable it will consider the hostname of 22 server.