Skip to content

How to get GitHub repository url from env variable in Jenkinsfile

Last updated on November 22, 2023

When working with Jenkins pipelines, you may need to retrieve the URL of your GitHub repository dynamically and use it in your pipeline. Here’s a code snippet that demonstrates how to achieve this:

pipeline {
    agent any

    environment {
        def gitRemoteOriginUrl = scm.getUserRemoteConfigs()[0].getUrl()
    }

    options {
        skipDefaultCheckout(true)
        disableConcurrentBuilds()
    }

    stages {
        stage('Checkout') {
            steps {
                script {
                    checkout([$class: 'GitSCM',
                        branches: [[name: env.BRANCH_NAME]],
                        userRemoteConfigs: [[credentialsId: 'jenkins-credentials-for-github', 
                        url: "${gitRemoteOriginUrl}"]]])
                }
            }
        }
    }
}

In the environment block, we define a variable called gitRemoteOriginUrl and assign it the value of the repository URL. The scm.getUserRemoteConfigs()[0].getUrl() expression retrieves the URL of the first remote configuration defined in your Jenkins SCM configuration. Make sure you have configured the repository URL correctly in the Jenkins job’s SCM configuration.

Then, in the checkout step, we use the ${gitRemoteOriginUrl} variable to dynamically set the URL for the GitSCM checkout. This ensures that the pipeline fetches the source code from the correct repository URL.

By using this approach, you can retrieve the GitHub repository URL dynamically and avoid hardcoding it in your Jenkinsfile, making your pipeline more flexible and reusable.

Published inci/cdJenkinsLinuxScript