Disable or auto approve Script Approval for scripts executed in Job Dsl (Active Choice Parameters)? - jenkins

Running Jenkins 2.289.1.
I have this pipelineJob Job Dsl setting up Active Choice parameters:
https://plugins.jenkins.io/uno-choice/
pipelineJob("test") {
parameters {
activeChoiceParam('CHOICE-1') {
description('Allows user choose from multiple choices')
filterable()
choiceType('SINGLE_SELECT')
groovyScript {
script('return ["choice1", "choice2", "choice3"];')
fallbackScript('"fallback choice"')
}
}
}
definition {
cpsScm {
scm {
git {
remote {
credentials("${creds}")
url("${gitUrl}")
}
branch("${gitBranch}")
}
}
scriptPath("${pathToFile}")
}
}
}
To make sure I can run Job Dsl in the first place without having to manually approve that I have added the following to jcasc:
jenkins:
security:
globalJobDslSecurityConfiguration:
useScriptSecurity: false
But that is not enough. Before I can run the generated pipeline based on above Job Dsl I still need to manually approve:
How do I configure Job Dsl, jcasc or something else to either disable script approval for anything that goes on in a Job Dsl or automatically approve any script that might be created inside a job dsl?
Hopefully I don't have to hack my way around that like suggested here:
https://stackoverflow.com/a/64364086/363603
I am aware that there is a reason for this feature but its for a local only jenkins that I am using for experimenting and this is currently killing my productivity. Related:
https://issues.jenkins.io/browse/JENKINS-28178?focusedCommentId=376405&page=com.atlassian.jira.plugin.system.issuetabpanels%3Acomment-tabpanel#comment-376405

What worked for me:
Manage Jenkins > Configure Global Security > CSRF Protection (section header -- not sure why) > Enable script security for Job DSL scripts (the name of the option that I disabled).

Related

Multiple Jenkins pipelines for a single repo

At the moment I have two MultiJob Projects for a single repo:
First runs on develop branch
Second runs on all opened Pull Requests
Each has a lot of nested Freestyle jobs.They are are quite different.
I'm looking at switching to Pipeline-as-Code by using Jenkinsfile. So my question is is there a way to switch Jenkinsfile path/name based on, say branch name. I tried to use MultiBranch Pipeline job type, but it only allows to set a single Jenkinsfile path and it uses it across any branch including PullRequests.
Maybe there is a better way to achieve that? I'm open to discussion. Thank you
You can do it in one jenkinsfile by using when expression, I assume your pipeline is not quite big
pipeline {
agent any
stages {
stage("Set variables from external input") {
when {
branch "develop"
}
steps{
#add the thing which you want execute when branch is develop
}
}
stage("2 for Pull request") {
when {
expression {return !env.GIT_BRANCH.contains('master|develop')}
}
steps{
#add the thing which you want execute when branch is pull request
}
}
}
}

Disable Concurrent Builds on Multibranch Pipeline Jobs with Job DSL

I am trying to create Multibranch Pipeline Jobs using Job DSL, but I want to disable concurrent builds on each branch. I have tried the following code snippet but it didn't work, "Do not allow concurrent builds" is still unchecked on new branches.
multibranchPipelineJob("${FOLDER_NAME}/${JOB_NAME}") {
branchSources {
git {
remote("https://gitlab.com/${REPO_PATH}")
credentialsId('gitlab_credentials')
includes('*')
}
}
configure {
def factory = it / factory(class: 'com.cloudbees.workflow.multibranch.CustomBranchProjectFactory')
factory << disableConcurrentBuilds()
}
orphanedItemStrategy {
discardOldItems {
numToKeep(1)
}
}
}
I also tried this in configure closure:
factory << properties {
disableConcurrentBuilds()
}
But this one caused following exception to be thrown:
19:03:50 groovy.lang.GroovyRuntimeException: Ambiguous method overloading for method groovy.util.Node#leftShift.
19:03:50 Cannot resolve which method to invoke for [null] due to overlapping prototypes between:
19:03:50 [class groovy.util.Node]
19:03:50 [class java.lang.String]
I have this need as well. I notice that in my jenkins instance the jobDSL api docs indicate that disableConcurrentBuilds() property is NOT supported in multibranch pipeline jobs.
I just returned to a related discussion I was having with #tknerr in which he pointed out that there IS a rate limiting feature available to multibranch pipelines via jobDSL.
My team just ran into a problem with pollSCM triggering running amok due to this Jenkins bug, and so I'm implementing this in jobDSL to make our jobs more robust to this. Like you, I had wanted to just "disableConcurrentBuilds" like can be done in pipelines, but since rate limiting appears to be the only solution currently available to multibranch pipelines, I experimented with putting this in our jobDSLs:
strategy {
defaultBranchPropertyStrategy {
props {
rateLimitBranchProperty {
count(2)
durationName("hour")
}
}
}
}
This is of course a horrible workaround, since it places a nasty dependency in the jobDSL of needing to know how long builds take, but i'm willing to accept this alternative to having to push disableConcurrentBuilds option to the Jenkinsfile on hundreds of branches.
It is also barely even effective at achieving the goal, since we want to allow concurrent builds across branches, but want to prevent individual branch jobs from being built "too fast".
We should check if there is a feature request in Jenkins for this (your original request).
In my jenkins instance (v2.222.3, Pipeline:multibranch v2.22), the setting is described here for applying it to "all branches":
https://<my_jenkins_fqdn>/plugin/job-dsl/api-viewer/index.html#path/multibranchPipelineJob-branchSources-branchSource-strategy-allBranchesSame-props-rateLimit
and here for applying it to specific branches:
https://<my_jenkins_fqdn>/plugin/job-dsl/api-viewer/index.html#path/multibranchPipelineJob-branchSources-branchSource-strategy-namedBranchesDifferent-defaultProperties-rateLimit
EDIT: Also wanted to link to a related Jenkins issue here.

How to configure basic branch build strategies plugin using job dsl?

The multi branch pipeline plugin, awesome as it is, doesn't build tags out of the box. The usage of the basic-branch-build-strategies-plugin is required to enable tag discovery and building.
My question is directly related to: Is there a way to automatically build tags using the Multibranch Pipeline Jenkins plugin?
This plugin works great in the UI but doesn't appear to be easily configurable using the Jenkins job dsl. Does anyone have any examples of how to set the branch strategies using the dsl (or dsl configure->) so that tags will be discovered and built?
Having examined the delta between the config.xml files when the settings are changed via ui, it looks like I need to be able to add this trait:
<org.jenkinsci.plugins.github__branch__source.TagDiscoveryTrait />
and this section under build strategies:
<buildStrategies
<jenkins.branch.buildstrategies.basic.TagBuildStrategyImpl
plugin="basic-branch-build-strategies#1.1.1">
<atLeastMillis>-1</atLeastMillis>
<atMostMillis>172800000</atMostMillis>
</jenkins.branch.buildstrategies.basic.TagBuildStrategyImpl>
</buildStrategies>
Something like
multibranchPipelineJob('pipline') {
...
branchSources {
branchSource {
source {
github {
...
traits {
...
gitTagDiscovery()
}
}
buildStrategies {
buildTags {
atLeastDays '-1'
atMostDays '20'
}
}
}
}
}
}
is what I've been working with. It's not documented in the plugin, but that doesn't stop the job-dsl plugin from dynamically generating the API calls for it.
You can see what the API for your specific Jenkins installation is by going to {your_jenkins_url}/plugin/job-dsl/api-viewer/index.html.
Sometimes things won't appear there because a plugins lacks support for job-dsl.
In that case you can still generate the xml with the Configure Block.
However, this is pretty clumsy to use.
Edit: At least if I use gitHubTagDiscovery() as suggested by the dynamically generated API, Jenkins will crash. Instead, the configure block has to be used to get all the discovery methods for github.
configure {
def traits = it / sources / data / 'jenkins.branch.BranchSource' / source / traits
traits << 'org.jenkinsci.plugins.github__branch__source.BranchDiscoveryTrait' {
strategyId(1)
}
traits << 'org.jenkinsci.plugins.github__branch__source.OriginPullRequestDiscoveryTrait' {
strategyId(1)
}
traits << 'org.jenkinsci.plugins.github__branch__source.TagDiscoveryTrait'()
}

How to enabe SCM polling with the Jenkins DSL plugin

I'd like to enable SCM polling in Jenkins by DSL code. As it's easily possible manually ( without DSL ) and works perfectly, but I'm looking for DSL code to
Make it enable -- check attached image for reference.
I already checked below link, but no any solution here.
https://jenkinsci.github.io/job-dsl-plugin/#method/javaposse.jobdsl.dsl.helpers.triggers.TriggerContext.scm
GitHub hook trigger for GITScm polling
and
Poll SCM
click here to check image
I'm not using Jenkins pipeline
Finally I got solution for this:
Following are the DSL code to enable scm polling:
triggers {
configure {
it / 'triggers' << 'com.cloudbees.jenkins.GitHubPushTrigger'{
spec''
}
scm('')
}
}
I have tested, It's working perfectly
Another Solution:
job('myjob') {
configure { it / 'triggers' / 'com.cloudbees.jenkins.GitHubPushTrigger' / 'spec' }
}
I had a similar situation when trying to enable scm polling for a pipeline.
I am configuring pipelines via job-dsl and CasC, and I specifically wanted to enable SCM polling.
So here's what I have working; I'm within the pipelineJob context, but I believe the solution is the same for the job context:
pipelineJob('myPipelineName') {
environmentVariables {
...
}
definition {
...
}
configure { project ->
project / 'properties' / 'org.jenkinsci.plugins.workflow.job.properties.PipelineTriggersJobProperty' / 'triggers' / 'hudson.triggers.SCMTrigger' {
'spec'('* * * * *')
}
}
}
The way I landed on this was manually changing a pipeline config (in the UI) to enable polling, then going and looking at the job's .xml on disk.
The slash delimited stuff you see in the code above represents the xml tag path to the value i want to change.

Is it possible to specify check-out strategy?

Is it possible in Jenkins-dsl to specify the SVN check-out strategy?
I would like to use "Use 'svn update' as much as possible", yet the only way I can see to configure this is manually
Cheers!
You can do this
job {
name 'svn2'
description 'Build and test the app.'
scm {
svn('https://subversion.assembla.com/svn/chucknorrisaxis', localDir='.'){
(it / 'workspaceUpdater').attributes().put 'class',
'hudson.scm.subversion.UpdateWithCleanUpdater'
}
}
steps {
gradle 'test'
}
publishers {
archiveJunit 'build/test-results/**/*.xml'
}
}
I have a different update strategy here because I think the default strategy is 'use svn update as much as possible'
I asked the job dsl google group on your behalf (as my own solution failed) here
Incidentally, to try out job-dsl commands outside of Jenkins you can use the job-dsl playground

Resources