You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修改Ansible Playbook实现多条件失败时输出自定义提示?

Fixing Ansible Playbook to Fail with Custom Messages for Different Conditions

Let's break down and fix your playbook step by step — you're hitting two main issues here: invalid playbook structure, and the original failed_when logic blocking your custom failure messages from triggering.

The Root Problems

  1. Invalid Play Structure: Your original code treats the Search for Number task as a separate play without specifying hosts, which is a syntax error in Ansible. All tasks need to live under a play's tasks section.
  2. Early Task Failure: The original failed_when on the command task would immediately mark the task as failed, stopping Ansible from running your subsequent fail tasks that have custom messages.

Corrected Playbook

Here's the fixed version that meets your requirements:

- name: "Play 1: Check Deployment Status"
  hosts: localhost
  tasks:
    - name: "Run SQL query to check for existing deployment"
      command: >
        mysql --user="{{ DBUSER }}" --password="{{ DBPASS }}" deployment --host=localhost --batch --skip-column-names --execute="SELECT num FROM deploy_tbl"
      register: command_result
      # Prevent this task from failing immediately — we'll handle failures in dedicated tasks
      failed_when: false
      when: Layer == 'APP'

    - name: Fail if deployment already exists (found 775 in results)
      fail:
        msg: "This REQ is already Deployed. Hence retry with a Unique Number."
      when:
        - Layer == 'APP'
        - command_result.stdout is search('775')

    - name: Fail if database is unreachable or query failed
      fail:
        msg: "Database is not reachable."
      when:
        - Layer == 'APP'
        - command_result.rc != 0

Key Adjustments Explained

  • Proper Play Structure: All tasks are now nested under the tasks section of the single play, which fixes the initial syntax error.
  • Deferred Failure Handling: Setting failed_when: false on the command task ensures it runs to completion even if the SQL query returns 775 or hits an error (like an unreachable database). This lets our dedicated fail tasks run and show custom messages.
  • Conditional Safety: Each fail task includes the Layer == 'APP' condition, which prevents errors when Layer isn't set to APP (since command_result won't be defined in that case).
  • Ordered Checks: Ansible runs tasks top to bottom. If the "775 found" condition is met, that fail task triggers first and stops the play — the database unreachable check won't run. If you want to check both conditions regardless, you could add ignore_errors: yes to the first fail task, but that's probably not necessary for your use case.

内容的提问来源于stack exchange,提问作者Ashar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 08:19:37