0

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.

maheshs
  • 3
  • 2

1 Answers1

0

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.

ViCeNTe
  • 16
  • 1
  • i agree, the variable should be identical for all hosts. but i have two different **vhost.name** for a single host. its host_var file looks as above. in future, i might have three vhost_names for another host. how should i get all the vhost.name for that particular host with its values. – maheshs Jan 12 '23 at 04:45
  • second point is, these are not hostnames. – maheshs Jan 12 '23 at 04:46
  • Well, you define the structure of your variables once you understand the full design. One thing to understand is whether you want to treat all vhosts as hosts (simplifying your design), or you need to treat only the parent as a host and the vhosts as applications. My recommendation would be to treat all of them as hosts, using a playbook for the high-level hosts, and another one for the vhosts. It's basically inventory-engineering. – ViCeNTe May 23 '23 at 09:45