Eduard Ahmatgareev
Eduard Ahmatgareev

Reputation: 51

Jenkins withCredentials in dynamic selected parameters

could you help me with a litle throuble?

I tried find solution with jenkins and your wonderful plugin: uno-choice, but I couldn't it.

I have very simple script:

#!/usr/bin/env groovy
def sout = new StringBuffer(), serr = new StringBuffer()
def proc ='/var/lib/jenkins/script.sh location'.execute()

proc.consumeProcessOutput(sout, serr)
proc.waitForOrKill(1000)

def credential(name) {
   def v;
   withCredentials([[$class: 'UsernamePasswordMultiBinding', credentialsId: name, usernameVariable: 'USERNAME', passwordVariable: 'PASSWORD']]) {
       v = "${env.USERNAME}"
   }
   return v
}

def key = credential('aws_prod_api')

String str = sout.toString()
String s = str.trim()
String[] items = s.split(",");
def v1 = Arrays.asList(items)
return v1

In general I want get AWS Credentional which save in Jenkins from bash script and with it do something.

I want use withCredentials in block which make selected list, but I don't understand how I can do it.

Could you help me with it? I will very appreciate it

I tried using withCredentials inside groovy, but I got error:

Fallback to default script... groovy.lang.MissingMethodException: No signature of method: Script1.withCredentials() is applicable for argument types: (java.util.ArrayList, Script1$_credential_closure1) values: [[[$class:UsernamePasswordMultiBinding, credentialsId:aws_prod_api, ...]], ...] at org.codehaus.groovy.runtime.ScriptBytecodeAdapter.unwrap(ScriptBytecodeAdapter.java:58) at org.codehaus.groovy.runtime.callsite.PogoMetaClassSite.callCurrent(PogoMetaClassSite.java:81) at

Upvotes: 3

Views: 7497

Answers (1)

cloudartisan
cloudartisan

Reputation: 656

It's because withCredentials does not exist in the scope of Script1. It exists in the scope of the Jenkinsfile DSL. You need to pass it in.

I suggest converting your script to functions. Then passing the Jenkinsfile DSL through to your Groovy code.

def doAwsStuff(dsl) {
   ...
   def key = credential(dsl, 'aws_prod_api')
   ...
}

def credential(dsl, name) {
   def v;
   dsl.withCredentials([[$class: 'UsernamePasswordMultiBinding', credentialsId: name, usernameVariable: 'USERNAME', passwordVariable: 'PASSWORD']]) {
       v = "${env.USERNAME}"
   }
   return v
}

and then call it from your Jenkinsfile with:

def result = MyAwsStuff.doAwsStuff(this)

Upvotes: 1

Related Questions