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.
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:If it is possible that there are multiple hosts you could also use
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:
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:
This template line will be resolved to the following string: