Can one use Jenkins to merge the approved pull request into the main/master branch?

Hi,

I am trying to use Jenkinsfile at the root of the repository to merge the pull request into main/controller. Is this feasible or I need to use GitHub Actions or anything else?

This is a sample of my Jenkinssfile

pipeline {
    agent any
    parameters {
        string(name: 'PR_NUMBER', defaultValue: '21', description: 'Pull Request Number to Merge')
    }
    environment {
        GITHUB_TOKEN = credentials('GitHub_Credentials')
    }
    stages {
        stage('Make HTTP Request') {
            steps {
                script {
                    def apiUrl = "https://api.github.com/repos/<USERNAME>/<REPOSITORY>/pulls/${params.PR_NUMBER}/merge"
                    echo "API URL: ${apiUrl}"

                    def response = sh(script: "curl -X POST $apiUrl -H 'Authorization: token ${GITHUB_TOKEN}'", returnStatus: true)
                    echo "HTTP Response Code: ${response}"
                    def responseBody = sh(script: "curl -X POST $apiUrl -H 'Authorization: token ${GITHUB_TOKEN}'", returnStdout: true).trim()
                    echo "Response Body: ${responseBody}"

                    if (response == 0) {
                        echo "HTTP request succeeded."
                    } else {
                        error("HTTP request failed with status code: ${response}")
                    }
                }
            }
        }
        stage('Merge Pull Request') {
            steps {
                script {
                    def prNumber = params.PR_NUMBER.toInteger()
                    def apiUrl = "https://api.github.com/repos/<USERNAME>/<REPOSITORY>/pulls/${params.PR_NUMBER}/merge"

                    def response = httpRequest(
                        url: apiUrl,
                        httpMode: 'POST',
                        authentication: 'GitHub_Credentials',
                        ignoreSslErrors: true
                    )

                    if (response.status == 200) {
                        echo "Pull request #${prNumber} merged successfully."
                    } else {
                        echo "Failed to merge pull request #${prNumber}."
                        error("HTTP Status: ${response.status}")
                    }
                }
            }
        }
    }
}

Needless to say it is coming with this error (from Jenkins)

hudson.AbortException: Fail: Status code 404 is not in the accepted range: 100:399 while calling https://api.github.com/repos/<USERNAME>/r<REPOSITORY>/pulls/24/merge
	at jenkins.plugins.http_request.HttpRequestExecution.responseCodeIsValid(HttpRequestExecution.java:470)
	at jenkins.plugins.http_request.HttpRequestExecution.processResponse(HttpRequestExecution.java:480)
	at jenkins.plugins.http_request.HttpRequestExecution.authAndRequest(HttpRequestExecution.java:376)
	at jenkins.plugins.http_request.HttpRequestExecution.call(HttpRequestExecution.java:284)
Also:   org.jenkinsci.plugins.workflow.actions.ErrorAction$ErrorId: 2708548f-f633-41ea-bac2-f371be2d2d8c
Caused: java.lang.IllegalStateException
	at jenkins.plugins.http_request.HttpRequestExecution.call(HttpRequestExecution.java:287)
	at jenkins.plugins.http_request.HttpRequestExecution.call(HttpRequestExecution.java:80)
	at hudson.remoting.LocalChannel.call(LocalChannel.java:47)
	at jenkins.plugins.http_request.HttpRequestStep$Execution.run(HttpRequestStep.java:404)
	at jenkins.plugins.http_request.HttpRequestStep$Execution.run(HttpRequestStep.java:383)
	at org.jenkinsci.plugins.workflow.steps.SynchronousNonBlockingStepExecution.lambda$start$0(SynchronousNonBlockingStepExecution.java:47)
	at java.base/java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:515)
	at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:264)
	at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
	at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
	at java.base/java.lang.Thread.run(Thread.java:834)
Finished: FAILURE

Thanks

You might consider using the GitHub command line interface to perform gh pr merge rather than attempting to call the API entry points yourself. The gh command must be authenticated, but once it is authenticated, it can perform many useful GitHub operations.

1 Like

Thanks Mark,

I install gh cli on my RHES and it works fine. However GitHub actions supposed to automate the CI part away from manual pr mege. Is GitHub actions is only alternative for CI?

Cheers

No, GitHub Actions is not the only alternative for CI.

As a Jenkins plugin maintainer and a Jenkins documentation maintainer, I very frequently click the GitHub button to enable automatic merge when the Jenkins CI job is successful. I like that use model very much because it allows GitHub to perform the merge (optionally squashing the merge or optionally rebasing the merge) without placing merge logic into the Jenkins job.

Thanks Mark, My GitHub actions does perform Validate pull requests automatically as shown below

image.png

However, there is no automation of merge and it has to be done manually?

Have this simple yml file for merge

name: Validate pull code in the merge queue, sleep for 60 sec

run-name: ${{ github.actor }} is validating code in the merge queue

on:

merge_group:

jobs:

validate-pr:

runs-on: ubuntu-latest

steps:

- name: Checkout code

uses: actions/checkout@v3

- name: Display info

run: |

pwd

tree -a -I '.git'

git status

- name: Run slow CI (emulated by a long sleep)

run: sleep 60

and it says “This workflow has no runs yet.” as below (graph not attached)

when I try the action “Validate pull code in the merge queue, sleep for 60 sec”

So I am confused whether this is expected behaviour and merge has to be done manually or my code is wrong?

Regards,

Mich

GitHub has the concept of auto-merge that can be enabled on a repository. It doesn’t require a GitHub action.

I usually enable it by following the instructions in a Google Doc that I’ve used for other Jenkins contribution ideas.