问题描述
摘要:一种更好的方法,可以在主机无法访问时立即中止可播放的剧本.
Summary: A better way for aborting ansible playbook immediately if any host is unreachable.
如果主机中的任何一个无法访问,是否可以中止Ansible剧本.我发现,如果无法连接到主机,它将继续运行并执行剧本中的所有剧本/任务.
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.
我所有的剧本都将max_fail_percentage指定为0,但是在这种情况下,ansible不会抱怨,因为所有可访问的主机都可以执行所有剧本.
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.
由于第一步是运行剧本的一部分,因此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:如果主机无法访问,则中止执行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!