为 Jenkins 管道设置环境变量以部署 kubernetes pod

时间:2021-04-26 05:40:19

标签: jenkins kubernetes docker-compose

我有部署和扩展 Jenkins 的 Kubernetes 集群, 在我在 Jenkins 管道中运行的 podTemplate yaml 文件下方:

podTemplate(yaml: """
apiVersion: v1
kind: Pod
spec:
  containers:
  - name: docker
    image: docker/compose
    command: ['cat']
    tty: true
    volumeMounts:
    - name: dockersock
      mountPath: /var/run/docker.sock
  volumes:
  - name: dockersock
    hostPath:
      path: /var/run/docker.sock
"""
  ) {

  def image = "image/name"
  node(POD_LABEL) {
    stage('Build and run Docker image') {
      git branch: 'test', 
      credentialsId: 'github-credentials',
      url: 'https://github.com/project/project.git'
      container('docker') {
        sh "docker-compose up -d --build"
      }
    }
  }
}

我有一个错误:

[Pipeline] sh
+ docker-compose up -d --build
The ENV variable is not set. Defaulting to a blank string.
[Pipeline] }

在这种部署期间设置环境变量的最佳做法是什么?

更新: 是的,它在詹金斯之外工作, 我已经在 docker compose yaml 文件中列出了 env var 文件:

...
    context: ./validator
    ports:
      - '${VALIDATOR_PROD_ONE_PORT}:${VALIDATOR_PROD_ONE_PORT}'
    volumes:
      - ./validator/logs_1:/usr/src/app/logs
    ***env_file: .env.validator.test***
...

当然,我在执行 docker-compose build 之前在 Jenkins 管道中设置了 env var,例如:

container('docker') {
***sh ' echo "someEnvVar=value" > .env.validator.test'***
   sh "docker-compose up -d --build"
 }

这种方式也行,但不美观(:

1 个答案:

答案 0 :(得分:0)

您应该能够在舞台上设置环境变量,如下所示:

    stage('Build and run Docker image') {
      environment {
        SOME_ENV_VAR = "SOME_VAL"
      }
      git branch: 'test', 
      credentialsId: 'github-credentials',
      url: 'https://github.com/project/project.git'
      container('docker') {
        sh "docker-compose up -d --build"
      }
    }

这实际上将设置 shell 环境变量,该变量应位于 .env 文件中的变量之前。