Ansible 如何避免在没有主机匹配时运行剧本?

Ansible 如何避免在没有主机匹配时运行剧本?,ansible,bamboo,Ansible,Bamboo,用例:用户可以提供主机名并触发playbook运行。如果主机名有输入错误,我希望在“没有匹配的主机”时无法完成playbook运行。我想让它失败,因为我喜欢在运行playbook时检测失败(我用于CD/CI) 我做了相当广泛的研究。当没有主机匹配时,playbook的退出代码为0,这似乎是一种需要的行为。我找到了。我同意一般的行为应该是这样的 因此,我需要对我的用例进行额外检查。我尝试了以下方法: - name: Deploy product hosts: "{{ target_hosts

用例:用户可以提供主机名并触发playbook运行。如果主机名有输入错误,我希望在“没有匹配的主机”时无法完成playbook运行。我想让它失败,因为我喜欢在运行playbook时检测失败(我用于CD/CI)

我做了相当广泛的研究。当没有主机匹配时,playbook的退出代码为0,这似乎是一种需要的行为。我找到了。我同意一般的行为应该是这样的

因此,我需要对我的用例进行额外检查。我尝试了以下方法:

- name: Deploy product
  hosts: "{{ target_hosts }}"
  gather_facts: no
  any_errors_fatal: true

  pre_tasks:
    - name: Check for a valid target host 
      fail: 
        msg: "The provided host is not knwon"
      when: target_hosts not in groups.tomcat_servers
但由于没有主机匹配,playbook将不会运行,这是正常的,但它也以退出代码0结束。这样我的自动化系统(竹子)就不会失败


因此,我正在寻找抛出退出代码的解决方案!=当没有主机匹配时为0。

添加一个在主机匹配时将设置事实的播放,然后在第二个播放中检查该事实:

- name: Check hosts
  hosts: "{{ target_hosts }}"
  gather_facts: no
  tasks:
    - set_fact:
        hosts_confirmed: true
      delegate_to: localhost
      delegate_facts: true

- name: Verify hosts
  hosts: localhost
  gather_facts: no
  tasks:
    - assert:
        that: hosts_confirmed | default(false)

- name: The real play
  hosts: "{{ target_hosts }}"
  # ...

改进了答案。