Jenkins Job DSL: Using parameters in groovyScript in job step - jenkins

For my build job "generated-job-1" I need several parameters, which are passed in when the build (of the generated-job-1) is triggered via URL.
Here my Job Definition with parameters inside the SeedJob DSL:
job('generated-job-1'){
label ('master')
parameters{
stringParam('DEPLOY_URI', 'https://192.168.200.176/hyperManager', 'Provide the URL where DeploymentManager can be accessed.')
stringParam('REG_ID', '12', 'The id of the owner (Registration) of this deployment.')
}
steps {
groovyCommand(readFileFromWorkspace('stepscript.groovy')){
prop('name', 'value')
prop('DEPLOY_URI', $DEPLOY_URI)
}
}
}
I tried to use DEPLOY_URI, $DEPLOY_URI and ${DEPLOY_URI} and it the build fails with different error messages like
No such property: DEPLOY_URI for class: javaposse.jobdsl.dsl.helpers.step.GroovyContext
or
ERROR: (script, line 12) No such property: $DEPLOY_URI for class: javaposse.jobdsl.dsl.helpers.step.GroovyContext
or
ERROR: (script, line 12) No signature of method: javaposse.jobdsl.dsl.helpers.step.GroovyContext.$() is applicable for argument types: (script$_run_closure1$_closure3$_closure4$_closure5) values: [script$_run_closure1$_closure3$_closure4$_closure5#1a11cf0]
How can I define and pass those parameters to my step-script.groovy?
How could I use those parameters in other steps, such as shell or batchFile?
How do I access those parameters in my step-script.groovy, to work with the given data?
I searched for a while now and tried hard to get it working... No success.
Help really appreciated, as I am new to Job DSL and to Groovy.
Thanks in advance,
Anne

You need to put the variable name in quotes so that it gets evaluated when the generated job is executed, not when the DSL script runs.
job('generated-job-1') {
parameters {
stringParam('DEPLOY_URI', '...', '...')
}
steps {
groovyCommand(readFileFromWorkspace('stepscript.groovy')) {
prop('DEPLOY_URI', '$DEPLOY_URI')
}
}
}

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.

Jenkins Password Param in Groovy

I'm trying to add a passwordParam to my Jenkins groovy file as such.
The intention is to have the password picked up by a job at runtime
pipelineJob(jobName) {
displayName(displayString)
parameters {
choiceParam('ARTEFACT',artefactName,'Artefact to deploy?')
choiceParam('CLUSTER',cluster,'Cluster to push to')
stringParam('BRANCH','main','What branch should be used?')
passwordParam('proxyUser', 'password123', 'ProxyPassword')
}
But I get the error
ERROR: (job_delete_release.groovy, line 23) No signature of method: javaposse.jobdsl.dsl.helpers.BuildParametersContext.passwordParam() is applicable for argument types: (java.lang.String, java.lang.String, java.lang.String) values: [proxyUser, password123, ProxyPassword]
According to the documentation here it should be possible.
I'm not sure what I'm doing wrong or if I'm missing something really obvious.
It looks like you are mixing DSL and Declarative syntaxs.
What you are writing here is JobDSL, however your link is to declarative code.
In the section you are writing you can only use the parameters available to JobDSL which can be found here:
Click the three dots in the parameters on https://jenkinsci.github.io/job-dsl-plugin/#method/javaposse.jobdsl.dsl.jobs.MavenJob.parameters
So for the JobDSL I believe you would use nonStoredPasswordParam (note I have never used it)
https://jenkinsci.github.io/job-dsl-plugin/#path/javaposse.jobdsl.dsl.jobs.MavenJob.parameters-nonStoredPasswordParam
If you wanted your parameters in Declarative you would write them inside the pipeline section.
e.g.
pipeline {
agent any
parameters {
string(name: 'script_args', defaultValue: '--out_file --purge', description: 'Command line args to pass to script')
}

Jenkins pipelineJob DSL not interpreting variables in pipeline script

I'm trying to generate Jenkins pipelines using the pipelineJob function in the jobDSL pluging, but cannot pass parameters from the DSL to the pipeline script. I have several projects that use what is essentially the same Jenkinsfile, with differences only in a few steps. I'm trying to use the JobDSL plugin to generate these pipelines on the fly, with the values I want changed in them interpreted to match the parameters to the DSL.
I've tried just about every combination of string interpretation that I can in the pipeline script, as well as in the DSL, but cannot get Jenkins/groovy to interpret variables in the pipeline script.
I'm calling the job DSL in a pipeline step:
def projectName = "myProject"
def envs = ['DEV','QA','UAT']
def repositoryURL = 'myrepo.com'
jobDsl targets: ['jobs/*.groovy'].join('\n'),
additionalParameters: [
project: projectName,
environments: envs,
repository: repositoryURL
],
removedJobAction: 'DELETE',
removedViewAction: 'DELETE'
The DSL is as follows:
pipelineJob("${project} pipeline") {
displayName('Pipeline')
definition {
cps {
script(readFileFromWorkspace(pipeline.groovy))
}
}
}
pipeline.groovy:
pipeline {
agent any
environment {
REPO = repository
}
parameters {
choice name: "ENVIRONMENT", choices: environments
}
stages {
stage('Deploy') {
steps {
echo "Deploying ${env.REPO} to ${params.ENVIRONMENT}..."
}
}
}
}
The variables that I pass in additionalParameters are interpreted in the jobDSL script; a pipeline with the correct name does get generated. The problem is that the variables are not passed to the pipeline script read from the workspace - the Jenkins configuration for the generated pipeline looks exactly the same as the file, without any interpretation on the variables.
I've made a number of attempts at getting the string to interpret, including a lot of variations of "${environments}", ${environments}, $environments, \$environments...I can't find any that work. I've also tried reading the file as a gstringImpl:
script("${readFileFromWorkspace(pipeline.groovy)}")
Does anyone have any ideas as to how I can make variables propagate down to the pipeline script? I know that I could just use a for loop to do string.replaceAll() on the script text, but that seems cumbersome; there's got to be a better way.
I've come up with a way to make this work. It's not what I'd prefer, which is having the string contents of the file implicitly interpreted during job creation, but it does work; it just adds an extra step.
import groovy.text.SimpleTemplateEngine
def fileContents = readFileFromWorkspace "pipeline.groovy"
def engine = new SimpleTemplateEngine()
template = engine.createTemplate(fileContents).make(binding.getVariables()).toString()
pipelineJob("${project} pipeline") {
displayName('Pipeline')
definition {
cps {
script(template)
}
}
}
This reads a file from your workspace, then uses it as a template with the binding variables. The other changes needed to make this work are escaping any variables used in your Jenkinsfile script, like \${VARIABLE} so that they are expanded at runtime, not at the time you build the job. Any variables you want to be expanded at job creation should be referenced as ${VARIABLE}.
You could achieve what you're trying to do by defining environment variables in the pipelineJob and then using those variables in your pipeline.
They are a bit limited because environment variables are strings, but it should work for basic stuff
Ex.:
//job-dsl
pipelineJob('example') {
environmentVariables {
// these vars could be specified by parameters of this job
env('repository', 'blah')
env('environments', "a,b,c"]) //comma separated string
}
displayName('Pipeline')
definition {
cps {
script(readFileFromWorkspace(pipeline.groovy))
}
}
}
}
And then in the pipeline:
//pipeline.groovy
pipeline {
agent any
environment {
REPO = env.repository
}
parameters {
choice name: "ENVIRONMENT", choices: env.environments.split(',')
//note the need to split the comma separated string above
}
}
You need to use the complete job name as a variable without the quotes. E.g., if JOBNAME is a parameter containing the entire job name:
pipelineJob(JOBNAME) {
displayName('Pipeline')
definition {
cps {
script(readFileFromWorkspace(pipeline.groovy))
}
}
}

Start jenkins job immediately after creation by seed job, with parameters?

Start jenkins job immediately after creation by seed job
I can start a job from within the job dsl like this:
queue('my-job')
But how do I start a job with argument or parameters? I want to pass that job some arguments somehow.
Afaik, you can't.
But what you can do is creating it from a pipeline (jobDsl step), then run it. Something more or less like...
pipeline {
stages {
stage('jobs creation') {
steps {
jobDsl targets: 'my_job.dsl',
additionalParameters: [REQUESTED_JOB_NAME: "my_job's_name"]
build job: "my_job's_name",
parameters: [booleanParam(name: 'DRY_RUN', value: true)]
}
}
}
}
With a barebones 'my_job.dsl'...
pipelineJob(REQUESTED_JOB_NAME) {
definition {
// blah...
}
}
NOTE: As you see, I explicitly set the name of the job from the calling pipeline (the REQUESTED_JOB_NAME var) because otherwise I don't know how to make the jobDSL code to return the name of the job it creates back to the calling pipeline.
I use this "trick" to avoid the "job params go one run behind" problem. I use the DRY_RUN param of the job (I use a hidden param, in fact) to run a "do-nothing" build as its name implies, so by the time others need to use the job for "real stuff" its params section has already been properly parsed.

Jenkins DSL : Job SLack publisher : baseUrl() method not available

I use Jenkins 2.63 with and Slack Notifier plugin 2.2
I need to generate Jobs with SlackNotifier by Job DSL but I can not set the Base URL in the DSL, I get this message :
ERROR: (script, line 145) No signature of method: baseUrl() is applicable for argument types: (java.lang.String) values: [https://my.domain.slack.com/services/hooks/jenkins-ci/] Possible solutions: authToken(), authTokenCredentialId(), botUser(), commitInfoChoice(), customMessage(), includeCustomMessage(), includeTestSummary(), notifyAborted(), notifyBackToNormal(), notifyFailure(), notifyNotBuilt(), notifyRegression(), notifyRepeatedFailure(), notifySuccess(), notifyUnstable(), room(), sendAs(), startNotification(), teamDomain() Finished: FAILURE
here is my DSL script
publishers {
def slackParam = new groovy.json.JsonSlurper().parse(new File(channelFile))
slackNotifier {
baseUrl(slackParam.url)
authTokenCredentialId(slackParam.authTokenCredentialId)
includeTestSummary(true)
notifyAborted(true)
notifyBackToNormal(true)
notifyFailure(true)
notifyNotBuilt(true)
notifyRegression(true)
notifyRepeatedFailure(true)
notifyUnstable(true)
room(slackParam.room)
}
}
But in the job config.xml I can find this parameter.
Can anyone help me to set the base URL parameter ?
Thanks a lot.
Using the Configure Block: https://github.com/jenkinsci/job-dsl-plugin/wiki/The-Configure-Block
configure { project ->
project / publishers << 'jenkins.plugins.slack.SlackNotifier' {
baseUrl("https://whatever.slack.com/services/hooks/jenkins-ci/")
room("#room")
notifyAborted(true)
notifyFailure(true)
notifyNotBuilt(false)
notifyUnstable(true)
notifyBackToNormal(true)
notifySuccess(true)
notifyRepeatedFailure(false)
startNotification(false)
includeTestSummary(false)
includeCustomMessage(true)
customMessage("Environment")
sendAs(null)
commitInfoChoice("AUTHORS_AND_TITLES")
teamDomain("yourDomain")
authTokenCredentialId("token")
}
}
Place this outside of your steps at the bottom of your job. You should see the changes reflected in the UI and config.xml for the job.

Resources