Ansible: inheriting group variables for sub-groups

Question:

Hello

We have the following: hosts file:

[common]
common-server1
common-server2

[common:children]
servers-group1
servers-group2

[servers-group1]
server1

[servers-group2]
server2

in the folder / file group_vars/servers-group1 users / groups are listed in the create_groups variables with users / groups for this server group.

task:
- hosts: common
...
- name: Create groups
  group: name="{{item.group_name}}" gid="{{item.gid}}"
  with_items:
     - "{{ create_groups }}"

The question is: is it possible in group_vars/all or group_vars/common to set the same create_groups variable with a list of groups / users that should be on all servers?

In other words, some include of the parent group variables file into the sub-group variables file

Thank you for your help

Answer:

You did not give an example of the structure of the create_groups variable, but apparently it is a kind of dictionary of the following form:

create_groups:
  group1:
    group_name: group1
    gid: 123
    ...
  group2:
    group_name: ...

Ansible has a setting so that when a variable is redefined, a value is added instead of a substitution. But it’s better not to do it that way. the setting works at the system level, i.e. the new behavior will be everywhere. Surely some other roles will fall down.

It is better to create another variable, like this:

group_vars/all.yml :

create_groups_common:
  common_group_1:
    group_name: cgroup1
    gid: 321
  ...

When used, you can combine it with groups_common :

task:
- hosts: common
...
- name: Create groups
  group: name="{{item.group_name}}" gid="{{item.gid}}"
  with_items:
     - "{{ create_groups_common | combine(create_groups) }}"

Why create_groups_common first: if you set some key in this variable, in create_groups you can override its value. If you need to concatenate dictionaries recursively (that is, concatenate the values ​​of the same key), use recursive=True .

Read more: Combining hashes / dictionaries .

Scroll to Top