Despite following this answer and others, I am unable to successfully use a local groovy file in my Jenkinsfile (both are in the same repository).
def deployer = null
...
...
...
pipeline {
agent {
label 'cf_slave'
}
options {
skipDefaultCheckout()
disableConcurrentBuilds()
}
stages {
stage ("Checkout SCM") {
steps {
checkout scm
}
}
...
...
...
stage ("Publish CF app") {
steps {
script {
STAGE_NAME = "Publish CF app"
deployer = fileLoader.load ('deployer')
withCredentials(...) {
if (BRANCH_NAME == "develop") {
...
...
...
} else {
deployer.generateManifest()
}
}
}
}
}
...
...
}
deployer.groovy:
#!/usr/bin/env groovy
def generateManifest() {
sh "..."
echo "..."
}
In the console log (stack):
[Pipeline] stage
[Pipeline] { (Publish CF app)
[Pipeline] script
[Pipeline] {
[Pipeline] echo
before loading groovy file
[Pipeline] echo
Loading from deployer.groovy
[Pipeline] load
[Pipeline] // load
[Pipeline] }
[Pipeline] // script
[Pipeline] }
[Pipeline] // stage
Update:
It seems the problem was not with loading the file but rather with the contents of the file, where I execute the following which apparently does not play well:
sh "node $(pwd)/config/mustacher manifest.template.yml config/environments/common.json config/environments/someFile.json"
echo "..."
When only the echo
is there, this is the stack.
So not the sh "node ..."
nor the echo
work. Even changing it just to sh "pwd"
fails as well. What could it be? the syntax in the file? the way it is called in the pipeline?
If I will make the same node call in the pipeline (for example in the withCredentials
if
statement, it works.
In Groovy, we can add a method named call to a class and then invoke the method without using the name call . We would simply just type the parentheses and optional arguments on an object instance. Groovy calls this the call operator: () .
The Jenkins file is a base code for Jenkins which executes it as a Groovy script in Jenkins script console.
Add a return this
to the bottom of the deployer.groovy
file, and then change you load
step to use relative path and extension to groovy file like load('deployer.groovy')
.
The return this
is documented on jenkins.io:
Takes a filename in the workspace and runs it as Groovy source text. The loaded file can contain statements at top level or just load and run a closure. For example:
def pipeline node('slave') { pipeline = load 'pipeline.groovy' pipeline.functionA() } pipeline.functionB()
pipeline.groovy
def pipelineMethod() { ...code } return this
Where pipeline.groovy
defines functionA and functionB functions (among others) before ending with return this
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With