如何在Jenkins声明性流水线中使用存储的证书

40次阅读
没有评论

问题描述

在Jenkins中有一个存储的证书,并且需要在流水线构建作业中使用它。但问题是,似乎流水线无法使用证书:
尝试使用:

environment {
    KEY = credentials('mycert')
}

结果是:

ERROR: No suitable binding handler could be found for type com.cloudbees.plugins.credentials.impl.CertificateCredentialsImpl. Supported types are StandardUsernamePasswordCredentials,FileCredentials,StringCredentials,SSHUserPrivateKey.

如何解决这个问题并在流水线中使用存储的证书?如果无法使用存储的证书,那么存储证书的意义就不存在了。

解决方案

请注意以下操作注意版本差异及修改前做好备份。

方案1

根据Jenkins文档,某些凭据类型无法直接绑定在环境部分中。如果需要在流水线中设置凭据,除了秘密文本、用户名和密码或秘密文件之外的其他凭据类型(如SSH密钥或证书),可以使用Jenkins的Snippet Generator功能,通过Jenkins的经典用户界面访问。
Snippet Generator会生成类似以下代码:

withCredentials([certificate(aliasVariable: '', credentialsId: 'myCert', keystoreVariable: 'CERT', passwordVariable: '')]) {
    // some block
}

方案2

我通常将凭据名称设置为环境变量:

environment {
    CERT = 'mycert'
}

然后,我可以在需要的地方使用该名称:

withCredentials([usernamePassword(credentialsId: "${env.CERT}",
                                  passwordVariable: 'CERT_PASSWORD',
                                  usernameVariable: 'CERT_USER')]) {
    // Do things needing environment variables
}

或者

checkout(poll: false,
         scm: [
               $class: 'GitSCM',
               userRemoteConfigs: [[credentialsId: "${env.CERT}",
                                    url: 'https://code.example.org/somerepo']]
               ])

以上是两种解决方案,你可以根据自己的需求选择其中一种来使用存储的证书。

正文完