How to set up envVars in container in Jenkins pipeline with Kubernetes plugin

12/19/2018

I'm setting up a Jenkins pipeline with Kubernetes, there is an option to set environment variables for a container in containerTemplate. Is there some option to override those values in container i.e.:

container(
  name: 'my-container',
  envVars: [
    envVar(key: $KEY, value: $VALUE)
 ]) {
   ...
 }

because some variables are derived during build stages and cannot be set up in podTemplate. The example above unfortunately does not work.

-- Sobik
jenkins-pipeline
kubernetes

1 Answer

12/19/2018

Note that as of this writing as per the docs:

The container statement allows to execute commands directly into each container. This feature is considered ALPHA as there are still some problems with concurrent execution and pipeline resumption

I believe there is not an option. However, you can try setting the variables in the sh command. For example:

def label = "mypod-${UUID.randomUUID().toString()}"
podTemplate(label: label, containers: [
    containerTemplate(name: 'maven', image: 'maven:3.3.9-jdk-8-alpine', ttyEnabled: true, command: 'cat'),
    containerTemplate(name: 'golang', image: 'golang:1.8.0', ttyEnabled: true, command: 'cat')
  ]) {

    node(label) {
        stage('Get a Maven project') {
            git 'https://github.com/jenkinsci/kubernetes-plugin.git'
            container('maven') {
                stage('Build a Maven project') {
                    sh 'MYENV1=value1 MYEVN2=value2 mvn -B clean install'
                }
            }
        }

        stage('Get a Golang project') {
            git url: 'https://github.com/hashicorp/terraform.git'
            container('golang') {
                stage('Build a Go project') {
                    sh """
                    mkdir -p /go/src/github.com/hashicorp
                    ln -s `pwd` /go/src/github.com/hashicorp/terraform
                    MYENV1=value1 MYEVN2=value2 cd /go/src/github.com/hashicorp/terraform && make core-dev
                    """
                }
            }
        }

    }
}
-- Rico
Source: StackOverflow