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

22 views
Skip to first unread message

SysAdmin EM

unread,
Jan 26, 2023, 1:12:25 PM1/26/23
to ansible...@googlegroups.com
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,

Rowe, Walter P. (Fed)

unread,
Jan 26, 2023, 1:26:09 PM1/26/23
to ansible...@googlegroups.com
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
--
Walter Rowe, Division Chief
Infrastructure Services, OISM
Mobile: 202.355.4123

--
You received this message because you are subscribed to the Google Groups "Ansible Project" group.
To unsubscribe from this group and stop receiving emails from it, send an email to ansible-proje...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/ansible-project/CAGUDtnkya%3DwVKxwWxs9uxzxw9ti2LPvvaq2mDrz9mFnkY65SYw%40mail.gmail.com.

SysAdmin EM

unread,
Jan 26, 2023, 2:03:35 PM1/26/23
to ansible...@googlegroups.com
For some reason you are evaluating the condition in all servers, shouldn’t you do it in one server?

Todd Lewis

unread,
Jan 26, 2023, 9:26:41 PM1/26/23
to Ansible Project
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.
Reply all
Reply to author
Forward
0 new messages