# Fail gracefully if no hosts match

**URL:** <https://forum.ansible.com/t/fail-gracefully-if-no-hosts-match/28886>\
**Category:** Ansible Project\
**Created:** [October 29, 2018, 1:49am UTC](https://forum.ansible.com/t/fail-gracefully-if-no-hosts-match/28886 "2018-10-29T01:49:44Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![Gonzalo\_Servat](https://avatars.discourse-cdn.com/v4/letter/g/71c47a/32.png) [@Gonzalo\_Servat](https://forum.ansible.com/u/Gonzalo_Servat)\
**Post date:** [October 29, 2018, 1:49am UTC](https://forum.ansible.com/t/fail-gracefully-if-no-hosts-match/28886/1 "2018-10-29T01:49:44Z")

</div>

Hi All

I’ve got an Ansible playbook that I’m running against a custom inventory group I’ve created. The issue is that this group may or may not be empty. I only want Ansible to exit non-zero if it ran against a host (or hosts) and any of them failed (standard Ansible behavior), but I don’t want Ansible to exit non-zero if the group is empty (or if the group doesn’t exist).

The reason why I want it to exit 0 if no hosts match is that I’m running it from a CI system and exiting non-zero means the job failed, which is not true in the case of no hosts matching (it just means it had nothing to do).

Any suggestions?

- Gonz

---

<div class="post-metadata">

**Author:** ![vbotka](https://sea1.discourse-cdn.com/ansible/user_avatar/forum.ansible.com/vbotka/32/359_2.png) [@vbotka](https://forum.ansible.com/u/vbotka)\
**Post date:** [October 29, 2018, 5:52am UTC](https://forum.ansible.com/t/fail-gracefully-if-no-hosts-match/28886/2 "2018-10-29T05:52:33Z")

</div>

> 

Running the playbook below with an empty group results in 0 exit code. What am I missing?

- hosts: test99  
pre\_tasks:
- debug: var=play\_hosts  
delegate\_to: localhost

HTH,

-vlado

---

<div class="post-metadata">

**Author:** ![Gonzalo\_Servat](https://avatars.discourse-cdn.com/v4/letter/g/71c47a/32.png) [@Gonzalo\_Servat](https://forum.ansible.com/u/Gonzalo_Servat)\
**Post date:** [October 29, 2018, 12:17pm UTC](https://forum.ansible.com/t/fail-gracefully-if-no-hosts-match/28886/3 "2018-10-29T12:17:53Z")

</div>

Ah, I should have mentioned that in my playbook I have a hosts line like:

hosts: group1,group2,group3

… and then I limit by this custom group I mentioned (which may be empty or not exist at all). That’s when the playbook fails… when the --limit doesn’t match any host at all.

You did, however, give me an idea. By making my hosts like something like:

hosts: group1,group2,group3,&{{ required | default(‘all’) }}

… I can provide the custom group as an extra variable and it works as I need it to. Thanks for replying!

- Gonz
