Siva
Siva

Reputation: 113

How to use different host group for each module in ansible playbook

I have two host groups in the ansible host file.

[hostGroup1]
host1
host2

[hostGroup2]
host3
host4

I have a playbook with two modules, let's say a copy module and a systemd module.

how to make the playbook to run the copy module only for hostGroup1 and systemd module only for hostGroup2

Upvotes: 1

Views: 551

Answers (2)

gary lopez
gary lopez

Reputation: 1954

If you want to use just one play you can write like this:

- name: Just 1 play
  hosts: hostgroup1,hostgroup2
  tasks:
  - debug: var=inventory_hostname
    when: 'hostgroup1' in group_names

  - debug: var=inventory_hostname
    when: 'hostgroup2' in group_names

group_name is a variable that contains all the groups to which each host belongs, then you could run each tasks in differents groups. You could change the module of the first task by copy module and the module of the second task by the systemd module.

Upvotes: 1

Vijesh
Vijesh

Reputation: 1218

You can write like this:

- name: hostgroup1 tasks
  hosts: hostgroup1
  tasks:
  - debug: var=inventory_hostname

- name: hostgroup2 tasks
  hosts: hostgroup2
  tasks:
  - debug: var=inventory_hostname

Output will be:

PLAY [hostgroup1 tasks] *********************************************************************************************************************************************

TASK [debug var=inventory_hostname] *********************************************************************************************************************************
ok: [host1] => {
    "inventory_hostname": "host1"
}
ok: [host2] => {
    "inventory_hostname": "host2"
}

PLAY [hostgroup2 tasks] *********************************************************************************************************************************************

TASK [debug var=inventory_hostname] *********************************************************************************************************************************
ok: [host3] => {
    "inventory_hostname": "host3"
}
ok: [host4] => {
    "inventory_hostname": "host4"
}

Upvotes: 2

Related Questions