Rupesh
Rupesh

Reputation: 880

How a single variable can have different value on the basis of host instance in Ansible?

I am having "appInstanceName": "{{appname_from_template}}" in my ansible template and I am manitaining appname_from_template in my group_vars/all file.

And when deploying I want this {{appname_from_template}} to be replaced with "endpoint_1" on host1 and "endpoint_2" on host2.

But I am not sure how a single variable can have different value based on the instance it's deploying.

Please let me know if there is any way to do? Thanks

Upvotes: 1

Views: 47

Answers (2)

Rupesh
Rupesh

Reputation: 880

I solved this by defining my variables for host1 and host2 in host_vars/host1 and host_vars/host2

Example: for host1
Inside host_vars/host1 file
appname_from_template: endpoint_1

Inside host_vars/host2 file
appname_from_template: endpoint_2

And this worked like charm!

Upvotes: 0

Vladimir Botka
Vladimir Botka

Reputation: 68074

Given the group_vars/all

shell> cat group_vars/all
appname_from_template: endpoint_maintained_in_groupvars_all

you can override the variable appname_from_template on precedence higher than 7. See Understanding variable precedence. " The variable can have different values based on the instance" if you put it into the

  • host_vars in the inventory file (precedence 8) or
  • host_vars in the inventory's directory (precedence 9) or
  • host_vars in the playbook's directory (precedence 10).

For example

shell> cat host_vars/host1
appname_from_template: endpoint_1

shell> cat host_vars/host2
appname_from_template: endpoint_2

Then the playbook

- hosts: host1,host2,host3
  tasks:
    - debug:
        var: appname_from_template

use host_vars for host1 and host2, and group_vars for host3

ok: [host1] => 
  appname_from_template: endpoint_1
ok: [host3] => 
  appname_from_template: endpoint_maintained_in_groupvars_all
ok: [host2] => 
  appname_from_template: endpoint_2

Upvotes: 1

Related Questions