所有阶段的 Jenkins 管道凭证

kag*_*kij 6 jenkins-pipeline

我有多个阶段的 Jenkins 脚本管道,所有阶段都需要相同的密码才能与第三方 API 交互。

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

出于显而易见的原因,我想保持此密码安全,例如在 Jenkins 凭据中。

我发现的唯一安全方法是添加withCredentials部分,但必须将其添加到每个管道阶段,例如:

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'
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

这种方法是不行的,因为真正的管道真的很复杂。

任何替代方案?

tzr*_*rlk 7

根据另一个 stackoverflow 问题本教程,您应该能够在声明性管道中指定所需的凭据,如下所示:

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'
    }
Run Code Online (Sandbox Code Playgroud)

使用脚本化管道,您几乎只能使用withCredentials您想要访问它们的东西。您是否尝试过使用凭据围绕各个阶段,如下所示:

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'
        }
    }
}
Run Code Online (Sandbox Code Playgroud)