When: on_fail causes a build error

I’m getting the following error:

Unable to parse YAML
mapping values are not allowed here
in 'string', line 23, column 13:
        when: on_fail
            ^

my code:

version: 2.1

commands:
destroy_environment:
steps:
- run:
name: Destroy Environments
command: |
aws delete-stack --stack-name udacityStack

jobs:
create_infrastructure:
docker:
- image: amazon/aws-cli
steps:
- checkout
- run:
name: create infrastructure
command: |
aws cloudformation deploy --template-file template.yml --stack-name udacityStack --region=us-west-2

  - run: return 1
  - destroy_environment
    when: on_fail

workflows:
my_workflow:
jobs:
- create_infrastructure

Hi @chrisj,

Welcome to Discuss – happy to help here!

Based on the example provided, you will want to move the when key to be contained with the command itself, so like:

commands:
  destroy_environment:
    steps:
      - run:
          name: Destroy Environments
          command: |
            aws delete-stack --stack-name udacityStack
          when: on_fail

If you need to change when it is run dynamically when you invoke the command, you can utilize parameters to accomplish that:

commands:
  destroy_environment:
    parameters:
      when_to_run:
        type: string
        default: "on_fail"
    steps:
      - run:
          name: Destroy Environments
          command: |
            aws delete-stack --stack-name udacityStack
          when: << parameters.when_to_run >>

Then you would invoke with the param when you needed to change it:

      - destroy_environment:
          when_to_run: always

Hope that helps!