当没有主机匹配时失败而不是警告

Fail instead of Warning when no hosts are matched

当您在清单中没有任何主机时,运行 剧本只有警告:

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

有没有办法让那个错误而不是警告?

我发现ansible.cfg里面有这个参数:

[inventory]
unparsed_is_failed = True

但只有在没有您尝试使用的清单文件时才会出现 return 错误。它没有查看内容。

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

问:"有没有办法让那个错误而不是警告?"

答:是的。这是。在剧本中测试它。例如

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

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

赠送空库存

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

一个简单的解决方案是:

  1. 创建剧本“main.yml”,例如:
---
# 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. 将主机变量放入 json 文件“var.json”:
{
    "RUNNER": {
        "HOSTNAME": "hostname-to-check"
    },
    "VAR1":{
        "CIAO": "CIAO"
    }
}
  1. 运行命令:
ansible-playbook main.yml --extra-vars="jsonfilename=var.json"

您也可以根据需要调整此解决方案,并使用命令直接传递主机名

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

但在最后一种情况下,请记住放入您的剧本:

hosts: all