Ansible - Group (Host Properties)


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.


There are two built-in groups:

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


The all group contains all host


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



In an inventory file


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


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

Inventory Variable



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


Powered by ComboStrap