How to pass parameter to function in Jenkins pipeline and pass it to the ssh command

321 Views Asked by At

I have following script

    def Greet(name){
      echo "Hello ${name}" // printing output on console as Hello Amol
      sh 'ssh -i @hostId "echo Hello ${name}"' // not printing anything on console. print only echo  
}

node() {
       stage("Hello") {
             Greet('Amol')
       }
}

How to print the ${name} variable value with ssh command. Can someone please help

1

There are 1 best solutions below

1
fajarhide On

In the sh command, I've replaced the single quotes (') with double quotes (") to allow variable interpolation. I've also escaped the $ character before name using a backslash (\) to prevent Jenkins from trying to interpolate the name variable locally. For example like this

def Greet(name) {
  echo "Hello ${name}"
  sh "ssh -i @hostId 'echo Hello \${name}'" 
}

node {
  stage("Hello") {
    Greet('Amol')
  }
}