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"
以及文档中的其他内容,但我真正想要的只是一种使用阻止"和救援"命令之类的方法,但据我所知,这只适用于同一本书和戏剧,而不是角色.有没有人有这样做的好方法?
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 失败,ansible 将应用 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屋!