Inheriting the Environment Variables from the Jenkins Host in Docker

Featured image for sharing metadata for article

If you're running your Jenkins builds in (Docker) containers - which I would recommend - you may have noticed that not all of your environment variables are passed through to the container from the host.

Fortunately this is straightforward to do, but has a slight implementation difference depending on how your pipeline is set up.

We'll use the contrived example of passing through the AWS_REGION and HOSTNAME environment variables to the container.

Declarative Pipeline

If you're using a declarative pipeline you'll likely have something like:

pipeline {
  agent {
    docker {
      image 'alpine'
    }
  }
  stages {
    stage('Environment Variables') {
      steps {
        sh 'env'
      }
    }
  }
}

And to pass the variables, we can pass the following argument:

 pipeline {
   agent {
     docker {
       image 'alpine'
+      args '-e AWS_REGION=$AWS_REGION -e HOSTNAME=$HOSTNAME'
     }
   }
   stages {
     stage('Environment Variables') {
       steps {
         sh 'env'
       }
     }
   }
 }

Note the single quotes, which must be done, otherwise Jenkins will attempt to resolve it as part of the WorkflowScript it's running, which will either not exist, or not be correct. Single quotes allows it to be interpolated at the right time, and pull the variables correctly.

Scripted Pipeline

If you're using a scripted pipeline you'll likely have something like:

docker.image('alpine').inside {
  stage('Environment Variables') {
    sh 'env'
  }
}

And to pass the variables, we can pass the following argument:

-docker.image('alpine').inside {
+docker.image('alpine').inside('-e AWS_REGION=$AWS_REGION -e HOSTNAME=$HOSTNAME') {
   stage('Environment Variables') {
     sh 'env'
   }
 }

Note the single quotes, which must be done, otherwise Jenkins will attempt to resolve it as part of the WorkflowScript it's running, which will either not exist, or not be correct. Single quotes allows it to be interpolated at the right time, and pull the variables correctly.

Written by Jamie Tanna's profile image Jamie Tanna on , and last updated on .

Content for this article is shared under the terms of the Creative Commons Attribution Non Commercial Share Alike 4.0 International, and code is shared under the Apache License 2.0.

#blogumentation #docker #jenkins.

This post was filed under articles.

Interactions with this post

Interactions with this post

Below you can find the interactions that this page has had using WebMention.

Have you written a response to this post? Let me know the URL:

Do you not have a website set up with WebMention capabilities? You can use Comment Parade.