Q: "Set variables for specific hosts in Ansible in the playbook itself, using the global vars."
A: Put the host-specific variables into a global dictionary, e.g. my_hostvars. (De facto, create your own hostvars). For example
- hosts: host-1,host-2
vars:
my_hostvars:
host-1: # < - set vars for host-1 specifically
a_var: yes
host-2: # < - set vars for host-2 specifically
a_var: no
tasks:
- debug:
msg: "{{ my_hostvars[inventory_hostname]['a_var'] }}"
gives
ok: [host-1] =>
msg: true
ok: [host-2] =>
msg: false
It's up to you where you declare the dictionary and how you reference it in the playbook. See Variable precedence: Where should I put a variable?.
Put the variables into your own facts to simplify the access. For example
- set_fact:
my_facts: "{{ my_hostvars[inventory_hostname] }}"
- debug:
var: my_facts.a_var
give
ok: [host-1] =>
my_facts.a_var: true
ok: [host-2] =>
my_facts.a_var: false
You can simplify the access further by setting the variables if needed. (For example, to avoid rewriting a code already using the variables).
- set_fact:
a_var: "{{ my_facts.a_var }}"
b_var: "{{ my_facts.b_var }}"
c_var: "{{ my_facts.c_var }}"
You can use it to set or customize (precedence 19.) the default values if needed. For example,
- set_fact:
a_var: "{{ my_facts.a_var|default('a') }}"
b_var: "{{ my_facts.b_var }}"
c_var: "{{ my_facts.c_var }}"