unagirabbit's blog

気づいたことをメモしています

【Jenkins】シングルクォート変数展開

シングルクォートは通常だと変数展開できないが、
withEnvでを使うことで環境変数として定義することができる。
外部プログラムや秘密テキスト類を使うときに利用する。

withEnvを利用する

www.jenkins.io

withEnv(["hoge=${params.BRANCH}", "fuga=user/home/fuga"]) {
    sh 'echo $hoge $fuga'
}

{name}={value}の形式で指定し、複数指定することが可能です。
Credentialsのテキストをダブルクォートで展開しようとすると以下の警告が表示されます。

The following steps that have been detected may have insecure interpolation of sensitive variables (click here for an explanation):

そういう際にwithEnvを使うようにしましょう。

pipeline {
    agent any
    parameters {
        string defaultValue: 'develop', name: 'BRANCH'
    }
    stages {
        stage("hoge") {
            steps {
                withCredentials([usernamePassword(credentialsId: "my_account", usernameVariable: 'ID', passwordVariable: 'PW')]) {
                    withEnv(["_branch=${params.BRANCH}"]) {
                        sh 'hoge.sh $_branch $ID $PW'
                    }
                }
            }
        }
    }
}

www.jenkins.io