Home > Software design >  How to use Jenkins environment variables in config.ini file?
How to use Jenkins environment variables in config.ini file?

Time:09-29

I am looking to use a database username/password in my config.ini file. I have the following withCredentials line in my Jenkinsfile:

withCredentials([usernamePassword(credentialsId: 'database', usernameVariable: 'DATABASE_USER', passwordVariable: 'DATABASE_PASSWORD')])

I don't explicitly call this config.ini file in my Jenkinsfile, however I do use a bash script to:

export CONFIG_FILE='config.ini'

Is there any way to set these accordingly in my config.ini:

DB_USERNAME = {DATABASE_USER}
DB_PASSWORD = {DATABASE_PASSWORD}

CodePudding user response:

Bash can do this for you. You have two options:

  1. Use envsubst. You'll need to install it on all of your nodes (it's usually part of the gettext package).
  2. Use evil eval

Full example:

pipeline {
    agent {
        label 'linux' // make sure we're running on Linux
    }
    
    environment {
        USER = 'theuser'
        PASSWORD = 'thepassword'
    }
    
    stages {
        stage('Write Config') {
            steps {
                sh 'echo -n "user=$USER\npassword=$PASSWORD" > config.ini'
            }    
        }
        
        stage('Envsubst') {
            steps {
                sh 'cat config.ini | envsubst > config_envsubst.ini'
                sh 'cat config_envsubst.ini'
            }
        }
        
        stage('Eval') {
            steps {
                sh 'eval "echo \"$(cat config.ini)\"" > config_eval.ini'
                sh 'cat config_eval.ini'
            }
        }
    }
}

This this Stackexchange question for more options.

  • Related