Ansible - Group (Host Properties)

> Infrastructure as code > Ansible

1 - About

A host can have one or more group (tag). A group may have also have a group. See Ansible - Child Group (Children|Group of Group)

Groups don’t really survive outside of inventory and host matching because variables are defined to a specific host before a play is run.

Advertising

3 - Built-in

There are two built-in groups:

  • all: all contains every host
  • ungrouped: ungrouped contains all hosts that don’t have a group

3.1 - All

The all group contains all host

3.2 - ungrouped

The ungrouped group contains all hosts that don’t have a group

4 - Management

4.1 - Definition

In an inventory file

hosts.ini
[group1]
host1
host2

4.2 - Task Conditional

Running a task if a server is or not in a group.

group_names is a list

when: 'webserver' not in group_names
# or
when: 'webserver' in group_names
Advertising

4.3 - Built-in groups variable

During execution, you can access the groups information with the built-in groups variable

Example: the first host

{{ groups['groupname'][0] }}
"all": [
	"alias_host"
],
"group1": [
	"alias_host"
],
"group2": [
	"alias_host"
],
"ungrouped": []
  • and with hostvars, you can access the variable. Example
# all variable
{{ hostvars[groups['groupname'][0]] }}
# the ansible of the first host of the group groupname
{{ hostvars[ groups['groupname'][0] ].ansible_host }}

4.4 - Variable

Variable that are defined on the group level can be defined:

4.4.1 - Inventory Variable

Example:

host.ini
[group1:vars]
ntp_server=ntp.atlanta.example.com
proxy=proxy.atlanta.example.com
Advertising

4.4.2 - Variable file (group_vars directory)

Variables for a group may be defined in one file or in multiple file under a directory.

The location of this file is relative to the inventory file path or playbook file path.

Order of precedence if both paths exist:

  • playbook directory (higher priority - chosen first )
  • inventory directory

Syntax:

($INVENTORY_DIR|$PLAYBOOK_DIR)/group_vars/group1.yml # can optionally end in '.yaml', or '.json' or no file extension
# or in a directory structure
($INVENTORY_DIR|$PLAYBOOK_DIR)/group_vars/group1/db_settings.yml
($INVENTORY_DIR|$PLAYBOOK_DIR)/group_vars/group1/cluster_settings

Example with the default inventory location: /etc/ansible/hosts, the structure would be

/etc/ansible/group_vars/group1.yml
# or in a directory structure
/etc/ansible/group_vars/group1/db_settings.yml
/etc/ansible/group_vars/group1/cluster_settings

with the file

group1.yml
---
ntp_server: acme.example.org
database_server: storage.example.org