在 Jenkins 使用當中,是否有遇到兩個 pipeline 只差了一點點的呢? 在 Jenkinsfile 中我們可以引入 parameter 來解決這個困擾。
// A pipeline
pipeline{
    agent any
    stages{
        stage('Sample'){
            steps{
                echo "This is ithome speaking."
            }
        }
    }
}
// B pipeline
pipeline{
    agent any
    stages{
        stage('Sample'){
            steps{
                echo "This is jenkins speaking."
            }
        }
    }
}
The parameters directive provides a list of parameters that a user should provide when triggering the Pipeline. The values for these user-specified parameters are made available to Pipeline steps via the params object, see the Parameters, Declarative Pipeline for its specific usage.
(https://www.jenkins.io/doc/book/pipeline/syntax/#parameters)
依照官網,我們可以先將常見 parameter 分成下列幾種
pipeline{
    parameters {
        booleanParam(name: 'POC', defaultValue: false)
    }
    ......
    script{
        if (params.POC){
            // do poc processing
        } else{
            ......
        }
    }
}
pipeline{
    parameters {
        text(name: 'env', defaultValue: 'testing')
    }
    ......
    script{
        if (params.env == "testing"){
            // do testing processing
        } else if (params.env == "poc"){
            // do poc processing
        } else if (params.env == "prod"){
            // do production processing
        } else {
            // error handling
        }
    }
}
pipeline{
    parameters {
        choice(name: 'env', choices: ['testing', 'poc', 'prod'])
    }
    ......
    script{
        if (params.env == "testing"){
            // do testing processing
        } else if (params.env == "poc"){
            // do poc processing
        } else if (params.env == "prod"){
            // do production processing
        }
    }
}
pipeline{
    parameters {
        password(name: 'db_passwd')
    }
    ......
    script{
        sh "psql postgresql://root:${params.db_passwd}@127.0.0.1:5432/sample-db"
    }
}
建議用 Credentials Binding Plugin 取代。
所以今天一開始提到的範例我們可以用 String Parameter 來做優化。
pipeline{
    parameters {
        text(name: 'Who', defaultValue: '')
    }
    agent any
    stages{
        stage("Sample"){
            steps{
                echo "This is ${params.Who} speaking."
            }
        }
    }
}
https://blog.johnwu.cc/article/jenkins-pipeline-job-boolean-parameter.html
https://www.jenkins.io/doc/book/pipeline/syntax/#parameters