Ansible:如果主机无法访问,则中止执行 [英] Ansible: Abort Execution if a host is unreachable
问题描述
总结:如果任何主机无法访问,立即中止 ansible playbook 的更好方法.
Summary: A better way for aborting ansible playbook immediately if any host is unreachable.
如果主机中的任何一个无法访问,是否有办法中止 Ansible playbook.我发现如果它无法到达主机,它仍然会继续并执行剧本中的所有剧本/任务.
Is there a way to abort Ansible playbook if any one of the host is unreachable. What I find that if it cannot reach a host it will still continue on and execute all the plays/tasks in the playbook.
我所有的 playbook 都指定 max_fail_percentage 为 0,但在这种情况下 ansible 不会抱怨,因为所有可访问的主机都可以执行所有 play.
All my playbooks I specify the max_fail_percentage of 0, but in this case ansible does not complain since all the hosts that are reachable can execute all the plays.
目前我有一个简单但笨拙的解决方案,但看看是否有更好的答案.
Currently I have a simple but hacky solution, but seeing if there is a better answer.
作为运行 playbook 的第一步,ansible 为所有主机收集事实.如果主机无法访问,它将无法访问.我在剧本的开头写了一个简单的剧本,它将使用一个事实.如果主机无法访问,该任务将因未定义变量错误"而失败.该任务只是一个虚拟任务,如果所有主机均可访问,它将始终通过.
Since the first step as part of running the playbooks, ansible gathers facts for all the hosts. And in case where a host is not reachable it will not be able to. I write a simple play at the very beginning of my playbook which will use a fact. And in case a host is unreachable that task will fail with "Undefined variable error". The task is just a dummy and will always pass if all hosts are reachable.
见下面我的例子:
- name: Check Ansible connectivity to all hosts
hosts: host_all
user: "{{ remote_user }}"
sudo: "{{ sudo_required }}"
sudo_user: root
connection: ssh # or paramiko
max_fail_percentage: 0
tasks:
- name: check connectivity to hosts (Dummy task)
shell: echo " {{ hostvars[item]['ansible_hostname'] }}"
with_items: groups['host_all']
register: cmd_output
- name: debug ...
debug: var=cmd_output
如果主机无法访问,您将收到如下错误:
In case a host is unreachable you will get an error as below:
TASK: [c.. *****************************************************
fatal: [172.22.191.160] => One or more undefined variables: 'dict object' has no attribute 'ansible_hostname'
fatal: [172.22.191.162] => One or more undefined variables: 'dict object' has no attribute 'ansible_hostname'
FATAL: all hosts have already failed -- aborting
推荐答案
或者,这看起来更简单,更有表现力
alternatively, this looks simplier and more expressive
- hosts: myservers
become: true
pre_tasks:
- name: Check ALL hosts are reacheable before doing the release
assert:
that:
- ansible_play_hosts == groups.myservers
fail_msg: 1 or more host is UNREACHABLE
success_msg: ALL hosts are REACHABLE, go on
run_once: yes
roles:
- deploy
https://github.com/ansible/ansible/issues/18782#issuecomment-319409529
这篇关于Ansible:如果主机无法访问,则中止执行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!