Jenkins job DSL plugin - hidden parameter - jenkins

I am using the Jenkins hidden parameter plugin but I cant find the syntax to write it in DSL like I am doing with other parameters.
For example:
https://jenkinsci.github.io/job-dsl-plugin/#method/javaposse.jobdsl.dsl.helpers.BuildParametersContext.activeChoiceParam
Is there any way to reflect hidden parameter in DSL?

Job DSL has no built-in support for the Hidden Parameter plugin, so it's not mentioned in the API viewer. But it's supported by the Automatically Generated DSL:
job('example') {
parameters {
wHideParameterDefinition {
name('FOO')
defaultValue('bar')
description('lorem ipsum')
}
}
}

BEfore using the declarative pipeline syntax (described in jenkinsci/pipeline-model-definition-plugin), you would have used:
the groovy-based DSL plugin
in combination with the JENKINS Mask Passwords Plugin (PR 755)
But with the pure DSL pipeline syntax, this is not yet supported (April 2017).
The PR 34 (a secret step) has been rejected
The following issues are still open:
"JENKINS-27386: Access credentials value from workflow Groovy script" (when to be implemented in a DSL pipeline)
"JENKINS-27398: Pipeline-as-Code CredentialsProvider for a job" (which would at least allow you tu use credentials as a workaround to access secret values)
The last issue though points out to JENKINS-29922 (Promote delegates of metasteps to top-level functions, deprecate $class) and adds the comment:
JENKINS-29922 is implemented, so assuming a #Symbol is defined for each credentials kind, and a credentials step is marked metaStep, you could write more simply:
usernamePassword id: 'hipchat-login', username: 'bob', password: 'abc/def+GHI0123='
hipchat server: …, message: …, credentialsId: 'hipchat-login'
or even allow the id to be generated, and return it from the step:
hipchat server: …, message: …, credentialsId: usernamePassword(username: 'bob', password: 'abc/def+GHI0123=')
While that is encrypted, that is not exactly "hidden" though.

Related

Referencing Folder-level scope credentials in declarative Jenkins pipeline

Question
I have the following script as part of a declarative pipeline in Jenkins
stages {
stage('sql') {
steps {
step([
$class: 'SQLPlusRunnerBuilder',
credentialsId:"sis-database-prod-schema-test",
instance:"(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=db_${ENVIRONMENT}.int.excelsior.edu)(PORT=1521))(CONNECT_DATA=(SERVICE_NAME=${ENVIRONMENT})))",
scriptType:'userDefined',
script: '',
scriptContent:"select*from dual",
customOracleHome: '/usr/lib/oracle/12.2/client64'
])
}
}
}
You will notice I am referencing the credential ID sis-database-prod-schema-test. When I scope this credential globally this script works. However, when I scope the credential at the folder level it get the following error
ERROR: Invalid credentials [sis-database-prod-schema-test]. Failed to initialize credentials or load user and password
Here is a screenshot of my folder-level scope configuration
Additional Information
When I scope the credential at the folder level I can see it in a configuration drop down element ONLY when I am in the appropriate folder. So, in my mind, the scope configuration is correct but there referencing ( in the code ) is wrong.
The entry I have highlighted is the sis-database-prod-schema-test credential ID. The one below it ( sis-test-database-prod-schema ) is a global credential unrelated to this question
Edit : This Was a Known Issue
This is a known bug that the author was unable to fix. The relevant code is here. You can issue a pull request to fix the bug.
I don't know if you still care but I just submitted a pull request for this that got accepted. Now this problem should be fixed.
Known Issue
This is a known bug that the author was unable to fix. The relevant code is here. You can issue a pull request to fix the bug.

Add Parameter Value in Message of Jenkins Office 365 Connector

I use the Jenkins Office 365 Connector and it sends messages of the build status to MS Teams as expected.
Now I want to add the value of a Jenkins job parameter to the message.
My usecase: I use a single job to deploy several services. I want to know in the message which service was deployed.
Notification from Dev_Deploy
Latest status of build #43
Status
Build Success
Remarks
Started by user XXX
Service
service-abc
I've seen in the Advanced configuration that there are Macros and Fact Definitions. Unfortunately there is no documentation in the plugin docs. Perhaps this configuration could help?
There is no option to customize the message in the jenkins GUI.
But a custom message can be specified in the pipeline script:
steps {
// some instructions here
office365ConnectorSend webhookUrl: 'https://outlook.office.com/webhook/123456...',
message: 'Application has been [deployed](https://uat.green.biz)',
status: 'Success',
color: '#0000FF'
}
Hint: The status color is not automatically set. So you have to set the color depending on the status.
Official documentation
In order to get the repository data, you can follow instructions to create a checkout snippet through the Jenkins UI in the configuration.
Once you input the correct URL, browser, and so on, you may invoke the office365ConnectorSend plugin. You may adapt the card sent by passing the factDefinitions attribute an array of [name,template] objects as outlined in Jenkins Docs. You can find an example in the open-source code readme.
there are some defaulted add-ons, but this should set you on the correct path.
Here is an example of my office365ConnectorSend:
office365ConnectorSend (
webhookUrl: "${webhookURL}",
color: "${currentBuild.currentResult} == 'SUCCESS' ? '00ff00' : 'ff0000'",
factDefinitions:[
[ name: "Commit Message", template: "${commit_message}"],
[ name: "Pipeline Duration", template: "${currentBuild.durationString.minus(' and counting')}"]
]
)

How to provide keychainPwd in hudson.util.Secret format in Xcode Integration plugin while working with Blue Ocean?

We created Jenkins Pipeline as a Code using Blue Ocean and it was working fine until recently.
Now when we try to pass parameters for keychainPwd for Xcode integration plugin in Blue Ocean, it gives us errors and our Blue Ocean Pipeline for iOS is not working.
We tried to use Secret key of credential and tried to pass it as parameter but it is not working.
environment {
Keychain_pwd_id = credentials('test')
}
Here 'test' secret key was created.
We tried following as well:
keychainPwd: hudson.util.Secret.fromString("${Keychain_pwd_id}")
pipeline {
environment {
Keychain_pwd_id = credentials('test')
}
stages {
stage('Xcode Build') {
steps {
xcodeBuild(buildIpa: true, bundleID: 'com.xxx.xxxxxxxxxx', cleanBeforeBuild: true, configuration: 'Release', developmentTeamID: 'xxxxxxxx', developmentTeamName: 'xxxxxxxxxxxxxxxxxxxxx', ipaExportMethod: ‘enterprise’, ipaName: ‘xxxxxxxxxxx’, ipaOutputDirectory: 'build', keychainName: 'login', keychainPath: '${HOME}/Library/Keychains/login.keychain', keychainPwd: "${Keychain_pwd_id}, manualSigning: true, provisioningProfiles: [[provisioningProfileAppId: 'xxxxxxxxxxxxxxxxxxx', provisioningProfileUUID: 'xxxxxxxxxxxxxxxxxxxxxxxxxx']], unlockKeychain: true, xcodeSchema: ‘xxxxxxxxxxxxxxxx
}
}
}
}
Expecting "class hudson.util.Secret" for parameter "keychainPwd" but got "${keychainPwd}" of type class java.lang.String instead # line 12, column 407.
I'm currently working through the same issue. It seems the xcodebuild plugin updated recently to require it.
I was able to get this building with the following answers: How do i compare user inputed password to credentials passphrase
Jenkins CI Pipeline Scripts not permitted to use method groovy.lang.GroovyObject
The change from the first link is what you're looking for, but you may need to approve your script via the info in the second link.

Jenkins Pipeline passing password parameter to downstream job

I want to pass a value, from the Password Parameter plugin, in a Jenkins Pipeline job, to another freestyle job, to be used for login. I don't want to see it in the output or anywhere else. I can do it between two freestyle jobs but it seems that the pipeline is a bit different.
Even if I'm able to send as a string, it would be visible in the Parameters tab or the Environment Variables tab.
Does anyone have any idea how this could be achieved?
I've spent hours trying different solutions for the same problem as you've had and here is the final solution, which worked for me:
In your pipeline script:
stages {
stage("Do something with credentials and pass them to the downstream job") {
steps {
build job: 'your/jobname/path', parameters: [
[$class: 'hudson.model.PasswordParameterValue', name: 'PASSWORD', value: env.PASSWORD],
[$class: 'TextParameterValue', name: 'USERNAME', value: env.USERNAME]
]
}
}
The trick is to use hudson.model.PasswordParameterValue class when passing password parameter to downstream (Freestyle) job, but you must use then the same class for parameter definition in your main pipeline (parent job) in order to make it work.
For example in your pipeline job you would configure password parameter:
configure {
it / 'properties' / 'hudson.model.ParametersDefinitionProperty' / 'parameterDefinitions' << 'hudson.model.PasswordParameterDefinition' {
name('PASSWORD')
description('My password')
}
}
You should make sure that parent and child job both are using password parameters. Then, this parameters tab will mask you password. Making build parameters as password parameter will not mask passwords in environment variables tab, for that you need to enable mask password in child and parent job configuration or use Inject passwords to the build as environment variables and enable mask password.
You should use credentials plugin, which in pipeline you write with withCredentials block. For example:
withCredentials([usernamePassword(credentialsId: 'abcd1234-56ef-494f-a4d9-d5b5e8ac357d',
usernameVariable: 'USERNAME',
passwordVariable: 'PASSWORD')])
{
echo 'username='+USERNAME
echo 'password='+PASSWORD
}
where abcd1234-56ef-494f-a4d9-d5b5e8ac357d is the id of credentials you have in jenkins, and of course, as long as you don't echo the variables (as I did in the example obviously for demonstration purposes), username and password are not visible.
You can trigger you downstream job with the help of below plugin
Parameterized+Trigger+Plugin

How to get culprits or committers inside a Jenkins workflow with one or more SCMs

Is it possible to access information about committers and/or culprits of a Jenkins workflow job when checking out from one or more SCMs (either via checkout() or other SCM steps like git/svn)?
The intention is to use that information to notify committers and/or culprits about the job status, for example in a mail step.
A small example of a workflow definition:
node {
// checkout from one or more SCMs, e.g.
git url: '<URL>'
checkout([$class:...])
...
// how can we know about committers or culprits at this point?
$committers = ??
// send a mail to committers or culprits
mail to: '$committers', subject: 'JENKINS', body: '<information about the job status>'
}
How could this be adapted to get a collection of the committers after running the SCM steps?
Edit:
I am currently working with Jenkins version 1.596.2 and Workflow: Aggregator version 1.6 and it seems this is an open issue in JENKINS-24141
This is now possible using the email-ext plugin.
def to = emailextrecipients([[$class: 'CulpritsRecipientProvider'],
[$class: 'DevelopersRecipientProvider'],
[$class: 'RequesterRecipientProvider']])
if (to != null && !to.isEmpty()) {
mail to: to, subject: "JENKINS", body: "See ${env.BUILD_URL}"
}
However, if you just want to send an email on failures, you may want to use Mailer (based on the email-ext pipeline examples):
step([$class: 'Mailer',
notifyEveryUnstableBuild: true,
recipients: emailextrecipients([[$class: 'CulpritsRecipientProvider'],
[$class: 'RequesterRecipientProvider']])])
Using groovy within a pipeline script:
#NonCPS // Necessary to allow .each to work.
def changelist() {
def changes = ""
currentBuild.changeSets.each { set ->
set.each { entry ->
changes += "${entry.commitId} by ${entry.author.fullName}\n"
}
}
changes
}
similar to the answer from #szym, but without the #NonCPS required:
def authors = currentBuild.changeSets.collectMany { it.toList().collect { it.author } }.unique()
As you found, pending JENKINS-24141 this is not supported. Changes to Jenkins core are required.
You can get the xml info for a job in which you will find the name of the person who committed the change along with the commit messages.
http://<Jenkins URL>:<Port Number>/job/<Jobname>/<BuildNumber>/api/xml?
Give this a go in your browser. Search for "user".
You can dump this information in a text file to process.
It seems that this feature was implemented inside the email-ext plugin but the author forgot to document the way we are supposed to use this.
Please check https://issues.jenkins-ci.org/browse/JENKINS-34763 -- and add a comment there, asking for an example. I already did.
You can fetch committers email :
committerEmail = sh (
script: 'git --no-pager show -s --format=\'%ae\'',
returnStdout: true
).trim()
and send:
emailext body: 'text you choose', subject: 'subject you choose', recipientProviders: [[$class: 'DevelopersRecipientProvider']], to: committerEmail
taken from : https://medium.com/#dilunika/find-the-git-commit-user-jenkins-pipeline-b6790613f8b5
In the emailext plugin you can provide culprits, developers, requestor etc in the recipientProviders directly.
emailext body: '',
recipientProviders: [culprits(),
developers(),
brokenBuildSuspects(),
brokenTestsSuspects(),
requestor()],
subject: ''
Description
Culprits: Sends email to the list of users who committed a change since the last non-broken build till now. This list at least always include people who made changes in this build, but if the previous build was a failure it also includes the culprit list from there.
Developers: Sends email to all the people who caused a change in the change set.
Broken Build suspects: Sends email to the list of users suspected of causing the build to begin failing.
Broken Test suspects: Sends email to the list of users suspected of causing a unit test to begin failing. This list includes committers and requestors of the build where the test began to fail, and those for any consecutive failed builds prior to the build in which the test began to fail.
Source: Jenkins Pipeline Syntax - Snippet Generator
If you want to notify the culprits who broke the build, You do not need to any checks, Use email plugin in jenkins. This plugin gives you option to send mails to commiter between past good build and current broken build.
If you are using "Editable email notifier plugin" You get option of send mail to culprit.
If you are using email plugin then you get the option "Send separate e-mails to individuals who broke the build".

Resources