通过 Jenkinsfile 传递凭据 -> Docker-compose -> Docker

Passing credentials though Jenkinsfile -> Docker-compose -> Docker

我需要通过环境变量将凭据推送到 docker 容器。此容器从 docker-compose 文件启动,该文件由 Jenkins 使用 CI/CD 维护。我将凭据存储在 Jenkins 中,作为全局域下的单独秘密文本条目。据我所知,我可以在构建阶段使用 credentials 函数通过 environment 块填充这些凭据。我对 Jenkinsfile 的尝试如下所示:

#!groovy
pipeline {
    agent any

    stages {
        stage("build") {
            environment {
                DISCORD_TOKEN = credentials('DICEBOT_DISCORD_TOKEN')
                APPLICATION_ID = credentials('DICEBOT_APPLICATION_ID')
            }

            steps {
                sh 'docker-compose up --build --detach'
            }
        }
    }
}

没有为错误打印太多内容。我得到的只是这个简单的错误:ERROR: DICEBOT_APPLICATION_ID。这就对了。那么我存储密文的范围是不是不对呢?我在读到,由于该域是全球性的,因此任何人都应该能够访问它。那么也许我对域范围界定的想法是错误的? Jenkinsfile 中 environment 的位置是否错误? 我不知道。错误非常平淡,并没有真正描述它不喜欢 DICEBOT_APPLICATION_ID.

的地方

更糟糕的是,解决这个问题甚至没有真正解决手头的主要问题:让 docker 容器保存这些凭据。我目前正在处理的问题只是将环境变量的范围限定为 运行 docker-compose 并且可能不会将环境变量填充到我需要它们的容器中。

对于第二部分,让 docker-compose 将凭据传递给容器,我认为下面的代码片段可能会成功吗?

version: "3"
services:
  dicebot:
    environment:
      DISCORD_TOKEN: ${DISCORD_TOKEN}
      APPLICATION_ID: ${APPLICATION_ID}
    build:
      context: .
      dockerfile: Dockerfile

解决方案

如果您只打算在该阶段使用这些变量,那么环境块位于正确的位置。您的 docker-compose.yml 文件看起来不错,但您没有将环境变量作为构建参数传递给 docker-compose 命令。请看下面我的修改

 steps {
      sh "docker-compose build --build-arg DISCORD_TOKEN='$DISCORD_TOKEN' --build-arg APPLICATION_ID='$APPLICATION_ID' --detach --verbose"
      sh "docker-compose up -d"
 }

I'm assuming the docker-compose.yml is in the same repository as your Jenkinsfile. Be cognizant of the scope of your credentials.