Ansible-发生错误时,退出角色并运行清理 [英] Ansible - On error, exit role and run cleanup
问题描述
我正在尝试在Ansible中启动一个AWS部署环境,因此我想做到这一点,以便在此过程中如果出现故障,Ansible会拆除到目前为止已启动的AWS上的所有内容.我不知道如何使Ansible在角色内引发错误
I'm trying to spin up an AWS deployment environment in Ansible, and I want to make it so that if something fails along the way, Ansible tears down everything on AWS that has been spun up so far. I can't figure out how to get Ansible to throw an error within the role
例如:
<main.yml>
- hosts: localhost
connection: local
roles:
- make_ec2_role
- make_rds_role
- make_s3_role
2. Then I want it to run some code based on that error here.
<make_rds_role>
- name: "Make it"
- rds:
params: etc <-- 1. Let's say it fails in the middle here
我尝试过:
- name: this command prints FAILED when it fails
command: /usr/bin/example-command -x -y -z
register: command_result
failed_when: "'FAILED' in command_result.stderr"
以及文档中的其他内容,但我真正想要的只是使用诸如"block"和"rescue"命令之类的方式,但据我所知,它只能在同一本书中使用和戏剧,而不是角色.有没有人有一个很好的方法来做到这一点?
As well as other things on within the documentation, but what I really want is just a way to use something like the "block" and "rescue" commands , but as far as I can tell that only works within the same book and on plays, not roles. Does anyone have a good way to do this?
推荐答案
将角色内部的任务包装成块/救援物.
确保救援块至少有一项任务–这样Ansible不会将主机标记为失败.
像这样:
Wrap tasks inside your roles into block/rescue thing.
Make sure that rescue block has at least one task – this way Ansible will not mark the host as failed.
Like this:
- block:
- name: task 1
... # something bad may happen here
- name: task N
rescue:
- assert: # we need a dummy task here to prevent our host from being failed
that: ansible_failed_task is defined
Ansible的最新版本注册 ansible_failed_task
和ansible_failed_result
.
因此,您可以像这样在main.yml剧本中执行一些post_tasks:
Recent versions of Ansible register ansible_failed_task
and ansible_failed_result
when hit rescue block.
So you can do some post_tasks in your main.yml playbook like this:
post_tasks:
- debug:
msg: "Failed task: {{ ansible_failed_task }}, failed result: {{ ansible_failed_result }}"
when: ansible_failed_task is defined
但要警告,该技巧不会阻止其他角色执行.
因此,在您的示例中,如果make_rds_role失败,则将应用make_s3_role并随后运行post_tasks.
如果需要防止这种情况,请在每个角色或某些角色的开头添加一些对ansible_failed_task
事实的检查.
But be warned that this trick will NOT prevent other roles from executing.
So in your example if make_rds_role fails ansible will apply make_s3_role and run your post_tasks afterwards.
If you need to prevent it, add some checking for ansible_failed_task
fact in the beginning of each role or something.
这篇关于Ansible-发生错误时,退出角色并运行清理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!