Conditional steps using when

May I make a suggestion?
I think you’re maybe overcomplicating it a little, and I also don’t think there’s a way to “fix” the above to work the way I think you want it to.

Also, if you don’t have “only build pull requests” set, you could also run into a deploy when someone pushes a commit to a random branch without making a PR, which I doubt you want? Do you have a large number of possible branches that could be getting deployed off of, and if so, do the branchnames have a predictable pattern?

IMO, your best bet is to deploy off either a cut tag, or on push to one or more branches or branch patterns. Then you can do something like

workflows:
  version: 2
  build-and-deploy:
    jobs:
      - checkout
      - lint:
          requires:
            - checkout
      - build:
          requires:
            - checkout
      - deploy:
          requires:
            - lint
            - build
          # Only deploy on pushes to "main" and "develop" branches
          filters:
            branches:
              only:
                # Note: filters for branches or tags can also be regexes, so 
                # you can get pretty elaborate here
                - main
                - develop

A better in some ways, but slightly more complex, option, would be to have something like semantic-release that runs on pushes to main, and cuts a tag when a release is needed, then have a separate workflow that deploys off that tag once it’s cut.

Is there a reason something like that won’t work for you?

All that said, I think even if you want to go the original route, it might be easier to have a single deploy step and have that in an if condition based directly on CIRCLE_PULL_REQUEST vs trying to define and redefine 3-4 different env vars (none of which will be accessible to Circle when it runs that conditional logic). That will work, whereas I could be wrong, but pretty sure the when condition (which IIRC is evaluated before your job even runs) won’t have any env vars (whether they’re in $BASH_ENV or not) in scope / available.

So, again, I personally wouldn’t recommend this, and see suggestions above, but something like this might work.

  deploy:
    steps:
      - run:
          name: deploy
          command: |
            if [ -n "$CIRCLE_PULL_REQUEST" ]; then
              echo "Not deploying"
            else
              echo "Deploying..."
              do some other stuff here
            fi              

In theory, you could use pipeline parameters (Project values and variables - CircleCI), however pipeline.trigger_parameters.circleci.event_type seems to be GitLab specific, so depending on your VCS provider, this might not be an option.

1 Like