How to set a task to run for a specific inventory group

Good morning everyone, this is my hosts file:

web-servers:
hosts:
web01:
ansible_host: x.x.x.x
web02:
ansible_host: x.x.x.x

backend-servers:
hosts:
balance1:
ansible_host: x.x.x.x
balance2:
ansible_host: x.x.x.x
balance3:
ansible_host: x.x.x.x

what is the correct way to call backend group servers? I tried this but it doesn’t work:

when: inventory_hostname in groups[“backend-servers”]

Regards,

Not to sound snippy but did you test it to see?

I usually add a when condition to a debug task to test it.

  • debug: msg=“running on {{ inventory_hostname }}”
    when: inventory_hostname in groups[“backend-servers”]

Then I run the playbook twice - once with the expected group, once with the other group.

$ ansible-playbook my_test_playbook.yml -i backend-servers

running on balance1
running on balance2
running on balance3

$

$ ansible-playbook my_test_playbook.yml -i web-servers
$

This is not actual output … just a mock up.

Walter

For some reason you are evaluating the condition in all servers, shouldn’t you do it in one server?

To be fair, the condition is evaluated on only one server: the Ansible controller. The task is skipped for other hosts in scope for that play.

And you did specifically ask for the task.

Alternatively, you could end the play, and in the same file start a new play that is scoped via “hosts:” to just the host group(s) you’re interested in, and put your task inside that play. That will eliminate the messages about the skipped hosts, because there are none.