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.

AnujAroshA
  • 193
  • 1
  • 2
  • 7

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
  • 19,757
  • 8
  • 52
  • 79
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
  • 1
  • 6
  • 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. – AnujAroshA Jul 07 '20 at 03:15