Table of Contents

Ansible - Group (Host Properties)

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.

Built-in

There are two built-in groups:

All

The all group contains all host

ungrouped

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

Management

Definition

In an inventory file

[group1]
host1
host2

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

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": []

# all variable
{{ hostvars[groups['groupname'][0]] }}
# the ansible of the first host of the group groupname
{{ hostvars[ groups['groupname'][0] ].ansible_host }}

Variable

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

Inventory Variable

Example:

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

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:

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

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