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

标签 jenkins jenkins-pipeline jenkins-plugins credentials

如何获取 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
  }
}

如何将上述代码合并到当前管道中,以便管道脚本中的所有阶段(即全局)都可以访问 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

我使用的是最新版本的 Jenkins。

请求解决方案。谢谢。

最佳答案

你可以做这样的事情。在这里,您可以在 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'
        }
    }
}

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

有关 official documentation 中的 credentials() 的更多信息.

关于jenkins - 如何在 Jenkins 声明式管道的所有阶段获取 Jenkins 凭据变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58037858/

相关文章:

angular - 如何在 Jenkins 中对 Angular 进行代码质量分析?

security - 如何为 Jenkins JNLP 从站启用安全性?

Jenkins 管道 'checkout scm' 在特定节点上失败

Jenkins Sonarqube 插件 : JAVA_HOME exists but does not point to a valid Java home

git - Jenkins Git 用户内容插件

jenkins - 将数据(变量/参数)从一个下游作业传递到上游作业,以便将数据传递到另一个下游作业

jenkins - 如何在 check out Jenkinsfile 中的存储库之前清理管道

Jenkinsfile - 操作后避免状态代码重复

jenkins - 从阶段内部定义全局环境变量

git - 错误 : Error fetching remote repo 'origin' returned status code 143