Fail instead of Warning when no hosts are matched

Viewed 2048

when you don't have any hosts in inventory, when running playbook there is only warning:

[WARNING]: provided hosts list is empty, only localhost is available. Note that the implicit localhost does not match 'all'

Is there a way to make that Error instead of Warning?

I find out that there is this parameter in ansible.cfg:

[inventory]
unparsed_is_failed = True

but it will only return error when there is no inventory file which you are trying to use. It didn't look into content.

2 Answers

One simple solution is:

  1. Create the playbook "main.yml" like:
---
# Check first if the supplied host pattern {{ RUNNER.HOSTNAME }} matches with the inventory
# or forces otherwise the playbook to fail (for Jenkins)
- hosts: localhost
  vars_files:
    - "{{ jsonfilename }}"
  tasks:
    - name: "Hostname validation | If OK, it will skip"
      fail:
        msg: "{{ RUNNER.HOSTNAME }} not found in the inventory group or hosts file {{ ansible_inventory_sources }}"
      when: RUNNER.HOSTNAME not in hostvars

# The main playbook starts
- hosts: "{{ RUNNER.HOSTNAME }}"
  vars_files:
    - "{{ jsonfilename }}"

  tasks:
    - Your tasks
...
...
...
  1. Put your host variables in a json file "var.json":
{
    "RUNNER": {
        "HOSTNAME": "hostname-to-check"
    },
    "VAR1":{
        "CIAO": "CIAO"
    }
}
  1. Run the command:
ansible-playbook main.yml --extra-vars="jsonfilename=var.json"

You can also adapt this solution as you like and pass directly the hostname with the command

ansible-playbook -i hostname-to-check, my_playbook.yml

but in this last case remember to put in your playbook:

hosts: all

[WARNING]: provided hosts list is empty, only localhost is available. Note that the implicit localhost does not match 'all'

Q: "Is there a way to make that Error instead of Warning?"

A: Yes. It is. Test it in the playbook. For example

- hosts: localhost
  tasks:
    - fail:
        msg: "[ERROR] Empty inventory. No host available."
      when: groups.all|length == 0

- hosts: all
  tasks:
    - debug:
        msg: Playbook started

gives with an empty inventory

fatal: [localhost]: FAILED! => {"changed": false, "msg": "[ERROR] Empty inventory. No host available."}

Related