如何在 config.ini 文件中使用 Jenkins 环境变量?

How to use Jenkins environment variables in config.ini file?

我想在我的 config.ini 文件中使用数据库 username/password。我的 Jenkinsfile:

中有以下 withCredentials 行

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

我没有在我的 Jenkinsfile 中明确调用此 config.ini 文件,但我确实使用 bash 脚本来:

export CONFIG_FILE='config.ini'

有没有办法在我的 config.ini:

中相应地设置这些
DB_USERNAME = {DATABASE_USER}
DB_PASSWORD = {DATABASE_PASSWORD}

Bash 可以为您做到这一点。您有两个选择:

  1. 使用envsubst。您需要在所有节点上安装它(它通常是 gettext 包的一部分)。
  2. 使用邪恶的评估

完整示例:

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.