Search code examples
jenkinscontinuous-integrationjenkins-groovyjenkins-job-dsl

How do I pass arguments to a Jenkins DSL inline shell script?


I have a Jenkins step which needs to run an inline shell script. The script requires a couple of arguments, which are contained in the config. What's the correct way of doing this? The shell script does need to be inline and can't be in a separate file. I've tried something like this, but it doesn't work.

stage('Build Image') {              
    steps {
        script {
            docker.withRegistry('.......', 'Gitlab') {
                CHECK_SHA_RESULT = sh '''
                    ARG1=$1
                    ARG2=$2
                    // Do other stuff and output a result
                ''' ${config.var1} ${config.var2}
            }
        }
    }
}

Solution

  • There are two options to pass values:

    1. string interpolation
    2. expand environment variables

    String Interpolation

    You may just pass values by expanding variables in Groovy strings:

    sh """\
        ARG1=${config.var1}
        ARG2=${config.var2}
        echo $ARG1
        echo $ARG2
    """
    

    (double quotes are used instead of single one)

    You must be careful, because the values are fist expanded and next the code is executed. It means you are able to inject code. Example:

    • config file:
      var1=text; cat /etc/passwd
      var2=hello
      
    • executed code:
      ARG1=text; cat /etc/passwd
      ARG2=hello
      echo $ARG1
      echo $ARG2
      

    Environment Variables

    You may inject values by using environment variables. It is much safer, because the values are expanded by the shell process (prevent command injection).

    withEnv([
        "ARG1=${config.var1}",
        "ARG2=${config.var2}"
    ]) {
        sh '''\
            echo $ARG1
            echo $ARG2
        '''
    }
    

    (sh script is defined by using singe quotes)

    Example:

    • config file:
      var1=text; cat /etc/passwd
      var2=hello
      
    • available environment variables:
      • ARG1 = text; cat /etc/passwd
      • ARG2 = hello
    • executed code:
      echo $ARG1
      echo $ARG2