3

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.

2 Answers2

1

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",
Gerald Schneider
  • 26,582
  • 8
  • 65
  • 97
0

You're looking for an Ansible "magic variable", specifically "inventory_hostname". You can use it in a jinja2 template like this, using the jinja2 'double brace' variable style:

"wellKnownUrl": "https://{{ inventory_hostname }}/my-configuration",

This template line will be resolved to the following string:

"wellKnownUrl": "https://hp2-3.mydomain.com/my-configuration",
cawwot
  • 221