Set environment variables to Jenkins pipeline for deploying kubernetes pods

Viewed 1225

I have Kubernetes Cluster where deployed and scaled Jenkins, below podTemplate yaml file which I run in Jenkins pipeline:

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"
      }
    }
  }
}

I have got an error:

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

Which is best practice to set env vars during the this kind of deployments?

Update: yes, it's working outside of Jenkins, I have listed env var files in docker compose yaml file:

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

Of course I cat set env var in Jenkins pipeline before executing docker-compose build like this, for example:

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

This way also working, but not beautiful (:

1 Answers

You should be able to set environment variables on your stage as following:

    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"
      }
    }

This would essentially set shell Environment variables, which should precede over those in .env file.

Related