Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jenkins pipeline credentials for all stages

I have Jenkins scripted pipeline with multiple stages, all of the stages require the same password for interaction with third-party API.

node {
    stage ('stage1') {
        sh 'curl --user login:password http://trird-party-api'
    }
    stage ('stage2') {
        sh 'curl --user login:password http://trird-party-api'
    }
}

For obvious reasons I want to keep this password safe, e.g. in Jenkins credentials.

The only secure way I've found is to add withCredentials section, but it must be added to each pipeline stage, e.g:

node {
    stage ('stage1') {
        withCredentials([string(credentialsId: '02647301-e655-4858-a7fb-26b106a81458', variable: 'mypwd')]) {
            sh 'curl --user login:$mypwd http://trird-party-api'
        }
    }
    stage ('stage2') {
        withCredentials([string(credentialsId: '02647301-e655-4858-a7fb-26b106a81458', variable: 'mypwd')]) {
            sh 'curl --user login:$mypwd http://trird-party-api'
        }
    }
}

This approach is not OK because real pipeline is really complicated.

Any alternatives?

like image 219
kagarlickij Avatar asked Apr 09 '18 19:04

kagarlickij


Video Answer


1 Answers

According to this other stackoverflow question and this tutorial, you should be able to specify the needed credentials in a declarative pipeline like so:

environment {
    AUTH = credentials('02647301-e655-4858-a7fb-26b106a81458')
}

stages {
    stage('stage1') {
        sh 'curl --user $AUTH_USR:$AUTH_PSW http://third-party-api'
    }
    stage('stage2') {
        sh 'curl --user $AUTH_USR:$AUTH_PSW http://third-party-api'
    }

With a scripted pipeline, you're pretty much relegated to using withCredentials around the things you want to have access to them. Have you tried surrounding the stages with the credentials, as in:

node {
    withCredentials([string(credentialsId: '02647301-e655-4858-a7fb-26b106a81458', variable: 'mypwd')]) {
        stage ('stage1') {
            sh 'curl --user login:password http://trird-party-api'
        }
        stage ('stage2') {
            sh 'curl --user login:password http://trird-party-api'
        }
    }
}
like image 79
tzrlk Avatar answered Oct 01 '22 23:10

tzrlk