Jenkins load env vars from file with expanding

Suppose you have some .env files that you would like to use in Jenkins.

rabbitmq.env

RABBITMQ_DEFAULT_USER=guest

celery.env

AMQP_USERNAME=${RABBITMQ_DEFAULT_USER}

If you use this files somewhere else, for example in Docker, you do not want to convert them to groovy files that natively loaded by Jenkins.

So you need some code that will load this .env file into Jenkins environment vars (env.*).

This simple groovy function will load .env file (with key=value on each line) into Jenkins env. So after that you could use env.AMQP_USERNAME in you Jenkinsfile.

The problem with this function - it won’t expand vars. That means that env.AMQP_USERNAME will be equal string ${RABBITMQ_DEFAULT_USER}.

If you want all environment vars like ${..} to be expanded (substituted with their respective values) we should find another solution.

For this purpose I created this simple groovy function and some Python code:

How to use it in declarative Jenkinsfile:

pipeline {
    // ...
    stages {
        // ...
        stage('Prepare environment') {
            steps {
                script {
                // ...
                vars_text = sh(
                    script: """python expand_vars.py \
                            rabbitmq.env \
                            celery.env
                            """,
                    returnStdout: true
                )
                loadVarsFromText(vars_text)
                // ...
                }
            }
        }
        // ...
    }
    // ...
}
// ...
private void loadVarsFromText(String text) {
    // ...
}

With this approach Jenkins env vars will be loaded from .env file and expended so env.AMQP_USERNAME == guest