Ansible - Group (Host Properties)

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.

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


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

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": [
"group1": [
"group2": [
"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



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


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

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

# or in a directory structure

with the file


Data Science
Data Analysis
Data Science
Linear Algebra Mathematics

Powered by ComboStrap