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

时间:2020-04-03 09:00:12

标签: ansible ansible-inventory

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

[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

,但是仅当没有要使用的清单文件时,它才会返回错误。它没有考虑内容。

2 个答案:

答案 0 :(得分:1)

一个简单的解决方案是:

  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

答案 1 :(得分:0)

[警告]:提供的主机列表为空,只有localhost可用。请注意,隐式本地主机与“ all”不匹配

Q:“有没有办法使该错误而不是警告?”

A:是的。它是。在剧本中进行测试。例如

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

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

给予空缺库存

致命:[localhost]:失败! => {“更改”:false,“ msg”:“ [错误]空库存。没有可用的主机。”}