Conditional loops in Job DSL - jenkins

I'm taking the build type i.e either Maven Job or Freestyle job as an input parameter (using the build parameterized plugin) and based on the input condition create the corresponding Job
My input parameter: "maven" (to create Maven job) , else block for freestyle Job.
if(params[build_type]=="maven"){
mavenJob('example') {
using(template_job)
scm {
svn {
location(svn_url)
}
}
}
}
freeStyleJob('example') {
using(template_job)
scm {
svn {
location(svn_url)
}
}
}
I'm facing the following error message and I'm very new to groovy so please excuse. Looking forward for any suggestions.Thanks.
Processing provided DSL script ERROR: (script, line 1) No such
property: params for class: script

The Job DSL script inherits the build parameters as variables in your Job DSL. So if you have a parameter named build_type, you can use it as a variable.
if (build_type == "maven") {
mavenJob('example') {
using(template_job)
scm {
svn {
location(svn_url)
}
}
}
}
See: User Power Moves: Parameterized Seed Job

Related

Jenkins Job DSL - can't load parmeters from file

DSL job:
#!groovy
def file = readFileFromWorkspace('params.properties').trim()
job('app-adm') {
label("adm")
println("#" + file + "#")
parameters{
file
}
steps
{
shell(readFileFromWorkspace('script-adm.sh'))
}
}
job('app-tst-mt')
{
parameters
{
booleanParam('FLAG', true)
}
steps
{
shell(readFileFromWorkspace('script-tst-mt.sh'))
}
}
params.properties:
choiceParam('OPTION', ['option 1 (default)', 'option 2', 'option 3'])
I've tried:
Use files as input to Jenkins JobDSL
adding through single variable like x=<param> and parameteres { x }
different formats
Nothing is working, through println inside job, I can clearly see that there is string that I want to put in parameters, but when doing so it dosen't register it and I don't get any params.
Okey, the answer is stupidly obvious but if anybody has same problem just make a shell job previous to DSL job in Jenkins build.
In this shell job you can easily modify files in workspace, so place there a whole dsl job (groovy script), and just replace parts of text with sed or envsubst.

How to pass paramaters to a pipelineJob in DSL

I have very similar pipeline jobs that have only differences are parameters. The goal is to create these jobs by passing parameters in a DSL script without any code duplication.
I followed this article. So If you run the DSL script below after you implemented the steps as mentioned in the article, my script able to run.
TL;DR
In that article adds a shared library and also have Jenkinsfile use that shared library.
I have a very similar approach. The difference is I want to create my build jobs via DSL and, changes default parameters of the Jenkinsfile by settings on the DSL.
The question is how can I pass/override parameters in the Jenkinsfile.
// BTW I'll run this code below in a loop. Open for any suggesstion
pipelineJob('AwesomeBild') {
description("A pipeline created by dsl")
definition {
cpsScm {
scm {
git {
remote { url('https://github.com/jalogut/jenkinsfile-shared-library-sample.git') }
branches('master')
// how can I pass params to the file
scriptPath('Jenkinsfile')
extensions { }
}
}
}
}
}
Edit
Parameters worked well. Here is the lastest version of the DSL file.
pipelineJob('AwesomeBild') {
description("A pipeline created by dsl")
parameters {
stringParam( "key", "value" )
}
definition {
cpsScm {
scm {
git {
remote { url('https://github.com/jalogut/jenkinsfile-shared-library-sample.git') }
branches('master')
// how can I pass params to the file
scriptPath('Jenkinsfile')
extensions { }
}
}
}
}
}
The solution is simple:
just use $key, but leave the single quotes:
scriptPath('Jenkinsfile$key')

How to add "single conditional steps" under build section using dsl script

I'm currently trying to develop a DSL script that can create a jenkins job with all required plugins and options.
I think I've almost completed all the section. But, I stuck up under build section where I've to include "conditional steps (single)" under Build.
Actually what I wanted is this
But, what I get is this
Here's the code that I used,
job('Sample_dev') {
steps {
conditionalSteps {
condition {
alwaysRun()
}
}
maven {
goals('install')
}
}
}
You have done few mistakes there:
Using multi-step DSL for achieving single step.
Pushed maven outside context like individual step.
Wrong DSL for Maven Step declaration.
Try following
job('Sample_dev')
{
steps{
singleConditionalBuilder{
condition{
alwaysRun()
}
buildStep {
maven{
targets('install')
name('')
pom('')
properties('')
jvmOptions('')
usePrivateRepository(false)
settings {
standard()
}
globalSettings {
standard()
}
injectBuildVariables(false)
}
}
runner {
fail()
}
}
}
}
The creator has deployed most on this url https://jenkinsci.github.io/job-dsl-plugin. But I would suggest you install in you local instance and access it via http://<your-jenkins-host>:<port> /plugin/job-dsl/api-viewer/index.html as Job DSL support auto generation so there is bright chance that plugin not listed above still has DSL support.

Job DSL Restrict jobs to selected nodes

I am struggling to restrict Jenkins job to specific nodes using Job DSL plugin.
I tried something like :
job("campaign") {
parameters {
stringParam("ARTIFACT_NUMBER", "","")
nodeParam('TEST_HOST') {
defaultNodes(["Slave"])
}
}
steps {
shell('''#!/bin/bash
ARTIFACT_DIR=daily_${ARTIFACT_NUMBER}
echo ${ARTIFACT_DIR}
''')
}
}
but no success. Basically, I want to set the property Restrict where this project can run through Job DSL plugin
The label method sets the Restrict where this project can run on job level:
job('example') {
label('agentA agentB')
}
See the API viewer for details: https://jenkinsci.github.io/job-dsl-plugin/#path/job-label

Jenkins job dsl and MSTest integration

Jenkins Job DSL plugin is an extremely nice way to store CI config in repo and vary it from branch to branch.
The question is - is there a natural or close to natural way to run MSTest tests, parse results and display them.
Right now I do a powershell call, but that gives me only logs, not UI integration.
def testSomeProjectJob = job(testSomeProjectJobName) {
steps {
powerShell("& ${vstest} '${root}/SomeProject/SomeProject.Tests/bin/Debug/SomeProject.Tests.dll' ")
}
}
May be there is a publisher or a trick with templating, or some tips of writing a plugin to JOB DSL for that
UPD: final script template for MSTest and VSTest using #daspilker answer, jenkins xUnit Plugin and archiveXUnit
job('RunTests') {
steps {
// VSTEST
powerShell("& ${vstest} 'path/to/Tests.dll' /logger:trx ")
// Or MSBUILD
powerShell("& ${msbuild} /testcontainer:'path/to/Tests.dll' ")
}
publishers {
archiveXUnit {
msTest {
pattern('**/*.trx')
// deleteOutputFiles()
}
}
}
}
Using a PowerShell step is a good start. Install the xUnit Plugin to parse and display the results. It can parse all sorts of test results including MSTest. And you can use the DSL to configure the plugin.
Example:
job('example') {
steps {
powerShell('...')
}
publishers {
archiveXUnit {
msTest {
pattern('path/to/test/results')
}
}
}
}
Its for VSTest but I had to end up using the configure block to be able to use it in the DSL jobs.
static Closure useVsTest(List<String> dlls) {
return {
it / 'builders' << 'org.jenkinsci.plugins.vstest__runner.VsTestBuilder' {
vsTestName 'VS 14.0'
testFiles dlls.join('\n')
settings ''
testCaseFilter ''
enablecodecoverage false
useVsixExtensions true
platform 'x86'
otherPlatform ''
framework 'framework45'
otherFramework ''
logger 'trx'
otherLogger ''
cmdLineArgs '/TestAdapterPath:"."'
failBuild true
}
}
}

Resources