how to write custom def functions in Jenkins Declarative pipeline?

4.8k views Asked by At

i'm posting a simplified version of the pipeline code i wanted but i'm using a custom withAWSCreds plugin from shared libraries in our org, here is the jenkinsfile, this is the different kind of use case i needed in this way only...

edited:

    @Library(['pipeline-step',]) _

pipeline {
agent none
stages {
    stage('build') {
        steps {
            script {
                Closure c = { sh "aws s3 ls" }
                awsAuthenticate('arn:aws-cn:iam::xxx:role/AgentRole','xxx','someRegion',creds:'aws', c)
            }
        }
    }
}

}

def awsAuthenticate(Map map = [:], String role,String account, String region, Closure action){
    if( env.BRANCH_NAME == 'test'  ) {
        withAWSCreds(role: ${role},roleAccount: ${account}, region: ${region}, credentials: ${map.creds ?: '1'}) {
            action ()
        }
    }
    else {
        withAWS([role: "arn:aws:iam::xxx:role/cicd", region: "us-west-1"])
    }
}

i would like to use the withAWSCreds step mentioned in the below def function at multiple stages just calling the function, how do we do that i get different kind of errors, if i remove the line sh 'aws s3 ls' i see authentication happening but i see No body to invoke error.

so how do we write the function and use it in stage block? help is really appreciated

     [[Pipeline] {
[Pipeline] withAWS
Setting AWS region us-west-1 
 Requesting assume roleAssumed role arn:aws:sts::xxxx:assumed-role/deploy/test-jenkins with id VCAYVVUWN:test-jenkins 
 [Pipeline] }
[Pipeline] // script
[Pipeline] }
[Pipeline] // stage
[Pipeline] }
[Pipeline] // withEnv
[Pipeline] End of Pipeline
java.lang.IllegalStateException: There is no body to invoke
    at org.jenkinsci.plugins.workflow.cps.CpsStepContext.newBodyInvoker(CpsStepContext.java:282)    
     
1

There are 1 answers

2
smelm On

The curly braces create an anonymous function which you need to accept and call in you authenticate function.

The way your are calling it

foo (paramA){
    sh "..."
}

boils down to

Closure c = { sh "..." }
foo(paramA, c)

So you need to add a parameter to the signatur accordingly

def foo(paramA, Closure action){
    withAWSCredentials(...){
         action()
    }