Ansible - 当至少一个项目在循环中失败时跳过任务

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

我 运行 几个 SQL 脚本使用 sqlplus present。在 运行 之前,我从该目录中获取所有 sql 文件的列表并将其存储在 sql_out 中,如下所示。

问题是如果 sql 脚本之一失败,其余 sql 脚本仍然执行。如果任何一个脚本失败,我想完全跳过该任务。有什么办法可以跳过。我想我们可以使用 with_items 但不确定如何实现。有帮助吗?

  - 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

据我所知,从当前的 Ansible 版本 2.3 开始,这是不可能的。

任务执行器在 such way 中工作,它首先执行每个循环迭代,然后才分析 task/items 结果。

您应该重构您的 shell 脚本,以便能够接收脚本列表作为参数并在脚本中迭代它们,而不是使用 Ansible。这也会给你显着的速度提升。

由于您没有详细说明“跳过任务”是什么意思,我实际上post只是一个概念性的回答。在当前形式中,脚本将按顺序 运行,如果一个失败,则整个任务将失败。如果你想跳过其他脚本,你需要添加额外的检查。

将脚本-运行ning 任务提取到单独的文件并将其包含在with_fileglob-循环中:

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

runscript.yml:

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

您应该在 Ansible 中添加 Strategy 参数。当任务失败时,它将停止执行剧本。 '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']} 可以找到详细信息 here。我正在使用 ansible 2.2.1.0