maheshs
maheshs

Reputation: 3

how to call a dictionary variable from ansible host_var to ansible playbook

I have an ansible playbook, which has a variable defined in it like this:

- hosts: dev-web
  become: yes
  vars:
    - web_dir: /opt/abc/example.com/xyz

i want the string inside the variable "/opt/abc/example.com/xyz" dynamically get from the host_var file in host_vars/dev-web. host_var file looks like this:

vhosts:
  dev1:
    name: 'example.com'
  dev2:
    name: 'xyz.com'

Expected outcome dev1 is:

vars:
  web_dir: /opt/abc/"{{ vhosts.dev1.name }}"/xyz

should reflect to

web_dir: /opt/abc/example.com/xyz

and for dev2:

vars:
  web_dir: /opt/abc/"{{ vhosts.dev2.name }}"/xyz

should reflect to
web_dir: /opt/abc/xyz.com/xyz

Any help would be appreciated.

Upvotes: 0

Views: 173

Answers (1)

ViCeNTe
ViCeNTe

Reputation: 16

You have to approach the problem from a different perspective:

  • In the playbook, the variable should be identical for all hosts, i.e. vhost.name, which will take a different value in every host.

  • In the host_vars/ directory, you should have a different file for each host.

File host_vars/dev1:

vhost:
  name: dev1

File host_vars/dev2:

vhost:
  name: dev2

On another note, if possible, I'd rather reuse the real hostname using an automatically generated variable like: ansible_host or inventory_hostname.

Upvotes: 0

Related Questions