3

In our github repository, we have set up a protected environment named Sandbox, for which the main branch is the only allowed deployment branch. Now we want to deploy automatically to that environment if a pullrequest is merged into main (and the if the pullrequest in addition bears the label "Sandbox").

Our workflow is roughly as follows:

name: Pull Request Merged

concurrency:
  group: ${{ github.ref }}

on:
  pull_request:
    types: [closed]

jobs:
  deploy_to_sandbox:
    if: |
      github.event.pull_request.merged == true && 
      contains(github.event.pull_request.labels.*.name, 'Sandbox')
    name: Deploy to Sandbox
    uses: ./.github/workflows/deploy.yml
    with:
      environment: Sandbox
    secrets: inherit

The workflow is triggered as expected upon merging a PR, but somehow it tries to deploy from the feature branch instead of deploying from main. Since the environment is protected, the deployment fails accordingly. How can we achieve that the deployment uses the target branch (i. e. , main) that was merged into, instead of the source branch?

Hermann.Gruber
  • 1,257
  • 1
  • 12
  • 37
  • Possibly related question: https://stackoverflow.com/questions/71382892/github-actions-on-a-push-to-master-workflow-how-can-i-get-a-link-to-the-pull-r – Hermann.Gruber Dec 08 '22 at 16:37
  • I am bumping into the same thing. I tried pull_request_target, but it _also_ ran in the context of the feature branch... :| The 'just use push' crowd is exhausting. It's the only answer I see. – Chris Pfohl Jun 07 '23 at 15:52

1 Answers1

0

There’s no way to specify that a workflow should be triggered when a pull request is merged. the reason why it's the feature branch that gets deployed is because it's the one that triggers the workflow. However, because a merged pull request always results in a push, you can use the push event to accomplish your goal.

For example, let’s say that you want to run a workflow whenever a pull request is merged to your main branch. You can do something like this:

on:
  push:
    branches:
      - main

also if you want to prevent push directly to main it's part of github pro plan.

mar0ne
  • 148
  • 1
  • 10
  • 1
    Welcome to StackOverflow @mar0ne and thank you for your answer! Unfortunately, I do not see how to solve my problem with this approach: I also need to know whether the PR that triggered the push bears the appropriate "Sandbox" label. I think that, from the context of the push, I have no means to access the PR object. – Hermann.Gruber Dec 12 '22 at 09:06