# How to execute tasks based on group names in ansible

**URL:** <https://forum.ansible.com/t/how-to-execute-tasks-based-on-group-names-in-ansible/19767>\
**Category:** Ansible Project\
**Created:** [November 15, 2015, 11:47am UTC](https://forum.ansible.com/t/how-to-execute-tasks-based-on-group-names-in-ansible/19767 "2015-11-15T11:47:56Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![Adithya\_Khamithkar](https://avatars.discourse-cdn.com/v4/letter/a/e495f1/32.png) [@Adithya\_Khamithkar](https://forum.ansible.com/u/Adithya_Khamithkar)\
**Post date:** [November 15, 2015, 11:47am UTC](https://forum.ansible.com/t/how-to-execute-tasks-based-on-group-names-in-ansible/19767/1 "2015-11-15T11:47:56Z")

</div>

Hi,

I would like to use the when condition to execute tasks based on group names in ansible.

I am using this code snipit

`when: ({{group_names}} == "web-server")`

But it always skips.

Can someone please correct me.

---

<div class="post-metadata">

**Author:** ![sivel](https://sea1.discourse-cdn.com/ansible/user_avatar/forum.ansible.com/sivel/32/1198_2.png) [@sivel](https://forum.ansible.com/u/sivel)\
**Post date:** [November 15, 2015, 3:36pm UTC](https://forum.ansible.com/t/how-to-execute-tasks-based-on-group-names-in-ansible/19767/2 "2015-11-15T15:36:48Z")

</div>

when: ‘“web-server” in group\_names’

group\_names is an array/list so you have to check if ‘web-server’ exists within it.

---

<div class="post-metadata">

**Author:** ![viper233](https://sea1.discourse-cdn.com/ansible/user_avatar/forum.ansible.com/viper233/32/2060_2.png) [@viper233](https://forum.ansible.com/u/viper233)\
**Post date:** [November 16, 2015, 10:59pm UTC](https://forum.ansible.com/t/how-to-execute-tasks-based-on-group-names-in-ansible/19767/3 "2015-11-16T22:59:55Z")

</div>

Have you though about creating another play and just including those tasks under that play?

- hosts: all  
tasks:

- name: do task A  
…

- hosts: webservers  
tasks:

- name: do tasks A only for webservers

I maybe oversimplifying your workflow but it could help decouple your tasks for re-usability later on.

> **(attachments)**
>
> ![Adithya_Khamithkar.png](https://us1.discourse-cdn.com/ansible/original/2X/a/a6330a35926a86652300e56ff85c3293dba69e63.png)
