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

Set environment variables to Jenkins pipeline for deploying kubernetes pods

我有 Kubernetes 集群,其中部署并扩展了 Jenkins, 下面是我在 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 构建之前,我在 Jenkins 管道中设置了 env var,例如:

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

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

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

    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 文件中的变量。