0
0
JenkinsHow-ToBeginner · 4 min read

How to Use Git in Jenkins Pipeline: Simple Guide

In Jenkins Pipeline, use the git step to clone a Git repository directly into your workspace. This step supports specifying the repository URL, branch, and credentials to automate code checkout during your build process.
📐

Syntax

The git step in Jenkins Pipeline clones a Git repository. You can specify the repository URL, branch, and credentials. It looks like this:

  • url: The Git repository URL.
  • branch: The branch to checkout (optional, defaults to master or main).
  • credentialsId: Jenkins credential ID for private repos (optional).
groovy
git url: 'https://github.com/user/repo.git', branch: 'main', credentialsId: 'my-credentials-id'
💻

Example

This example shows a simple Jenkins Pipeline script that clones a Git repository and prints the latest commit hash.

groovy
pipeline {
    agent any
    stages {
        stage('Checkout') {
            steps {
                git url: 'https://github.com/jenkinsci/pipeline-examples.git', branch: 'master'
            }
        }
        stage('Show Commit') {
            steps {
                script {
                    def commit = sh(script: 'git rev-parse HEAD', returnStdout: true).trim()
                    echo "Latest commit hash: ${commit}"
                }
            }
        }
    }
}
Output
Cloning into 'pipeline-examples'... ... Latest commit hash: 3a1b2c4d5e6f7g8h9i0jklmnopqrstuvwx
⚠️

Common Pitfalls

Common mistakes when using Git in Jenkins Pipeline include:

  • Not specifying credentialsId for private repositories, causing authentication failures.
  • Using the wrong branch name or forgetting to specify it, leading to unexpected code versions.
  • Running Git commands outside the workspace or before checkout, causing errors.

Always ensure your Jenkins agent has Git installed and the workspace is clean before checkout.

groovy
/* Wrong way: Missing credentials for private repo */
git url: 'git@github.com:private/repo.git'

/* Right way: Specify credentialsId */
git url: 'git@github.com:private/repo.git', credentialsId: 'my-ssh-key'
📊

Quick Reference

ParameterDescriptionExample
urlGit repository URL'https://github.com/user/repo.git'
branchBranch to checkout (optional)'main'
credentialsIdJenkins credential ID for private repos (optional)'my-credentials-id'

Key Takeaways

Use the Jenkins git step to clone repositories in your pipeline.
Specify credentialsId for private repositories to avoid authentication errors.
Always confirm the branch name to checkout the correct code version.
Run Git commands only after the repository is checked out in the workspace.
Ensure your Jenkins agent has Git installed and workspace is clean before checkout.