DEV Community

Jace
Jace

Posted on

Ansible notes: group_names

In ansible, group_names is a list (array) of all the groups the current host is in.

This can be used in templates using Jinja2 syntax to make template source files that vary based on the group membership (or role) of the host:

{% if 'webserver' in group_names %}
   # some part of a configuration file that only applies to webservers
{% endif %}

For example, If I must run a task for certain host in the group of hosts.

And the inventory hosts file shown as follows.

[all]
node1  ip=192.168.1.1
node2  ip=192.168.1.2

[delpy_infra]
node1
node2

[special]
node2

And here's the task.
You can use group_names to specify the certain host.

- name: Speciall ops for special nodes
  command: "/usr/bin/special.sh"
  when: "'special' in {{ group_names }}"

Top comments (1)

Collapse
 
alesidorov profile image
alesidorov

It is correct to write like this:
when: "'special' in group_names"