How to enabe SCM polling with the Jenkins DSL plugin - jenkins

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.

Related

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

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).

Jenkins Job DSL configure block

I am new to Jenkins Job DSL and trying to figure out how to use configure block in the scm section of my DSL. I have a section that is generated by default in my Jenkins config.xml
<scm class='hudson.plugins.git.GitSCM'>
<browser class='hudson.plugins.git.browser.GithubWeb'>
<url>https://github.com/repository/</url>
</browser>
</scm>
I know there is a browser method in the Jenkins Job DSL Plugin API and you can set it to gitblit, gitiles, gitLab, gitWeb, gogs, and stash.
I would like to set it (Auto). I've tried using the configure block method but it returns an error:
javaposse.jobdsl.dsl.DslScriptException: (script, line 12) Ambiguous method overloading for method groovy.util.Node#div.
Cannot resolve which method to invoke for [null] due to overlapping prototypes between:
line 12 is the it statement.
Code:
scm {
git {
remote {
github
credentials
}
branch("refs/heads/master")
configure {
it / 'scm' / 'browser' {}
}
}
}
So I am not sure how to fix this with code.
Any help would be appreciated.
thank you.
In the documentation it said that process xml might be a bit tricky, I think It should go something like this(format, content don't know if it's like this):
it / scm / browser(class: 'hudson.plugins.git.browser.GithubWeb') / url('https://github.com/repository/')

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'()
}

Jenkins DSL script - Test Failure - Found multiple extensions which provide method lastCompleted

Trying to create multijobs in Jenkins with DSL scripting.
There are multiple jobs in a phase and I want to create a consolidated report for the multijob from downstream jobs.
I am using copy artifact to copy the results of downstream jobs to the multijob's target dir. Using selector - lastCompleted()
However I am getting this an error saying multiple extensions providing the method and tests are failing. lastCompleted() is apparently present in copyArtifact and multijob plugins where in this case I require both.
Here is my script:
multiJob('dailyMultiJob') {
concurrentBuild(true)
logRotator(-1, 10, -1, 10)
triggers {
cron('H H(0-4) * * 0-6')
}
steps {
phase('Smoke Tests'){
phaseJob('JobA')
phaseJob('JobB')
phaseJob('JobC')
}
copyArtifacts{
selector{
lastCompleted()
}
projectName('JobA')
filter('target/allure-results/*.*')
target('/path/to/this/multijob/workspace')
flatten(false)
}
copyArtifacts{
selector{
lastCompleted()
}
projectName('JobB')
filter('target/allure-results/*.*')
target('/path/to/this/multijob/workspace')
flatten(false)
}
copyArtifacts{
selector{
lastCompleted()
}
projectName('JobC')
filter('target/allure-results/*.*')
target('/path/to/this/multijob/workspace')
flatten(false)
}
}
publishers {
allure {
results {
resultsConfig {
path('target/allure-results')
}
}
}
archiveArtifacts {
pattern('target/reports/**/*.*')
pattern('target/allure-results/**/*.*')
allowEmpty(true)
}
}
}
Getting this below error after running gradle tests
Caused by: javaposse.jobdsl.dsl.DslException: Found multiple extensions which provide method lastCompleted with arguments []: [[hudson.plugins.copyartifact.LastCompletedBuildSelector, com.tikal.jenkins.plugins.multijob.MultiJobBuildSelector]]
I am not sure if there is a way to indicate use specific artifact's method.
Been stuck on this for quite some time. Any helps are highly appreciated. Thank you in advance!
I had come across the same issue few months back.
There are two possible solutions to this issue.
1 - Keep only one plugin that will avoid the conflict. (Not recommended as it might break other jobs)
2- Use configure block to modify the xml file which will avoid this conflict & you can keep multiple plugins that support the same extensions. (Recommended solution)
Thanks,
Late update:
What I had to do is to switch to scripted pipeline jobs instead.
Configure blocks are not really allowed on all the methods you want to use and they are limited by design. I believe some plugins also don't allow it for security reasons.
Better do use Pipelines.

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