我正在使用ansible自动执行堆栈部署。我使用“shell”或“command”模块来执行大部分任务。所以为了使playbook与shell和模块幂等,我正在修改这样的剧本..
- name: Task1
shell: 'source /etc/nova/openrc && heat stack-show myne01 | tee stack_show.log'
args:
creates: stack_show.log
register: list
- debug: var=list.stdout_lines
ignore_errors: yes
- name: Delete stack-show.log
file: path=/home/wrsroot/stack_show.log state=absent
when: "list.rc != 0"
- name: Failed the stack
shell: "echo 'stack is failed'"
when: "list.rc != 0"
failed_when: "list.rc != 0"
这里的流程是:
1)显示堆栈状态
2)如果堆栈执行失败,则忽略错误并删除“stack_show.log”文件,因此在重新运行anisble时不会跳过此任务。
3)如果堆栈执行失败,则任务失败。
请建议是否有更好的方法来做到这一点。
为了在playbook中添加幂等性,我为每个“shell”模块添加了9行代码。它使我的剧本非常大。
答案 0 :(得分:0)
您只需要changed_when: false
是幂等的。
另外我认为你可以更简单地做到这一点:
- name: Task1
shell: bash -c 'set -o pipefail;source /etc/nova/openrc && heat stack-show myne01 | tee stack_show.log'
changed_when: false
args:
creates: stack_show.log
register: list
- name: Delete stack-show.log
file: path=/home/wrsroot/stack_show.log state=absent
changed_when: false
# You don't need this because file will deleted if exists
# when: "list.rc != 0"
# You don't need it because command will failed
# set -o pipefail
#- name: Failed the stack
# shell: "echo 'stack is failed'"
# when: "list.rc != 0"
# failed_when: "list.rc != 0"
tasks:
- block:
- shell: bash -c 'set -o pipefail;source /etc/nova/openrc && heat stack-show myne01 | tee stack_show.log'
changed_when: false
args:
creates: stack_show.log
register: list
always:
- debug: msg="this always executes"
- name: Delete stack-show.log
file: path=/home/wrsroot/stack_show.log state=absent
changed_when: false