Reputation: 450
I am currently using a Jenkins library without issues from my jobs. Right now I am trying to do some refactor, there is a chunk of code to determine with AWS account to use in almost every tool we currently have in the library.
I created the following file "get account.groovy"
class GetAccount {
def getAccount(accountName) {
def awsAccount = "abcd"
return awsAccount;
}
}
Then I am trying to do this from within one of the other groovy scripts:
def getaccount = load 'getaccount.groovy'
def awsAccount = getaccount.getAccount(account)
But that does not work since it is looking for that file in the current work directory not in the library directory
I am unable to figure out what the best way to call another class from within a library that is already being used.
Upvotes: 0
Views: 2135
Reputation: 2098
Jenkins load
DSL is meant to load an externalize groovy file that is available in the job workspace and it will not work if you try to load a groovy script available in Jenkins shared library, because the shared library never checkout in the job Workspace.
If you follow the standard shared library structure like below, it could be done like :
shared-library
├── src
│ └── org
│ └── any
│ └── GetAccount.groovy
└── vars
└── aws.groovy
GetAccount.groovy
package org.any
class GetAccount {
def getAccount(accountName) {
def awsAccount = "abcd"
return awsAccount;
}
}
aws.groovy
import org.any;
def call() {
def x = new GetAccount()
// make use of val and proceed with your further logic
def val = x.getAccount('xyz')
}
In your Jenkinsfile (declarative or scripted ) you can use both the shared library groovy class like :
make use of aws.groovy
scripted pipeline
node {
stage('deploy') {
aws()
}
}
declarative pipeline
pipeline {
agent any;
stages {
stage('deploy') {
steps {
aws()
}
}
}
}
make use of GetAccount.groovy scripted pipeline
import org.any
node {
stage('deploy') {
def x = new GetAccount()
// make use of val and proceed with your further logic
def val = x.getAccount('xyz')
}
}
declarative pipeline
import org.any
pipeline {
agent any;
stages {
stage('deploy') {
steps {
script {
def x = new GetAccount()
// make use of val and proceed with your further logic
def val = x.getAccount('xyz')
}
}
}
}
}
Upvotes: 1