The group_vars directory can be used to create unique variables for different groups of managed nodes (e.g. target systems). Or, if you have groups of managed nodes in your default hosts file or your own inventory file, you could just as well create unique variables for different groups of managed nodes in your default hosts file or your own inventory file.
Let's say you have the following playbook.
/usr/local/ansible/testing.yml
Let's also say you've a group of Linux servers and a group of Windows servers, like this, and the "foo" variable should contain a value of "Hello" for Linux servers, and a value of "World" for Windows servers.
[linux]
server1.example.com
[windows]
server2.example.com
In this scenario, you could create files in the group_vars directory, like this. In this scenario, the name of the YAML files must be all.yml or match the managed node group name (linux.yml, windows.yml).
/usr/local/ansible/group_vars/all.yml
/usr/local/ansible/group_vars/linux.yml
/usr/local/ansible/group_vars/windows.yml
Or like this. In this scenario, the name of the directory must be "all" or match the managed node group name (linux, windows).
/usr/local/ansible/group_vars/all/example.yml
/usr/local/ansible/group_vars/linux/example.yml
/usr/local/ansible/group_vars/windows/example.yml
Let's say all.yml or /usr/local/ansible/group_vars/all/example.yml contains the following.
foo: Hello World
Let's say linux.yml or /usr/local/ansible/group_vars/all/linux.yml contains the following.
foo: Hello Linux
Let's say windows.yml or /usr/local/ansible/group_vars/all/windows.yml contains the following.
foo: Hello Windows
If /usr/local/ansible/testing.yml contains hosts: all, then the "all" group_vars should be used, so that the "foo" variable contains a value of "Hello World". If both exist, the "all" directory will take precedence over the "all.yml" file.
---
- hosts: all
tasks:
- debug:
var: foo
...
Which should return the following.
TASK [debug]
ok: [server1.example.com] => {
"msg": "Hello World"
}
If /usr/local/ansible/testing.yml contains hosts: linux, then the "linux" group_vars should be used, so that the "foo" variable contains a value of "Hello Linux".
---
- hosts: linux
tasks:
- debug:
var: foo
...
Which should return the following.
TASK [debug]
ok: [server1.example.com] => {
"msg": "Hello Linux"
}