首页 > 解决方案 > 在 Jenkins 共享库中管理凭据的正确方法是什么?

问题描述

我已经开始为我的团队管理多个 Jenkins 管道。在这些管道中,有很多重复的代码。也就是说,我已经开始更好地遵循Jenkins 文档并将重复的代码移动到共享库中,以便在多个作业中使用。

我面临的问题是决定如何管理作业和共享库之间的凭据传递。许多库将处理通过不同 Web 服务器交换数据。与这些 Web 服务器的每次交互都需要用户名 + 密码或一些 API 令牌来进行身份验证/授权。

我知道可行的解决方案是让共享库中的每个函数都将凭据作为参数。有了它,我可以withCredentials(...) { }在我的 Jenkinsfile 中指定我的凭据。虽然我相信这会奏效,但我想知道这是否是最好的解决方案。

由于每个 API(和相应的库)都将绑定到一个凭证,我想知道我是否可以以某种方式以安全的方式将库链接到单个凭证。下面是两个管道示例,说明我知道什么会起作用以及我想探索什么。

我所知道的会起作用:

stage('promote') {
    steps {
        // known working solution
        interactWithApi1(content1, credentials)
        interactWithApi2(content2, credentials)
    }
}

我想从可行性的角度探讨:

stage('promote') {
    steps {
        // something I'm inclined to look into
        // where these library(s) already know the credentials
        interactWithApi1(content1)
        interactWithApi2(content2)
    }
}

标签: jenkinsjenkins-pipelineshared-librariescredentials

解决方案


像这样的东西对我们有用:

//vars/interactWithAws.groovy in your library

def call(Map params) {
   withAWS(credentials: 'jenkins-aws-credentials') { 
       s3upload bucket: "myBucket", 
           file: params.file // etc.
   }

凭证在主 Jenkins > Credentials 中定义。

可能它也对你有用吗?


推荐阅读