What I’m running in order to create a random password with alphanumeric and special characters:
randomPasswordCreation = random_password_creation(14)
println "Random pass: $randomPasswordCreation"
def random_password_creation(pass_length ){
def special = ['!','@','#','$','%','&']
def pool = ['a'..'z','A'..'Z',0..9,'_'].flatten().plus(special);
Random rand = new Random(System.currentTimeMillis());
def passChars = (0..pass_length - 1).collect { pool[rand.nextInt(pool.size)] };
def specialChar = special[rand.nextInt(special.size)]
passChars[rand.nextInt(passChars.size)] = specialChar
def PASSWORD = passChars.join();
return PASSWORD
}
What I receive as error:
org.jenkinsci.plugins.scriptsecurity.sandbox.RejectedAccessException: No such field found: field java.lang.String size
at org.jenkinsci.plugins.scriptsecurity.sandbox.groovy.SandboxInterceptor.unclassifiedField(SandboxInterceptor.java:426)
at org.jenkinsci.plugins.scriptsecurity.sandbox.groovy.SandboxInterceptor.onGetProperty(SandboxInterceptor.java:410)
at com.cloudbees.groovy.cps.CpsDefaultGroovyMethods.collect(CpsDefaultGroovyMethods:3170)
at com.cloudbees.groovy.cps.CpsDefaultGroovyMethods.collect(CpsDefaultGroovyMethods:3140)
at WorkflowScript.run(WorkflowScript:1922)
>Solution :
There are at least two problems with the code you have shown:
- You access
sizeas it was a field, but it is a method, so it should besize()instead. - The
passChars.join()is missing a separator argument, e.g.''for an empty string.
Based on the error stack trace, I assume you are running this code as a part of a Jenkins Pipeline. Keep in mind, that Jenkins executes Groovy in a more restrictive way. For instance, while the regular dynamic Groovy can handle things like .size instead of .size(), the WorkflowScript executor requires that the Groovy code is free from such mistakes.