Git Integration

Jenkins connects to Git repositories to fetch your code before every build.

Syntaxgit branch: 'main', url: 'https://github.com/user/repo.git'

Jenkins integrates tightly with Git through the built-in Git plugin. Almost every pipeline starts by checking out code from a repository.

Ways to configure Git

  • Freestyle job β€” fill in the repository URL under Source Code Management.
  • Pipeline β€” use the git step or the more flexible checkout step.
  • Pipeline from SCM β€” Jenkins checks out the repo just to find and run the Jenkinsfile.

Authentication

For private repositories, store an SSH key or a personal access token in the Jenkins credentials store and reference it by ID.

Example

Example Β· bash
pipeline {
    agent any
    stages {
        stage('Checkout') {
            steps {
                git branch: 'main',
                    url: 'https://github.com/example/my-app.git',
                    credentialsId: 'github-token'
            }
        }
        stage('Show commit') {
            steps {
                sh 'git log -1 --oneline'
            }
        }
    }
}

When to use it

  • A pipeline checks out a private GitHub repo using an SSH key credential stored in the Jenkins credentials store.
  • A team configures the Git SCM step with a refspec to fetch only the branch that triggered the build.
  • Jenkins checks out a shallow clone with a depth of 1 to speed up builds on a repository with a very long history.

More examples

Checkout via pipeline SCM

Clones a private GitHub repository using a stored HTTPS token credential.

Example Β· groovy
pipeline {
  agent any
  stages {
    stage('Checkout') {
      steps {
        git url: 'https://github.com/org/myapp.git',
            branch: 'main',
            credentialsId: 'github-https-token'
      }
    }
  }
}

Shallow clone for speed

Performs a shallow Git clone with depth 1 to avoid downloading the full repository history.

Example Β· groovy
steps {
  checkout([
    $class: 'GitSCM',
    branches: [[name: '*/main']],
    extensions: [[$class: 'CloneOption', depth: 1, shallow: true]],
    userRemoteConfigs: [[url: '[email protected]:org/myapp.git',
                         credentialsId: 'github-ssh']]
  ])
}

Checkout specific tag

Checks out a specific Git tag provided as a pipeline parameter, useful for release builds.

Example Β· groovy
steps {
  checkout([
    $class: 'GitSCM',
    branches: [[name: "refs/tags/v${params.VERSION}"]],
    userRemoteConfigs: [[url: 'https://github.com/org/myapp.git',
                         credentialsId: 'github-https-token']]
  ])
}

Discussion

  • Be the first to comment on this lesson.
Git Integration β€” Jenkins | SoundsCode