首页 > 解决方案 > 如何将变量传递给 JenkinsFiles 中的凭证参数?

问题描述

我正在尝试编写一个 JenkinsFile,它会自动通过 ssh 访问 git repo 并执行一些操作,但我想使用存储在 Jenkins 中的 ssh id 来使用 repo 和 ssh 密钥使用变量,但我似乎错过了 Jenkins 文档了解如何将变量传递给 Jenkins 文件,因为我无法将值传递到凭据键中。传递给 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 ...
            ....
            ....
          }
        }
      }
    }

目标是我的开发人员可以调用的管道,并将使用他们自己的 repos 和我没有使用的 ssh id。当我尝试使用传递值的 SSH_priv 参数运行它时,我在 Jenkins 中遇到以下故障。

故障输出

JenkinsFile 与硬编码的凭证 id 完美配合 - 如下所示: 成功输出

标签: jenkinsparametersjenkins-pipelinecredentialsssh-agent

解决方案


因此,在测试了不同的东西后,一位朋友在 5 分钟内解决了这个问题。 引号类型在 Groovy 脚本中很重要

改变

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

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

解决了这个问题。


推荐阅读