How to programmatically set Authentication Token in Jenkins groovy script? - jenkins

I'm looking to set the Authentication Token in groovy similar to how I setup other options for the build:
properties([[$class: 'BuildConfigProjectProperty'],
buildDiscarder(logRotator(numToKeepStr: '25')),
parameters([
password(name: 'aws_access_key', defaultValue: 'AWS Access Key', description: 'Enter AWS Access Key ID'),
])])
The field I wish to set (from the UI):
Picture of UI
How does one set this field?

Related

How do I define Credentials as params in Jenkinsfile scripted pipeline

I am defining a scripted pipeline with many inputs, 2 of them are credentials. In the UI I can see how to add an input that is a credential, but I can't find anything on how to define Credential Params for scripted Pipelines. My params are defined like:
properties([
buildDiscarder(logRotator(numToKeepStr: '20')),
parameters([
stringParam(name: 'export_credentials'),
stringParam(name: 'import_credentials'),
]),
])
But I'd prefer it to be actual credentials params and not string ones
To keep the string secured use the following:
properties([
buildDiscarder(logRotator(numToKeepStr: '20')),
parameters([
password(description: 'b', name: 'b')
])
])
I figured it out after exploring the job-dsl plugin API (<jenkins_url>/plugin/job-dsl/api-viewer/index.htm):
properties([
buildDiscarder(logRotator(numToKeepStr: '20')),
disableResume(),
parameters([
credentials(name: 'export_token_credential_id', required: true, credentialType: "com.cloudbees.plugins.credentials.impl.UsernamePasswordCredentialsImpl", defaultValue: 'dockerjenkins-token', description: 'Username and API Token for the Jenkins to migrate from'),
credentials(name: 'import_token_credential_id', required: true, credentialType: "com.cloudbees.plugins.credentials.impl.UsernamePasswordCredentialsImpl", defaultValue: 'cloudbees-token', description: 'Username and API Token for this Jenkins'),
stringParam(name: 'item', description: 'Item (job) to migrate. '),
choiceParam(name: 'disable_mode', choices: "NEITHER\nDEST\nSOURCE\nBOTH", description: 'Which Jenkins, if any, to disable jobs on when migrating'),
]),
])

what can I do on Jenkinsfile to get credentials?

I'm new to jenkins and I'm creating a jenkinsfile with a declarative pipeline that supports different parameters. I also need to access to a credential stored in Jenkins, that I created already. How can I access to this credentials though jenkinsfile? do I need to call them inside of the stage or like this is ok? I got very confused in this part :S
I saw something like this on internet:
steps {
withCredentials([usernamePassword(credentialsId: 'x'....
}
Until now I have this:
pipeline {
agent any
environment{
my_credentials = credentials('x-credentials-id')
}
stages{
stage('Setup parameters') {
steps {
parameters([
string(name: 'a', defaultValue: 'x', description: 'test'),
text(name: 'b', defaultValue: ''),
text(name: 'b2', defaultValue: ''),
text(name: 'c', defaultValue: ''),
text(name: 'c2', defaultValue: '')
])
//])
}
}
}
}
From Jenkins documentation.
Jenkins' declarative Pipeline syntax has the credentials() helper
method (used within the environment directive) which supports secret
text, username and password, as well as secret file credentials.
So basically credentials('x-credentials-id') will support the aforementioned credential types and you should be using this helper method within an Environment block. You can use this approach if you want to declare your credentials globally so they can be used anywhere in the pipeline.
example
environment {
AWS_ACCESS_KEY_ID = credentials('jenkins-aws-secret-key-id')
AWS_SECRET_ACCESS_KEY = credentials('jenkins-aws-secret-access-key')
}
For other types, you can use withCredentials directive.(This is coming from Credentials Binding plugin) Both will get the Job done.
withCredentials(bindings: [certificate(credentialsId: 'jenkins-certificate-for-xyz', \
keystoreVariable: 'CERTIFICATE_FOR_XYZ', \
passwordVariable: 'XYZ-CERTIFICATE-PASSWORD')]) {
//
}
Although it says secrettext, username and password etc are not supported with Bind Credentials plugin, you can use WithCredentials for those types as well.
withCredentials([usernamePassword(credentialsId: 'amazon', usernameVariable: 'USERNAME', passwordVariable: 'PASSWORD')]) {
echo "username is $USERNAME"
}
Read more from here and here

How to add radio buttons in Jenkins using groovy when building a job using "Build with parameters"?

I am trying to add radio buttons in Jenkins instead of checkboxes when running Build with Parameters. In my existing code, I am getting checkboxes. What changes should I make in my existing code to get the radio buttons. Below is my groovy code:
def call(Map config = [:]) {
paramsList = []
paramsList << booleanParam(name: 'deployToDev', defaultValue: false, description: 'Set to true to deploy to Dev K8s Environment')
paramsList << booleanParam(name: 'deployToTest', defaultValue: false, description: 'Set to true to deploy to Test K8s Environment')
paramsList << booleanParam(name: 'deployToStage', defaultValue: false, description: 'Set to true to deploy to Stage K8s Environment')
properties([parameters(paramsList)])
}
Please find the below screenshot:
You can achieve that easily using the Extended Choice Parameter which has a built in support for all kinds of selection options including radio buttons.
You can use it as follows:
def call(Map config = [:]) {
paramsList = []
// You can also set the default value using the 'defaultValue' option
paramsList << extendedChoice(name: 'DeployTo', description: 'Select the environment to deploy to', type: 'PT_RADIO', value: 'Dev,Test,Stage', visibleItemCount: 5)
properties([parameters(paramsList)])
}
The result will look like:
You can also use the Active Choices plugin, which is a bit more complicated but has more configuration options, it will also allow you to generate the values from a groovy script.
For example:
properties([parameters(
[[$class: 'ChoiceParameter', name: 'DeployTo', choiceType: 'PT_RADIO', description: 'Select the environment to deploy to', script: [$class: 'GroovyScript', script: [classpath: [], sandbox: false, script: "return ['Dev','Test','Stage']"]]]]
)])

Jenkins error while setting build parameters from Jenkinsfile

I am trying to set build parameter (String and password param) from the Jenkinsfile but I am getting following error and the build fails.
Caused by: java.lang.UnsupportedOperationException: PasswordParameterDefinition as a class hudson.model.ParameterDefinition could mean either hudson.model.PasswordParameterDefinition or com.michelin.cio.hudson.plugins.passwordparam.PasswordParameterDefinition
at org.jenkinsci.plugins.structs.describable.DescribableModel.resolveClass(DescribableModel.java:419)
Copy/pasted from https://issues.jenkins-ci.org/browse/JENKINS-18141:
In the example above, the DSL tries to find a subclass of hudson.model.ParameterDefinition named PasswordParameterDefinition. In your installation there are two classes named PasswordParameterDefinition, one defined by Jenkins itself and one provided by the Mask Passwords Plugin. The DSL can't decide which to use, so it generates the error.
If you have installed the Mask Passwords Plugin, you can use nonStoredPasswordParam to create a password parameter:
https://jenkinsci.github.io/job-dsl-plugin/#path/job-parameters-nonStoredPasswordParam
If you are calling your class as:
[$class: 'PasswordParameterDefinition', defaultValue: '', description: 'Vpn password', name: 'Psw']
try with this:
[$class: 'hudson.model.PasswordParameterDefinition', defaultValue: '', description: 'Vpn password', name: 'Psw']

Use password parameter in Jenkins as Secret in Pipeline

I have a Jenkins pipeline job that needs to provide the username and password to checkout from RTC as parameters.
The checkout action can use a userId and password variable, but the Password must be of the class "Secret".
When trying to create a secret using hudson.util.Secret secret = hudson.util.Secret.fromString("${Build_Password}"), I get the following error:
org.jenkinsci.plugins.scriptsecurity.sandbox.RejectedAccessException: Scripts not permitted to use staticMethod hudson.util.Secret fromString java.lang.String
Is there a way to create a Secret or Credential from parameters?
I had to disable the groovy sandbox. After that, I was able to use the Secret class:
hudson.util.Secret secret = hudson.util.Secret.fromString(Build_Password)
checkout([$class: 'TeamFoundationServerScm', localPath: 'D:\Build-Code-Scm', projectPath: '$/RootDirectory/SubFolder', serverUrl: 'http://TEST.TEST.com:8080/TEST/TEST', useOverwrite: true, useUpdate: true, userName: 'UNMAME', password: hudson.util.Secret.fromString('PASSWORD'), workspaceName: 'Hudson-${JOB_NAME}-${NODE_NAME}'])

Resources