CIsForCookies
CIsForCookies

Reputation: 12807

How to send optional arguments via jenkins

I have a jenkins pipeline that gets arguments that will affect a the args for a python script I want to run:

Jenkins file:

pipeline {
    agent {label "master"}
    parameters {
        string(name: "add_option_x", defaultValue: '')
        string(name: "add_option_y", defaultValue: '')
    }
    stages {
        stage ("Z") {
            agent {label "master"}
            steps { 
                script {
                    sh "python my_script.py <OPTIONAL_ARGS>"
                } } } }

Python script:

from argparse import ArgumentParser
p = ArgumentParser()
p.add_argument('--x')
p.add_argument('--y')
print(vars(p.parse_args()))

Now, I want to be able to send via jenkins 4 options of args to the script:

 1. sh "python my_script.py"
 2. sh "python my_script.py --x ${params.x}"
 3. sh "python my_script.py --y ${params.y}"
 4. sh "python my_script.py --x ${params.x} --y ${params.y}"

What would be the best way to do so? (I don't want to have a global string "python my_script.py" and, loop over the params, and add a sub string whenever I find the param is not empty. It would look awful in groovy, AFAIK)

Upvotes: 0

Views: 717

Answers (1)

cfrick
cfrick

Reputation: 37008

If you don't want to write a loop, you can optionally replace inside the string:

def params = [x: "x"]
println """python thescript ${params.x ? "-x ${params.x}" : ""} ... """
// => python thescript -x x ... 

Which is pretty verbose, but you can do what you want with each argument (e.g. transform the values, add multiple different args, ...).

If you just want a simple mapping from param to argument, a "loop" version would like this:

def params = [x: "x"]

def args = [x: "--the-x", y: "--some-y"].findAll{
    it.key in params
}.collect{
    "${it.value} '${params[it.key]}'"
}.join(" ")

println args
// => --the-x 'x'

Upvotes: 1

Related Questions