0

The goal is to limit the group of hosts a play inside a playbook is run on. The below code doesn't limit the groups to group cluster and sometimes the below playbook is run on localhost

- hosts: all:!localhost
  gather_facts: no
  tasks:
    ... 

The inventory file is below:

[localhost]
127.0.0.1  ansible_connection=local
[cluster]
ip1
ip2
ip3

Tried - hosts: cluster, however, play still runs on localhost sometimes.

There's option to limit the groups via cli:

ansible-playbook playbooks/PLAYBOOK_NAME.yml --limit 'all:!localhost'

My goal is to limit groups a play is run on from the playbook source code.

rok
  • 9,403
  • 17
  • 70
  • 126

2 Answers2

0
- name: Ensure dir exists
  file:
    path: example/path
    state: directory
    owner: user
    group: group
    mode: 0755
  when: inventory_hostname in groups['cluster']

The following does the trick. It runs the task only on the group you wish.

when: inventory_hostname in groups['cluster']
Mr ASD
  • 103
  • 1
  • 1
  • 8
0

Then either run on the desired group of hosts

    - hosts: cluster,cluster1,cluster2
      gather_facts: no
      tasks:
      ... 

or in the inventories, you can group the groups of hosts by:

    [cluster]
    ip1
    ip2
    ip3

    [clusters:children]
    cluster
    cluster1 

and then run the playbook on the clusters group

Mr ASD
  • 103
  • 1
  • 1
  • 8