如何修改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
- Invalid Play Structure: Your original code treats the
Search for Numbertask as a separate play without specifyinghosts, which is a syntax error in Ansible. All tasks need to live under a play'staskssection. - Early Task Failure: The original
failed_whenon thecommandtask would immediately mark the task as failed, stopping Ansible from running your subsequentfailtasks 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
taskssection of the single play, which fixes the initial syntax error. - Deferred Failure Handling: Setting
failed_when: falseon thecommandtask ensures it runs to completion even if the SQL query returns 775 or hits an error (like an unreachable database). This lets our dedicatedfailtasks run and show custom messages. - Conditional Safety: Each
failtask includes theLayer == 'APP'condition, which prevents errors whenLayerisn't set toAPP(sincecommand_resultwon't be defined in that case). - Ordered Checks: Ansible runs tasks top to bottom. If the "775 found" condition is met, that
failtask triggers first and stops the play — the database unreachable check won't run. If you want to check both conditions regardless, you could addignore_errors: yesto the firstfailtask, but that's probably not necessary for your use case.
内容的提问来源于stack exchange,提问作者Ashar
相关产品推荐
相关产品推荐

