# Ansible execute code when Host is a part of of Group X

**URL:** <https://forum.ansible.com/t/ansible-execute-code-when-host-is-a-part-of-of-group-x/27926>\
**Category:** Ansible Project\
**Created:** [July 1, 2018, 4:56pm UTC](https://forum.ansible.com/t/ansible-execute-code-when-host-is-a-part-of-of-group-x/27926 "2018-07-01T16:56:41Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![VS1](https://avatars.discourse-cdn.com/v4/letter/v/bbe5ce/32.png) [@VS1](https://forum.ansible.com/u/VS1)\
**Post date:** [July 1, 2018, 4:56pm UTC](https://forum.ansible.com/t/ansible-execute-code-when-host-is-a-part-of-of-group-x/27926/1 "2018-07-01T16:56:41Z")

</div>

Hello, I want to make a code that will execute on all my webserver but some part of my webserver i want to execute only on a specific machine from the webserver list ot when that machine is also part of group of [mainws] or [secondaryws]

`  
webservers:  
1.1.1.1  
2.2.2.2

mainws  
1.1.1.1

secondary  
2.2.2.2  
`

`  
-host webservers

tasks:

- name: execute task  
…  
when: \>  
host : IP or group or some varialbe

`

How can i write the when part in order to ran my task only on the mainws ?

---

<div class="post-metadata">

**Author:** ![Kai\_Stian\_Olstad](https://avatars.discourse-cdn.com/v4/letter/k/e19adc/32.png) [@Kai\_Stian\_Olstad](https://forum.ansible.com/u/Kai_Stian_Olstad)\
**Post date:** [July 1, 2018, 5:08pm UTC](https://forum.ansible.com/t/ansible-execute-code-when-host-is-a-part-of-of-group-x/27926/2 "2018-07-01T17:08:07Z")

</div>

when: inventory\_hostname in groups['mainws']

---

<div class="post-metadata">

**Author:** ![mhalano](https://sea1.discourse-cdn.com/ansible/user_avatar/forum.ansible.com/mhalano/32/1815_2.png) [@mhalano](https://forum.ansible.com/u/mhalano)\
**Post date:** [July 2, 2018, 8:30pm UTC](https://forum.ansible.com/t/ansible-execute-code-when-host-is-a-part-of-of-group-x/27926/3 "2018-07-02T20:30:08Z")

</div>

The Kai answer was perfect, but could be useful (may be to this problem or may be later) this page, which shows patterns for the groups definitions: [https://docs.ansible.com/ansible/latest/user\_guide/intro\_patterns.html](https://docs.ansible.com/ansible/latest/user_guide/intro_patterns.html)
