Pudding
Pudding

Reputation: 553

Jenkinsfile can't use function from dynamically loaded library

I load my library dynamically in the Jenkinsfile like so

library identifier: 'custom-lib', retriever: modernSCM(
    [$class: 'GitSCMSource',
    remote: 'https://github.mygit.io/owner/jenkins-libraries.git',
    credentialsId: 'gitcred'])

When I don't call a method from the library in the following stages it runs fine and I can see the methods available on the replay.

How ever when I attempt to call a method in a step block as follows

 steps{
     run-terraform()
 }

I get the error

WorkflowScript: 32: Expected a step @ line 32, column 17.
                   run-terraform()
                   ^

It looks like while Jenkins is interpreting the Jenkinsfile it does not load the library first and assumes run-terraform() does not exist. Yet when I dynamically load the library and forego calling any methods it looks like the Jenkinsfile is valid and runs.

I feel like I am missing something obvious when it comes to loading custom-lib. When I predefine the library in Jenkins before hand and call it using @Library it works fine.

How do I call a method from a dynamically loaded library?

Upvotes: 1

Views: 818

Answers (1)

Matthew Schuchard
Matthew Schuchard

Reputation: 28774

If you want to invoke a method from a shared library, then it must be inside a scripts block. You can adjust your code accordingly:

steps {
  script {
    run-terraform()
  }
}

and then it should work for you just fine.

Upvotes: 3

Related Questions