# how to loop inventory groups in ansible

**URL:** <https://forum.ansible.com/t/how-to-loop-inventory-groups-in-ansible/34816>\
**Category:** Ansible Project\
**Created:** [March 20, 2021, 4:41pm UTC](https://forum.ansible.com/t/how-to-loop-inventory-groups-in-ansible/34816 "2021-03-20T16:41:55Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![Chetan\_Kumar\_Sriram](https://avatars.discourse-cdn.com/v4/letter/c/9e8a1a/32.png) [@Chetan\_Kumar\_Sriram](https://forum.ansible.com/u/Chetan_Kumar_Sriram)\
**Post date:** [March 20, 2021, 4:41pm UTC](https://forum.ansible.com/t/how-to-loop-inventory-groups-in-ansible/34816/1 "2021-03-20T16:41:55Z")

</div>

Hi I am struck with looping for below requirement.

The mail section has to loop over first group in inventory, check the uptime with the condition of more than 200 days and send mail to only the lab\_email with lab servers only

Next go to 2nd web group check condition and send mail to web\_email with web servers only.

- name: send mail  
hosts: all  
gather\_facts: no  
become: yes  
tasks:
- name: check uptime  
ignore\_errors: yes  
shell: uptime |awk ‘{print $3}’  
register: up\_time
- debug:  
msg: “{{inventory\_hostname}} has {{ up\_time.stdout }} days uptime”
- name: send mail to chetan  
mail:  
host: relay.services  
port: 25

---

<div class="post-metadata">

**Author:** ![system](https://us1.discourse-cdn.com/ansible/original/1X/1882d9a01da5d8996a862359b0913cc568a39b84.svg) [@system](https://forum.ansible.com/u/system)\
**Post date:** [March 23, 2021, 3:55pm UTC](https://forum.ansible.com/t/how-to-loop-inventory-groups-in-ansible/34816/2 "2021-03-23T15:55:45Z")

</div>

You can modify the mail task to send per group:

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;- name: send mail to chetan  
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;mail:  
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;host: relay.services  
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;port: 25

---

<div class="post-metadata">

**Author:** ![Chetan\_Kumar\_Sriram](https://avatars.discourse-cdn.com/v4/letter/c/9e8a1a/32.png) [@Chetan\_Kumar\_Sriram](https://forum.ansible.com/u/Chetan_Kumar_Sriram)\
**Post date:** [March 26, 2021, 1:56am UTC](https://forum.ansible.com/t/how-to-loop-inventory-groups-in-ansible/34816/3 "2021-03-26T01:56:38Z")

</div>

Thanks Brian for the reply,

I will try the same and get back to you.
