如何在JenkinsFiles中将变量传递给凭证参数?

时间:2020-07-13 05:22:45

标签: jenkins parameters jenkins-pipeline credentials ssh-agent

我正在尝试编写一个JenkinsFile,它将通过ssh自动到达git repo并执行一些操作,但是我想使用存储在Jenkins中的ssh id来使repo和ssh密钥使用变量,但是我似乎丢失了Jenkins文档中有关如何将变量传递给Jenkins Files的信息,因为我无法将值传递给凭证密钥。传递给sh命令的变量可以很好地解析...

以下示例管道:

pipeline {
  parameters {
    string(name: 'SSH_priv', defaultValue: 'd4f19e34-7828-4215-8304-a2d1f87a2fba', description: 'SSH Credential with the private key added to Jenkins and the public key to the username stored in Git Server, this id can be found in the credential section of Jenkins post its creation.')
    string(name: 'REPO', defaultValue: 'git@--------------------')
  }
  stages {
    stage ('Output Variables'){
      // checks I can get these variables
      steps{
        sh("echo ${params.SSH_priv}")
        sh("echo ${params.REPO}")
      }
    }

stage('Do Something') {
      steps {
        // this below commented line, does not work.  
        // sshagent (credentials: ['${params.SSH_priv}']){

        // this line does work
        sshagent (credentials: ['d4f19e34-7828-4215-8304-a2d1f87a2fba']){
          sh("git clone --mirror ${params.REPO} temp")
          dir("temp"){
            // start doing fancy stuff ...
            ....
            ....
          }
        }
      }
    }

目标是我的其他开发人员可以调用的管道,该管道将使用我自己未使用的自己的存储库和自己的ssh id。当我尝试通过SSH_priv参数传递该值来运行此程序时,在Jenkins中出现以下错误。

Failure Output

JenkinsFile与硬编码的凭证ID完美配合,如下所示: Success Output

2 个答案:

答案 0 :(得分:1)

更好地在管道中使用环境步骤。

pipeline {
    agent any
    environment { 
                AN_ACCESS_KEY = credentials('an_access_key_id') 
            }
    stages {
        stage('Example') {
            steps {
                sh 'printenv'
            }
        }
    }
}

并且凭据应该在ID为an_access_key_id的詹金斯中存在

看看官方文档here

答案 1 :(得分:0)

因此,在测试了不同的事物之后,一个朋友在不到5分钟的时间内解决了这个问题。 Quotation mark types matter in Groovy Script

更改

sshagent (credentials: ['${params.SSH_lower}']){

收件人

sshagent (credentials: ["${params.SSH_lower}"]){

解决了这个问题。

相关问题