7

I have the following setup:

(Stripped out) Jenkinsfile:

@Library('my-custom-library') _

pipeline {
    agent any
    stages {
        stage('Example') {
            steps {
                printHello name: 'Jenkins'
            }
        }
    }
}

my-custom-library/resources/com/org/scripts/print-hello.sh:

#!/bin/bash

echo "Hello, $1"

my-custom-library/vars/printHello.groovy:

def call(Map parameters = [:]) {
    def printHelloScript = libraryResource 'com/org/scripts/print-hello.sh'
    def name = parameters.name
    //the following line gives me headaches
    sh(printHelloScript(name))
}

I expect Hello, Jenkins, but it throws the following exception:

groovy.lang.MissingMethodException: No signature of method: java.lang.String.call() is applicable for argument types: (java.lang.String) values: [Jenkins]

Possible solutions: wait(), any(), wait(long), split(java.lang.String), take(int), each(groovy.lang.Closure)

So, is it possible to do something like described above, without mixing Groovy and Bash code?

ebu_sho
  • 394
  • 6
  • 17
  • Related: [How to invoke bash functions defined in a resource file from a Jenkins pipeline Groovy script?](https://stackoverflow.com/q/40213654/1015595) – Big McLargeHuge Jul 04 '20 at 15:10

1 Answers1

8

Yes, check out withEnv

The example they give looks like;

node {
  withEnv(['MYTOOL_HOME=/usr/local/mytool']) {
    sh '$MYTOOL_HOME/bin/start'
  }
}

More applicable to you:

// resources/test.sh
echo "HI here we are - $PUPPY_DOH --"

// vars/test.groovy
def call() {
   withEnv(['PUPPY_DOH=bobby']) {
    sh(libraryResource('test.sh'))
  }
}

Prints:

[Pipeline] {
[Pipeline] withEnv
[Pipeline] {
[Pipeline] libraryResource
[Pipeline] sh
+ echo HI here we are - bobby --
HI here we are - bobby --
[Pipeline] }
[Pipeline] // withEnv
[Pipeline] }

Using that, you can pass it in using a scoped named variable, something like

def call(Map parameters = [:]) {
    def printHelloScript = libraryResource 'com/org/scripts/print-hello.sh'
    def name = parameters.name
    withEnv(['NAME=' + name]) { // This may not be 100% syntax here ;)
    sh(printHelloScript)
}

// print-hello.sh
echo "Hello, $name"
chrisb
  • 393
  • 2
  • 10
  • You can use `withEnv(["NAME=${name}"])` (note the double qoutes). You might also want to escape the variable contents first. – iliis Nov 04 '20 at 11:53