paltaa
paltaa

Reputation: 3244

Pass environment variable to jenkins pipeline bash script

Hey I'm trying to make changes to the environment variable GIT_BRANCH and parse the right side of the /, i know this can be achieved with cut like this: $(echo ${env.GIT_BRANCH} | cut -d \"/\" -f 2 )

Thing is, cannot make it work in Jenkins pipelines, error: bad substitution

pipeline {
    agent any

    stages {
        stage('Build') {
            steps {
                sh "docker build -t jpq/jpq:test ."
            }
        }
        stage('Test') {
            steps {
                sh  "docker run jpq/jpq:test python3 tests.py"
            }
        }
         stage('Push') {
             steps {
                sh '''#!/bin/bash
                  BRANCH=\$(echo \${env.GIT_BRANCH} | cut -d \"/\" -f 2 )
                  echo ${BRANCH}
                  docker tag jpq/jpq:test jpq/jpq:${BRANCH}
                  docker push jpq/jpq:test
                    '''
             }
         }
        // stage('Deploy') {
        //     steps {
        //     }
        // }
    }

}

How can I correctly generate the BRANCH variable and pass it to the docker tag?

Upvotes: 0

Views: 1081

Answers (1)

Technext
Technext

Reputation: 8107

This should work:

stage('Push') {
     steps {
        sh '''#!/bin/bash
            #printenv
            BRANCH=$(echo ${GIT_BRANCH} | cut -d "/" -f2)
            echo "Branch: ${BRANCH}"
        '''
    }
}

Note: To see what all environment variables are available to the shell block, you may use printenv.

Upvotes: 1

Related Questions