Pushing Back to Git In a Jenkins Multibranch Pipeline

Featured image for sharing metadata for article

When you're working with Jenkins multibranch pipelines, it's possible that you'd want to push something back to Git after the fact.

This could be that you're pushing a Git tag, or that maybe you're generating new package-lock.json files.

If you take a Jenkins multibranch pipeline that looks like this:

node {
  checkout scm

  stage('Build') {
    sh 'make'
  }

  if (env.BRANCH_NAME == 'master') {
    stage('Release') {
      sh 'git tag v..'
      sh 'git push --tags'
    }
  }
}

We'll find that unfortunately this does not work, even if you're configuring your Multibranch pipeline to be retrieved using Git credentials.

To make this work, we can instead follow Alan Edwardes' article and use the Git credentials helper:

node {
  checkout scm

  stage('Build') {
    sh 'make'
  }

  if (env.BRANCH_NAME == 'master') {
    stage('Release') {
      withCredentials([
        usernamePassword(credentialsId: '...', usernameVariable: 'GIT_USERNAME', passwordVariable: 'GIT_PASSWORD')
      ]) {
        sh 'git config credentials.helper "/path/to/helper.sh"'
        sh 'git tag v..'
        sh 'git push --tags'
      }
    }
  }
}

This requires that we create a file, helper.sh:

#!/usr/bin/env bash
echo username="$GIT_USERNAME"
echo password="$GIT_PASSWORD"

This now allows Git to correctly push to the remote using HTTPS authentication.

Written by Jamie Tanna's profile image Jamie Tanna on , and last updated on .

Content for this article is shared under the terms of the Creative Commons Attribution Non Commercial Share Alike 4.0 International, and code is shared under the Apache License 2.0.

#blogumentation #jenkins #git.

This post was filed under articles.

Interactions with this post

Interactions with this post

Below you can find the interactions that this page has had using WebMention.

Have you written a response to this post? Let me know the URL:

Do you not have a website set up with WebMention capabilities? You can use Comment Parade.