'How to implement "run command X, fix it if it fails and rerun after the fix" in Ansible?

In my playbook, I plan to run a command X, but this command X might fail the first time then I have a fix for that command. If command X fails, then invoke the fix. After the fix, run command X again.

    - name: a block with a command that might fail the first time but can be fixed and then rerun that command
    block:
        - name: this task might fail the first time
        command: command X
    
    rescue:
        - name: fix the error caused by command X
        command: fix it!
    
    always:
        - name: run command the second time
        command: command X

But i'm not happy with this structure because:

  • always is run whatever even if command X succeeds.
  • command X is very long and I don't like copy and paste the code everywhere.

So do we have a better solution? Any suggestion is appreciated.

[Edit]

I can improve it to:

    - name: a block with a command that might fail the first time but can be fixed and then rerun that command
    block:
        - name: this task might fail the first time
        command: command X
    
    rescue:
        - name: fix the error caused by command X
        command: fix it!
        - name: run command the second time
        command: command X

But there is still code duplication issue since command X is extremely long and I don't want to copy and paste it.



Solution 1:[1]

You only want to run the command a second time when it fails the first time, so it should be part of the rescue.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 flowerysong