Ansible:循环中任务失败时如何跳过后续任务进入下一轮?
解决Ansible循环中任务失败后跳过后续任务的问题
针对你遇到的问题,有两种简洁的解决方案可以实现「命令失败时跳过子剧本后续任务,直接进入下一个循环项」的需求:
方法一:使用Block-Rescue结构(推荐)
将需要在命令成功后执行的任务打包到block中,当block内任何任务失败时,直接进入rescue分支(可仅做提示或空操作),从而跳过剩余任务。修改createBackupconfigSub.yaml如下:
- name: Describe task set_fact: task_description: "Creating backupconfig {{item.name}}" - name: Print the task debug: var=task_description - block: - name: Create Backupconfig command: "create-backupconfig abc" register: command_output - name: Get command output as json set_fact: jsondata: "{{command_output.stdout | from_json}}" - name: Get timestamp from the system shell: "date" register: tstamp rescue: - name: Notify failure and skip debug: msg: "创建Backupconfig {{item.name}}失败,跳过后续任务"
原理:block定义了一组需要按顺序执行的成功路径任务,一旦其中某个任务失败(比如create-backupconfig执行出错),Ansible会立即终止block内剩余任务,转而执行rescue中的内容。执行完rescue后,整个子剧本执行完毕,自动回到父剧本的loop中处理下一个元素。
方法二:通过条件判断控制后续任务执行
给Create Backupconfig任务添加错误捕获,然后用when条件让后续任务仅在命令成功时执行。修改createBackupconfigSub.yaml如下:
- name: Describe task set_fact: task_description: "Creating backupconfig {{item.name}}" - name: Print the task debug: var=task_description - name: Create Backupconfig command: "create-backupconfig abc" register: command_output ignore_errors: yes # 捕获错误,不终止整个子剧本执行 - name: Get command output as json set_fact: jsondata: "{{command_output.stdout | from_json}}" when: command_output is succeeded # 仅命令成功时执行 - name: Get timestamp from the system shell: "date" register: tstamp when: command_output is succeeded # 仅命令成功时执行
原理:ignore_errors: yes让命令失败时不会终止子剧本,后续任务通过when: command_output is succeeded判断,仅在命令返回码为0时才执行,否则直接跳过,进入下一个循环项。
注意:父剧本abc.yaml中的ignore_errors: yes可以保留,确保即使子剧本出现未处理的错误,也不会终止整个play的执行。
内容的提问来源于stack exchange,提问作者Akash-BLR
相关产品推荐
相关产品推荐

