I have a Jenkins seed DSL job:
job("cronjob/${ACTION}_${ENVRIONMENT}_environment_CRONJOB") {
scm {
git('https://git_user#github.com/abc-Data/devops.git','*/develop')
}
triggers {
scm("${SCHEDULE}")
}
steps {
ansiblePlaybook("ansible/scripts/ansible-${ACTION}.yml") {
inventoryPath("/etc/ansible/hosts")
credentialsId("usercred")
extraVars {
extraVar('environment_name',"${ENVRIONMENT}",false)
}
}
}
}
ACTION, ENVIRONMENT and SCHDULE are parameters.
ACTION can have values of create or remove, and I have two ansible playbooks ansible-create.yml and ansible-remove.yml.
When I run the sseed job, I got the following error:
ERROR: (unknown source) No signature of method: javaposse.jobdsl.dsl.helpers.step.StepContext.ansiblePlaybook() is applicable for argument types: (org.codehaus.groovy.runtime.GStringImpl, script$_run_closure1$_closure4$_closure5) values: [ansible/scripts/ansible-create.yml, ...]
Finished: FAILURE
The ansiblePlaybook("ansible/scripts/ansible-${ACTION}.yml") does not work with the variable ACTION.
If I hard code the the script name in ansiblePlaybook, the seed job will create a new job.
The other two variables work fine in the DSL script.
What did I miss here?
Thanks!
As #daggett suggested above, I changed the code as below:
job("cronjob/${ACTION}_${ENVRIONMENT}_environment_CRONJOB") {
scm {
git('https://git_user#github.com/abc-Data/devops.git','*/develop')
}
triggers {
scm("${SCHEDULE}")
}
steps {
ansiblePlaybook("ansible/scripts/ansible-${ACTION}.yml" as String) {
inventoryPath("/etc/ansible/hosts")
credentialsId("usercred")
extraVars {
extraVar('environment_name',"${ENVRIONMENT}",false)
}
}
}
}
It works as expect and create a new job with the use entered variable values. Thanks to you again #daggett!
Related
I have a groovy script to setup a scheduled job in Jenkins.
I want to execute some shell scripts on failed build.
If I had the scripts manually after the job creation after the job is updated by groovy script, they run.
But the groovy script does not add it:
job('TestingAnalysis') {
triggers {
cron('H 8 28 * *')
}
steps {
shell('some jiberish to create error')
}
publishers {
postBuildScripts {
steps {
shell('echo "fff"')
shell('echo "FFDFDF"')
}
onlyIfBuildSucceeds(false)
onlyIfBuildFails(true)
}
retryBuild {
rerunIfUnstable()
retryLimit(3)
fixedDelay(600)
}
}
}
Every thing works fine except:
postBuildScripts {
steps {
shell('echo "fff"')
shell('echo "FFDFDF"')
}
onlyIfBuildSucceeds(false)
onlyIfBuildFails(true)
}
This is my result:
I tried postBuildSteps and also got error.
I tried also with error:
postBuildScripts {
steps {
sh' echo "ggg" '
}
onlyIfBuildSucceeds(false)
onlyIfBuildFails(true)
}
Take a look at JENKINS-66189 seems like there is an issue with version 3.0 of the PostBuildScript in which the old syntax (that you are using) is no longer supported. In order to use the new version it in a Job Dsl script you will need to use Dynamic DSL syntax.
Use the following link in your own Jenkins instance to see the correct usage:
YOUR_JENKINS_URL/plugin/job-dsl/api-viewer/index.html#path/freeStyleJob-publishers-postBuildScript.
it will help you build the correct command. In your case it will be:
job('TestingAnalysis') {
triggers {
cron('H 8 28 * *')
}
steps {
shell('some jiberish to create error')
}
publishers {
postBuildScript {
buildSteps {
postBuildStep {
stopOnFailure(false) // Mandatory setting
results(['FAILURE']) // Replaces onlyIfBuildFails(true)
buildSteps {
shell {
command('echo "fff"')
}
shell {
command('echo "FFDFDF"')
}
}
}
}
markBuildUnstable(false) // Mandatory setting
}
}
}
Notice that instead of using functions like onlyIfBuildSucceeds and onlyIfBuildFails you now just pass a list of relevant build results to the results function. (SUCCESS,UNSTABLE,FAILURE,NOT_BUILT,ABORTED)
I am working on a project and i have to configure a jenkins using JCasC (config as code plugin).
I have to create a job BUT i can't pass variables in the script.
My code:
freeStyleJob("SEED") {
parameters {
stringParam("MY_PARAMETER", "defaultValue", "A parameter")
}
steps {
jobDsl {
scriptText('''
job("seedJOB") {
displayName('${MY_PARAMETER}') // don't work
description("${MY_PARAMETER}") // don't work
//description("$MY_PARAMETER") // don't work
//description('$MY_PARAMETER') // don't work
// i tried to use triple full quotes instead of triple single quote but it's not working...
... here the job...
'''.stripIndent())
}
}
EDIT: BEST SOLUTION HERE:
i'm writing groovy code in """ quotes so if I want to evaluate variable : I don't have to put ${} just write your variable name:
With the solution:
freeStyleJob("SEED") {
parameters {
stringParam("MY_PARAMETER", "defaultValue", "A parameter")
}
steps {
jobDsl {
scriptText('''
job("seedJOB") {
displayName('MY_PARAMETER) // solution
... here the job...
'''.stripIndent())
}
}
easy!
May you could write it to a file ? You'll get something like that in your step:
steps {
shell('echo $DISPLAY_NAME > display_name.txt')
jobDsl {
scriptText('''
job("seedjob") {
String jobname = readFileFromWorkspace('display_name.txt').trim()
displayName(jobname)
}
'''.stripIndent())
}
}
You could also use a .properties file to do it more properly.
I have the following code to build as a job-dsl with "Active Choice Plugin":
freeStyleJob('job') {
description('description')
// Label which specifies on which nodes this job can be run.
label('master')
logRotator {
numToKeep(10)
}
//This Build is parametrized
parameters {
activeChoiceReactiveParam('branch') {
description('Select the branch you are going to use')
choiceType('SINGLE_SELECT')
script('["integration", "master"]')
fallbackScript('"Error. No branch to select."')
filterable(true)
}
}
}
I when executing it I get the following error:
How can this error be solved?
The syntax is actually a bit different:
job('example-1') {
parameters {
activeChoiceReactiveParam('CHOICE-1') {
description('Allows user choose from multiple choices')
filterable()
choiceType('SINGLE_SELECT')
groovyScript {
script('["choice1", "choice2"]')
fallbackScript('"fallback choice"')
}
referencedParameter('BOOLEAN-PARAM-1')
referencedParameter('BOOLEAN-PARAM-2')
}
}
}
Use the API viewer to lookup the syntax:
https://jenkinsci.github.io/job-dsl-plugin/#path/job-parameters-activeChoiceReactiveParam
I need to share some code between several stages, which would also need to add post actions. To do so, I thought about putting everything in a method, which will be called from
pipeline {
stages {
stage('Some') {
steps {
script { commonCode() }
}
}
}
}
However, I'm not sure how could I install post actions in from commonCode. Documentation does not mention a thing. Looking at the code, implies that this DSL is basically just playing with a hash map, but I don't know would it be possible to access it from the method and modify on the fly.
Basically I would like to do something like this in commonCode:
if (something) {
attachPostAction('always', { ... })
} else {
attachPostAction('failure', { ... })
}
The only thing that works so far is that in commonCode I do:
try {
...
onSuccess()
} catch (e) {
onError()
} finally {
onAlways()
}
But was wondering if there is a more elegant way...
Now that I better understand the question (I hope)...
This is a pretty interesting idea--generate your post actions on the fly in previous stages.
It turns out to be really easy. I tried one option (success) that stored various closures in a list, then iterate through the list and run all the closures in the post action. Then I did another (failure) where I just saved a single closure as a variable and ran that. Both work well.
Below is the code that does this. Uncomment the error line to simluate a failed build.
def postSuccess = []
def postFailure
pipeline {
agent any
stages {
stage('Success'){
steps {
script {
println "Configure Success Post Steps"
postSuccess[0] = {echo "This is a successful build"}
postSuccess[1] = {
echo "Running multiple steps"
sh "ls -latr"
}
}
}
}
stage('Failure'){
steps {
script {
println "Configure Failure Post Steps"
postFailure = {
echo "This build failed"
echo "Running multiple steps for failure"
sh """
whoami
pwd
"""
}
}
// error "Simulate a failed build" //uncomment this line to make the build fail
}
}
} // stages
post {
success {
echo "SUCCESS"
script {
for (def my_closure in postSuccess) {
my_closure()
}
}
}
failure {
echo "FAILURE!"
script {
postFailure()
}
}
}
} // pipeline
You can use regular groovy scripting outside of the pipeline block. While I haven't tried it, you should be able to define a method outside of there and then call it from inside the pipeline. But method calls can't be called as steps. You would need to wrap it in a script step. But post actions take the same steps as steps{} blocks, so if you can use it insteps, you can use it in the post sections. You will need to watch scoping carefully or you will end up trying to sort out why things are null in some places.
You can also used a shared library. You could define a step in the shared library and then use it like any other step in a steps{} block or one of the post blocks.
I using Jenkins CI with Job DSL and Multijob plugins. I'm attempting to define a parametrized Multijob containing conditional step using DSL, but I fail to figure out the correct syntax. My code:
multiJob("MyJob")
{
parameters {
stringParam("PLATFORM", "Win32")
stringParam("CONFIGURATION", "Release")
}
steps
{
phase("Build") {
job("BuildJob") { sameNode() }
}
conditionalSteps {
condition {
and { stringsMatch("${PLATFORM}", "Win32", false) } { stringsMatch("${CONFIGURATION}", "Release", false) }
}
runner('Fail')
steps {
phase("Prepare installer") {
job("PrepareInstallerJob") { sameNode() }
}
}
}
}
}
Running this I get the following error:
Processing DSL script My.groovy
ERROR: (My.groovy, line 117) No such property: PLATFORM for class: javaposse.jobdsl.dsl.helpers.step.RunConditionContext
Finished: FAILURE
When line 117 is the line containing the "and" condition.
What would be the correct syntax? Why does not it resolve the PLATFORM parameter?
Groovy interpolates double quoted strings, see String interpolation. You need to use single quotes to avoid the interpolation, e.g. '${PLATFORM}'.