Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using parameters within a shell command in Jenkinsfile for Jenkins pipeline

I want to use defined parameters in Jenkinsfile in several shell commands, but I get an exception. In my example I want to execute a simple docker command. The parameter defines the path to docker executable.

This is my very short Jenkinsfile:

pipeline {
  agent any

  parameters {
    string(defaultValue: '/Applications/Docker.app/Contents/Resources/bin/docker', description: '', name: 'docker')
  }

  stages {
    stage('Test') {
      steps {
        sh 'sudo ${params.docker} ps -a'
      }
    }
  }
}

And I get the following exception:

[e2e-web-tests_master-U4G4QJHPUACAEACYSISPVBCMQBR2LS5EZRVEKG47I2XHRI54NCCQ] Running shell script
/Users/Shared/Jenkins/Home/workspace/e2e-web-tests_master-U4G4QJHPUACAEACYSISPVBCMQBR2LS5EZRVEKG47I2XHRI54NCCQ@tmp/durable-e394f175/script.sh: line 2: ${params.docker}: bad substitution

When I change the Jenkinsfile without using the paramter inside the shell command it passes successfully:

pipeline {
  agent any

  parameters {
    string(defaultValue: '/Applications/Docker.app/Contents/Resources/bin/docker', description: '', name: 'docker')
  }

  stages {
    stage('Test') {
      steps {
        sh 'sudo /Applications/Docker.app/Contents/Resources/bin/docker ps -a'
      }
    }
  }
}

So, how can I use parameters inside a shell command in Jenkinsfile? I tried string and text as parameter types.

like image 277
GRme Avatar asked Aug 23 '17 10:08

GRme


1 Answers

The issue you have is that single quotes are a standard java String.

Double quotes are a templatable String, which will either return a GString if it is templated, or else a standard Java String.

So it you use double quotes:

  stages {
    stage('Test') {
      steps {
        sh "sudo ${params.docker} ps -a"
      }
    }
  }

then params.docker will replace the ${params.docker} inside the 'sh' script in the pipeline.

If you want to put " inside the "sudo ${params.docker} ps -a" it doesn't work like bash (which is confusing) you use java style escaping, so "sudo \"${params.docker}\" ps -a"

like image 115
JamesD Avatar answered Sep 29 '22 02:09

JamesD