Jenkins Plugins update email notification - jenkins

I need a script to get a list of jenkins plugins that need to be updated and send weekly email notification about them.

You can use the following script as a reference and build a Pipeline to send an Email.
// This cript prints all the installed plugins and if there are updates, the latest version available.
jenkins.model.Jenkins.getInstance().getUpdateCenter().getSites().each { site ->
site.updateDirectlyNow(hudson.model.DownloadService.signatureCheck)
}
hudson.model.DownloadService.Downloadable.all().each { downloadable ->
downloadable.updateNow();
}
def pluginList = new ArrayList(Jenkins.instance.pluginManager.plugins)
pluginList.sort { it.getShortName() }.each{ plugin ->
println ("${plugin.getDisplayName()} (${plugin.getShortName()}): ${plugin.getVersion()} : ${plugin.hasUpdate() ? plugin.getUpdateInfo().version : 'No Update'}")
}

Related

Is it possible to send Fortify SSC results in a Jenkins pipeline email?

Has anyone been successful in sending results from the Jenkins Fortify plugin (fortify-plugin) to developers via email using the Email Extension plugin (email-ext-plugin)?
I'm looking to add the List of Fortify SSC Issues summary to the build summary email by manipulating the Email Extension default Groovy template:
https://github.com/jenkinsci/email-ext-plugin/blob/master/src/main/resources/hudson/plugins/emailext/templates/groovy-html.template
I've been trying to use the getAction method to get information from the Fortify results similar to how JUnit tests are reported, but the problem I'm finding is that the Fortify Assessment is returned at the Jenkins project level instead of at the job level, so the following is never successful:
<%
def buildStatsAction = null
def buildStatsFolders = null
try {
buildStatsAction = it.getAction("com.fortify.plugin.jenkins.TableAction.BuildStatistics")
buildStatsFolders = buildStatsAction.getFolders()
} catch(e) {
//buildStatsAction not exist in this build
}

How to set the discovery modes for multibranch job created by Job DSL

I'm new to Jenkins and I'm trying to figure something out.
Is there a way to add Branch Sources behavior via Groovy. This is to analyse GitHub projects in SonarQube using Jenkins.
I'm creating a multi-branch pipeline but can't seem to figure out how to add the following behaviours.
These behaviours come by default when the job is created in the UI, but don't appear when the job is created via Groovy.
I've defined this as my pipeline. Any idea how these other parameters can be added in?
multibranchPipelineJob('Foo') {
displayName('Foo')
description('Jenkins')
branchSources {
branchSource {
source {
github {
id('15')
repoOwner('12345')
repository('foo')
repositoryUrl('https://example.com')
configuredByUrl(true)
credentialsId('foo')
traits {
gitBranchDiscovery()
}
}
}
}
}
orphanedItemStrategy {
discardOldItems {
numToKeep(10)
}
}
}
I've tried adding in the following parameters but it throws an error.
import jenkins.plugins.git.traits.*
def traits = []
traits.add(new TagDiscoveryTrait())
traits.add(new LocalBranchTrait())
gitSCMSource.setTraits(traits)
Is there a way to create the job via Groovy but with the default settings that would appear when the job is created in the UI?
You can check all available options on your Jenkins by using this URL:
https://<your-jenkins>/plugin/job-dsl/api-viewer/index.html
Branch Discovery Mode
multibranchPipelineJob('Foo') {
branchSources {
branchSource {
source {
github {
traits {
gitHubBranchDiscovery {
strategyId(1)
// strategyId(2)
// strategyId(3)
}
}
}
}
}
}
}
Strategy id:
1 - discover all branches, except branches that are pull request sources
2 - discover only branches that are pull request sources
3 - discover all branches
Pull Request Discovery Mode
multibranchPipelineJob('Foo') {
branchSources {
branchSource {
source {
github {
traits {
gitHubPullRequestDiscovery {
strategyId(1)
// strategyId(2)
// strategyId(3)
}
}
}
}
}
}
}
Strategy id:
1 - discover each pull request once with the discovered revision corresponding to the result of merging with the current revision of the target branch
2 - discover each pull request once with the discovered revision corresponding to the pull request head revision without merging
3 - discover the current pull request revision and the pull request merged with the current target branch revision
Fork Pull Request Discovery Mode
Due to a bug in Jenkins (JENKINS-60874), you have to use the configure block:
multibranchPipelineJob('Foo') {
configure {
def traits = it / 'sources' / 'data' / 'jenkins.branch.BranchSource' / 'source' / 'traits'
traits << 'org.jenkinsci.plugins.github__branch__source.ForkPullRequestDiscoveryTrait' {
strategyId(1)
// strategyId(2)
// strategyId(3)
trust(class: 'org.jenkinsci.plugins.github_branch_source.ForkPullRequestDiscoveryTrait$TrustPermission')
// trust(class: 'org.jenkinsci.plugins.github_branch_source.ForkPullRequestDiscoveryTrait$TrustNobody')
// trust(class: 'org.jenkinsci.plugins.github_branch_source.ForkPullRequestDiscoveryTrait$TrustContributors')
// trust(class: 'org.jenkinsci.plugins.github_branch_source.ForkPullRequestDiscoveryTrait$TrustEveryone')
}
}
}
Strategy id:
1 - discover each pull request once with the discovered revision corresponding to the result of merging with the current revision of the target branch
2 - discover each pull request once with the discovered revision corresponding to the pull request head revision without merging
3 - discover the current pull request revision and the pull request merged with the current target branch revision
Trust class:
TrustPermission - trust those with write permission to the repository
TrustNobody - trust nobody
TrustContributors - trust contributors to the repository
TrustEveryone - trust everyone

Triggering a multibranch pipeline job from github enterprise webhook

I am attempting to trigger multi-branch pipeline jobs from a GitHub enterprise server. I have the webhook configured to send a notification on all events. The event log on github enterprise shows that the requests to Jenkins are successful, however on the multibranch pipeline the event log is empty.
My multibranch pipeline jobs are being created using JobDSL like so:
multibranchPipelineJob("build_${repo}") {
branchSources {
branchSource {
source {
git {
id("${org}.${repo}")
remote("git#${githubEntrerpise}:${org}/${repo}")
}
}
}
}
configure {
def traits = it / sources / data / 'jenkins.branch.BranchSource' / source / traits
traits << 'jenkins.plugins.git.traits.BranchDiscoveryTrait' {}
}
triggers {
periodic(1) // Trigger every min.
}
orphanedItemStrategy { discardOldItems { numToKeep(10) } }
}
Is there anything I am missing here?
I resolved it by changing the webhook endpoint I was using.
Changing it to the following format solved the issue http://[JENINS_HOST]/git/notifyCommit?url=git#[GIT_REPO].git

Trigger Input Step in Jenkins via HipChat

I can find tons of information in the internet about integrating HipChat in a scripted Jenkins pipeline. So that works fine for me. But how can I post a status message to HipChat that contains an element to trigger an action back in Jenkins?
Currently I have input steps in Jenkins to approve a deployment to the next stage, e.g. PROD.
I also send a HipChat message if approval is needed which contains a link to JENKINS. That looks like this:
hipchatSend color: "${color}", notify: true, room: "Jenkins Team FooBar", message: "${env.JOB_NAME}#${env.BUILD_NUMBER}: ${message}", textFormat: true
/************** PROD **************/
stage ('Approval for PROD') {
try {
timeout(time: approvalTime, unit: approvalTimeUnit) {
input 'Do you approve the deployment to PROD?'
}
} catch (Exception ex) {
finishBuild = true
}
}
// Stop build if flag was set
if (finishBuild)
return
How can I define actions in that hipChat message? Is there a way that I can approve the next build step within HipChat?
I have not found a tutorial or documentation on how to define other kinds of hipchat messages with this plugin.
I could send a POST request to JENKINS if the message would contain standard HTML. Any ideas on how to do that?
How would it work with cards?
Thanks in advance.

Jenkins get user who aborted a build

Is there a way to get the username when a build is aborted by a user?
Preferably using jenkins pipeline code.
When a build is aborted by a user, it logs:
Aborted by <username>
so I hope it is stored as a variable for a brief period.
Use case: username to be later used to inform the user itself or other users via email or other means of messaging.
It seems that a InterruptedBuildAction object is inserted in to the list of build action if a job is aborted. This object can be used to retrieve the user that aborted the build. I use the following function in my Jenkinsfile:
#NonCPS
def getAbortUser()
{
def causee = ''
def actions = currentBuild.getRawBuild().getActions(jenkins.model.InterruptedBuildAction)
for (action in actions) {
def causes = action.getCauses()
// on cancellation, report who cancelled the build
for (cause in causes) {
causee = cause.getUser().getDisplayName()
cause = null
}
causes = null
action = null
}
actions = null
return causee
}
In fact you can have this information with the REST API, just use the following URL with an appropriate build:
/api/json?tree=actions[causes[*]]&pretty=true
And you should be able to find the requested information under actions[causes], e.g.:
{
"_class" : "jenkins.model.InterruptedBuildAction",
"causes" : [
{
"_class" : "jenkins.model.CauseOfInterruption$UserInterruption",
"shortDescription" : "Aborted by some_user_name"
}
]
},
Unfortunately there seem to be no other solutions at the moment but to tweak Jenkin's code itself and a workaround.
Post-Build actions → Editable Email Notification → Triggers → Add Trigger → Aborted → Send To → Add → Requestor → → ... Jenkins Mailer Plugin:
Sends email to the user who initiated the build.
There's no Aborter to add.
http://<jenkins>/job/<project name>/lastBuild/api/xml shows:
...
<result>ABORTED</result>
...
but there's no info who aborted the build either.
A workaround could be to curl http://<jenkins>/job/<project name>/<build #> in a Post build task script and to grep for <p>Aborted by user username</p>.

Resources