Access Jenkins credentials bindings from inside a Jenkins job DSL script - jenkins

I'm not creating a new job.
I want to access a Jenkins secret string binding from inside a job DSL script. I haven't been able to find examples of this.
If I have a secret string binding in Jenkins named "my-secret-string" how do I get the value of that in a DSL script? I want the DSL to make REST calls and other things using secrets I have securely stored in Jenkins.
I cant use credentials('<idCredentials>') because I'm not creating a new job or anything, I want to use those secret values in the DSL script itself.

I don't understand the scenario. You are not creating a new job but you are still inside a job? What does that mean? I understood that you defined a credential - secret text in Jenkinks and you want to access it from a job? This is a standard scenario:
withCredentials([string(credentialsId: 'my-secret-string', variable: 'mySecretStringVar')]){
println mySecretStringVar
}
From Jenkins Console or groovy script epending on where credentials are located:
def getFolderCredsScript(def pipelineFolder, def credId){
def credentialsStore =
jenkins.model.Jenkins.instance.getAllItems(com.cloudbees.hudson.plugins.folder.Folder.class).findAll{it.name.equals(pipelineFolder)}
.each{
com.cloudbees.hudson.plugins.folder.AbstractFolder<?> folderAbs = com.cloudbees.hudson.plugins.folder.AbstractFolder.class.cast(it)
com.cloudbees.hudson.plugins.folder.properties.FolderCredentialsProvider.FolderCredentialsProperty property = folderAbs.getProperties().get(com.cloudbees.hudson.plugins.folder.properties.FolderCredentialsProvider.FolderCredentialsProperty.class)
if(property != null){
for (cred in property.getCredentials()){
if ( cred.id == credId ) {
return "${cred.username}:${cred.password}"
}
}
}
}
}
def getGlobalCredsScript(def credId){
def creds = com.cloudbees.plugins.credentials.CredentialsProvider.lookupCredentials(com.cloudbees.plugins.credentials.common.StandardUsernameCredentials.class, Jenkins.instance, null, null);
for (cred in creds) {
if (cred.id == credId){
return "${cred.username}:${cred.password}"
}
}
}

I found this question when trying to figure out how to set authenticationToken in my jenkins DSL. You can't use withCredential or a credentials call since it only accepts a string. The answer I found is to wrap the build/seed file. It can use withCredential and you pass in the credential as a string like this:
Jenkinsfile.build
withCredentials([
string(credentialsId: 'deploy-trigger-token', variable: 'TRIGGER_TOKEN'),
]) {
jobDsl targets: ".jenkins/deploy_${env.INSTANCE}_svc.dsl",
ignoreMissingFiles: true,
additionalParameters: [
trigger_token: env.TRIGGER_TOKEN
]
}
Then in your dsl file:
pipelineJob("Deploy Service") {
...
authenticationToken (trigger_token)
...
}
So to answer your question, you are correct you can't directly access the credential in your dsl, instead you do it in the seed build file which passes it in as a additionalParameters variable.

Related

Jenkins ec2 plugin ssh keys

I have a groovy script which will configure AWS ec2 plugin with required data. I am able to configure all other inputs. I need to give private key in same region, is there any way that i can generate and configure this key in grrovy script. followed below document and template.
https://gist.github.com/vrivellino/97954495938e38421ba4504049fd44ea
https://github.com/jenkinsci/ec2-plugin/blob/master/src/main/java/hudson/plugins/ec2/SlaveTemplate.java
This will help you to get Jenkins private keys:
EC2Cloud cloud = Jenkins.instance.clouds.find { it instanceof EC2Cloud }
KeyPair key_pair= cloud.getKeyPair()
private_key_text = key_pair.keyMaterial
def secret_key = hudson.util.Secret.decrypt(cloud.getSecretKey()).toString()
I am not sure if this is the right answer to your question, but this is where Google led me when I wanted to decipher the private key for the EC2 Jenkins plugin.
This worked for me with Jenkins 2.190.2.
import hudson.plugins.ec2.AmazonEC2Cloud
def cloud = Jenkins.instance.clouds.find { it instanceof AmazonEC2Cloud }
println cloud.getKeyPair().keyMaterial

job-dsl - How to pass credentials while creating jobs from gitlab repo branches?

I am creating a jobs for each application branches from github.
I am not sure how to pass the credentials to the repo link?
import groovy.json.*
def project = 'app-ras'
def branchApi = new URL("https://gitlab.etctcssd.com/sdadev/${project}/branches")
def branches = new JsonSlurper().parse(branchApi.newReader())
branches.each {
def branchName = it.name
def jobName = "${project}-${branchName}".replaceAll('/','-')
job(jobName) {
scm {
git("https://gitlab.etctcssd.com/sdadev/${project}.git", branchName)
}
}
}
Our project is secure project in gitlab, so how can I pass the credentials in this case?
I am sure it would redirect to login page. But I am not sure how to handle this. Any help would be greatly appreciated.
I hope it will work in the following way:
import groovy.json.JsonSlurper
def project = 'app-ras'
def branchApi = new URL("https://gitlab.etctcssd.com/sdadev/${project}/branches")
def branches = new JsonSlurper().parse(branchApi.newReader())
branches.each {
def branchName = it.name
String jobName = "${project}-${branchName}".replaceAll('/', '-')
job(jobName) {
scm {
git {
branch(branchName)
remote {
url("https://gitlab.etctcssd.com/sdadev/${project}.git")
credentials("HERE")
}
}
}
}
}
Try to substitute HERE with plain credentials (a kind of an access token) or with credential ID (of type Secret text) defined under Jenkins -> Credentials.
Also, are you using gitlab or github?
EDIT
So as far as I understood you have problems with fetching the branches names not with the Jenkins DSL. Here you can see how to fetch branches from gitlab. In groovy in can be done in the following way:
URLConnection connBranches = new URL("https://gitlab.etctcssd.com/sdadev/${project}/branches").openConnection()
connBranches.setRequestProperty("PRIVATE-TOKEN", "PASTE TOKEN VALUE HERE")
new JsonSlurper().parse(new BufferedReader(new InputStreamReader(connBranches.getInputStream())))

How to set an environment variable in Jenkins DSL using the Credentials Binding plugin?

I have created a credential in Jenkins called AZURE_CLIENT_ID. I have the "Credentials Binding Plugin" installed.
If I create a Job manually in the UI I am able to select the Binding I would like for the Environment and select my Secret Text type.
I want to replicate this in my Jobs DSL script. I have found the following snippet which is very close to what I want to do:
job('example-2') {
wrappers {
credentialsBinding {
usernamePassword('PASSWORD', 'jarsign-keystore')
}
}
}
However the credential I want to inject is Secret Text and I cannot find what the function to it with is, e.g. instead of usernamePassword. Does anyone know what this should be please?
'Secret text' kind credentials are retrieved as 'string()' in the credentialBinding context.
For example:
job('example') {
wrappers {
credentialsBinding {
string('SECRETWORD', 'name_of_credential')
}
}
}
Documentation at: https://jenkinsci.github.io/job-dsl-plugin/#method/javaposse.jobdsl.dsl.helpers.wrapper.WrapperContext.credentialsBinding

Job DSL Pipeline Config Trigger

I want to know how can i use Job Dsl to configure trigger "Trigger build remotely" a pipeline job.
I need input string as Authentication Token.
My sample code:
pipelineJob("PipelineJobs") {
logRotator {
daysToKeep(7)
numToKeep(10)
}
concurrentBuild(false)
parameters {
stringParam('PHID',null,null)
stringParam('SHA1',null,null)
}
triggers {
}
}
Thanks.
Internally that option is not a trigger, so you can't find it within the triggers context.
You need to use authenticationToken on the job level, see the API Viewer
pipelineJob('example') {
authenticationToken('secret')
}

How to enforce parameter ordering in Jenkins DSL?

We have a parameterized job that has three params: server, username, and password. We would like them to be presented in that order, but it looks like Jenkins DSL is alphabetizing them, as they are presented in the job as password, server, username. Is there any way to specify an ordering for the parameters other than lexigraphical, or should we just rename our parameters so they sort alphabetically? It's odd to enter a password, then a server, followed by the username to use. I'm also surprised that Jenkins DSL isn't using the declared order for ordering the params.
Here is the groovy definition, redacted as appropriate:
< snip >
job("myFolder/seed-jobname") {
description('This job does stuff on a specified server')
parameters {
stringParam('SERVERNAME',
'',
'Enter the server to do stuff on'
)
stringParam('USERNAME', '', 'Enter your user ID')
configure {
it / 'properties' / 'hudson.model.ParametersDefinitionProperty' / parameterDefinitions << 'hudson.model.PasswordParameterDefinition' {
name 'PASSWORD'
description 'Enter your password'
defaultValue ''
}
}
}
< snip >
Thanks!
Jenkins and Job DSL will keep the parameters in the specified order.
The problem with your snippet is that you put the configure block inside the parameters closure. configure is only available on job level. Calling it inside another closure will cause the configure block to execute before the containing closure. In your case the PASSWORD parameter is generated before the other parameters.
Try this:
job('example') {
parameters {
stringParam('SERVERNAME')
stringParam('USERNAME')
}
configure {
it / 'properties' / 'hudson.model.ParametersDefinitionProperty' / parameterDefinitions << 'hudson.model.PasswordParameterDefinition' {
name('PASSWORD')
}
}
}

Resources