Ansible - Skip task when at least one item fails in loop

痴心易碎 提交于 2019-12-11 07:05:54

问题


I am running few SQL scripts using sqlplus present. Before running I am getting all the list of sql files from that directory and storing it in sql_out as shown below.

The problem is if one of the sql script fails the rest of the sql scripts still executes. I want to skip the task completely if any one of the script fails. Is there any way to skip. I reckon we can use with_items but not sure how to implement. Any help?

  - name: "Get sql files from directory"
    shell: ls {{ directory }}/{{ scripts_path }}/*.sql
    register: sql_out
    tags:
     - sql

  - name: "Execute each SQL Scripts"
    script: sqlplus.sh {{ db_username }} {{ db_password }} {{ 
    connection_string }} {{ schema }} {{ item }} 
    delegate_to: localhost

    with_items: sql_out.stdout_lines
    tags:
     - sql

回答1:


AFAIK this is not possible as of current Ansible version 2.3.

Task executor works in such way that it executes every loop iteration first and only then analyzes task/items results.

You should refactor your shell script to be able to receive scripts list as parameter and iterate them inside the script, not with Ansible. This will also give you significant speed boost.




回答2:


As you have not provided details on what do you mean by "skip task", I actually post only a concept answer. In the current form, the scripts will be run sequentially and if one fails, the whole task will fail. If you want other scripts to be skipped, you need to add additional check.

Extract the script-running task to a separate file and include it in a with_fileglob-loop:

- include: runscript.yml
  with_fileglob: "{{ directory }}/{{ scripts_path }}/*.sql"

with runscript.yml:

- script: sqlplus.sh {{ db_username }} {{ db_password }} {{ connection_string }} {{ schema }} {{ item }} 



回答3:


You should add Strategy parameter in Ansible. It will stop executing playbook as task fails. 'strategy: debug'

- name: Install & Configure Test server gather_facts: True strategy: debug sudo: yes hosts: test-client vars: test_server_ip: xxx.xxx.xx.xx roles: - { role: tools, tags: ['tools']} - { role: test-client, tags: ['test-client']} Details can be found here. I am using ansible 2.2.1.0



来源:https://stackoverflow.com/questions/44773833/ansible-skip-task-when-at-least-one-item-fails-in-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!