Only run job on pull request from specific branch

I’d like to run integration tests only if I create a pull request from staging to master.

I can’t seem to find anything in the documentation that allows this, is it possible?

Thanks

Hi @pocockn,

Thank you for sharing your question on our forum!

There is no built in feature to replicate the functionality you are looking for, but one workaround would be to make use of the Github CLI. With the CLI, you can query for headRefName and baseRefName and then conditionally end (fail) a job if the conditions you set do not match.

The Github CLI can be installed via the following orb:

CircleCI Developer Hub - circleci/github-cli

I have come up with a sample config.yml that you can use as a reference:

version: 2.1

orbs: 
  gh: circleci/github-cli@2.1.0
  
jobs:
  build:
    parameters:
      head_branch:
        type: string
        default: ""
      target_branch:
        type: string
        default: ""
    docker: 
      - image: cimg/base:edge
    steps:
      - checkout
      - gh/setup
      - run:
          name: Determine PR target branch
          command: |
            if [[ -z "$CIRCLE_PULL_REQUEST" ]]; then
              echo "This is not a pull request" && exit 1
            fi
            
            HEAD_BRANCH=$(gh pr view $CIRCLE_PULL_REQUEST --json headRefName --jq '.headRefName')
            TARGET_BRANCH=$(gh pr view $CIRCLE_PULL_REQUEST --json baseRefName --jq '.baseRefName')
            
            echo "$HEAD_BRANCH -> $TARGET_BRANCH"
            
            if [[ $HEAD_BRANCH == "<<parameters.head_branch>>" ]] && [[ $TARGET_BRANCH == "<<parameters.target_branch>>" ]]; then
              echo "Branch conditions met"
            else
              echo "Exiting Job"
              circleci-agent step halt
            fi
      - run:
          name: Run integration tests
          command: echo "Running integration tests...."
            
workflows:
  github_cli:
    jobs:
      - build:
          head_branch: "dev"
          target_branch: "main"

Note: a job will still start, but will be failed if the conditions don’t match. Also, I am assuming you have the only build prs feature enabled.

If you would like the job status to be canceled instead of failed, you can replace exit 1/circleci-agent step halt above with an API call to cancel the job/workflow:

V2 API - Cancel a job
V2 API - Cancel a workflow

Please let me know if you have any questions about the above!

Best Regards

1 Like