如何在 Jenkins 声明式管道的所有阶段获取 Jenkins 凭据变量

Ash*_*har 2 credentials jenkins jenkins-plugins jenkins-pipeline

如何让 Jenkins 凭证变量(即“mysqlpassword”)可供 Jenkins 声明性管道的所有阶段访问?

下面的代码片段工作正常并打印我的凭据。

node {
  stage('Getting Database Credentials') {
    withCredentials([usernamePassword(credentialsId: 'mysql_creds', passwordVariable: 'mysqlpassword', usernameVariable: 'mysqlusername')]) 
    {
        creds = "\nUsername: ${mysqlusername}\nPassword: ${mysqlpassword}\n"
    }
        println creds
  }
}
Run Code Online (Sandbox Code Playgroud)

如何将上述代码合并到当前的管道中,以便管道脚本的所有阶段(即全局)都可以访问 mysqlusername 和 mysqlpassword 变量。

我的管道脚本布局如下所示:

pipeline {          //indicate the job is written in Declarative Pipeline

    agent { label 'Prod_Slave' }

    environment {
                     STAGE_2_EXECUTED = "0"
    }

        stages {
            stage ("First Stage")  {
                     steps {
                echo "First called in pipeline"
                                script {
                        echo "Inside script of First stage"
                    }

                } 
          }       // end of first stage

            stage ("Second Stage")  {
                     steps {
                echo "Second stage called in pipeline"
                                script {
                        echo "Inside script of Second stage"
                    }

                } 
          }     // end of second stage

   }      //end of stages
}      // end of pipeline
Run Code Online (Sandbox Code Playgroud)

我使用的是最新版本的詹金斯。

请求解决方案。谢谢。

Pac*_*ist 5

你可以做这样的事情。在这里,您可以在下面定义变量environment { }并在整个阶段中使用它。

pipeline {
agent any
   environment {
        // More detail: 
        // https://jenkins.io/doc/book/pipeline/jenkinsfile/#usernames-and-passwords
        MYSQL_CRED = credentials('mysql_creds')
   }
stages {
    stage('Run Some Command') {
        steps{
            echo "Running some command"
            sh '<some-command> -u $MYSQL_CRED_USR -p $MYSQL_CRED_PSW'
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

环境下定义的变量对于所有阶段都是全局的,因此可以在整个 jenkinsfile 中使用。

更多信息请参见credentials()官方文档