Reputation: 15394
I am in the process of putting together a shared library for my Jenkins builds. I haven't really used groovy much before so at the moment I am following the docs (always a good start :-)) and have created a file located at /vars/myFile.groovy
for example.
Now I have a list (shortened in the example below) that I need to use and have placed it within a method for now, but am I right in thinking it would be better outside of the method so that it is only instantiated once rather than every time the method is called?
/vars/myFile.groovy
#!/usr/bin/groovy
def slack_handle(String dev_name) {
developerList = [
[name: "Richard Lewis", slack_handle: "<@richardlewis123>"],
[name: "Mark Turner", slack_handle: "<@markTurner123>"]
]
return developerList.find {it['name'] == dev_name}?.get("slack_handle")
}
def other_method() {
}
def another_method() {
}
Then in my Jenkinsfile i can just do
SLACK_HANDLE = slackNotification.slack_handle("Richard Lewis")
echo "${SLACK_HANDLE}"
"<@richardlewis123>"
How can i declare the list outside of the method to then use within my slack_handle
method in this shared library
I have tried
final def developerList = [
[name: "Richard Lewis", slack_handle: "<@richardlewis123>"],
[name: "Mark Turner", slack_handle: "<@markTurner123>"]
]
def slack_handle(String dev_name) {
return developerList.find {it['name'] == dev_name}?.get("slack_handle")
}
def other_method() {
}
def another_method() {
}
But when the Jenkins job runs developerList
is undeclared.
So my question is, should the List be declared outside of the method or in this instance is it OK where it is?
Upvotes: 3
Views: 1067
Reputation: 1858
You need to annotate the List with @Field
import groovy.transform.Field
def call(String dev_name) {
return slack_handle(dev_name)
}
def slack_handle(String dev_name) {
return developerList.find {it['name'] == dev_name}?.get("slack_handle")
}
def otherMethod() {
echo "I got called"
}
@Field
def developerList = [
[name: "Richard Lewis", slack_handle: "<@richardlewis123>"],
[name: "Mark Turner", slack_handle: "<@markTurner123>"]
]
Function can then be used in the Pipeline e.g. the following way:
node {
stage('Call Function') {
// either
echo myFile("Mark Turner")
// or
echo myFile.slack_handle("Mark Turner")
myFile.otherMethod()
}
}
Upvotes: 3