HiveBrain v1.2.0
Get Started
← Back to all entries
snippetMinor

How to determine if a Jenkins build is triggered by a Pull Request merged to Master

Submitted by: @import:stackexchange-devops··
0
Viewed 0 times
pulljenkinsrequestmastermergeddeterminehowbuildtriggered

Problem

I think i've scoured every post on this topic but haven't found my specific scenario. (Maybe that means I'm building the wrong thing OR i've built something unique and new? The former is far more likely)

I have a multibranch pipeline in Jenkins being triggered by webhooks from GitHub. I want to automatically tag the repo being built only when a PR from develop|release|hotfix branches are closed and merged to master.

What I want to drill in on is how to identify when a master branch build is triggered by the merge from a PR, and not from anything else. I don't want to tag if master builds due to a non-PR merge. (This would allow updating readmes and code comments without generating a new tag.)

I'm getting the tag string from a file in the repo, and I know how to use the PR builder to identify the source and target of a pull request for when conditions. I know how to get the JSON build information and pull data out, but what I want doesn't seem to be there.

when { changeRequest target: 'master' } only identifies the PR build, not the master build that results when the PR is closed and merged.

when { branch 'master' } obviously identifies a master branch build, but how can I limit it to only build when the build is triggered the merge from a closed PR?

Solution

You might try installing the GitHub Integration plugin. Reading their documentation, they provide a number of environment variables you can use for your purpose.

  • GITHUB_PR_STATE can be OPEN, CLOSE



  • GITHUB_PR_SOURCE_BRANCH for the source branch (e.g., hotfix/foo)



  • GITHUB_PR_TARGET_BRANCH or master



Using the when condition, you can run a job/stage when it's a closed PR merging into the master branch using:

when { 
  allOf { 
    expression { env.GITHUB_PR_STATE == "CLOSE" }
    expression { env.GITHUB_PR_TARGET_BRANCH == "master" }
    expression { env.GITHUB_PR_SOURCE_BRANCH == "hotfix/foo" }
  } 
}

Code Snippets

when { 
  allOf { 
    expression { env.GITHUB_PR_STATE == "CLOSE" }
    expression { env.GITHUB_PR_TARGET_BRANCH == "master" }
    expression { env.GITHUB_PR_SOURCE_BRANCH == "hotfix/foo" }
  } 
}

Context

StackExchange DevOps Q#11824, answer score: 3

Revisions (0)

No revisions yet.