Parameterized Build Syntax for Jenkins Configuration as Code Plug-in (JCasC) - jenkins

I'm trying to use the configuration as code (JCasC) plug-in to create a pipeline job that takes in build parameters but I can't find the syntax for this anywhere online. I'm writing the configuration in YAML.
On the GUI, the field is called "This build is paramertized" and it is under the 'General' heading. I need to define two string parameters: CLUSTER_ID=cluster_id and OPENSHIFT_ADMINSTRATION_BRANCH=develop.
This is the yaml file that I am trying to edit:
jobs:
- script: >
folder('test1'){
pipelineJob('test1/seedJobTest') {
description 'seedJobTest'
logRotator {
daysToKeep 10
}
definition {
cpsScm {
scm {
git {
remote {
credentials "xxx"
url 'xxx'
}
branches 'refs/head/master'
scriptPath 'Jenkinsfile'
extensions { }
}
}
}
}
configure { project ->
project / 'properties' / 'EnvInjectJobProperty' {
'on'('true')
}
project / 'properties' / 'org.jenkinsci.plugins.workflow.job.properties.DisableConcurrentBuildsJobProperty' {}
}
}
}
Thanks for your help!

Solution
jobs:
- script: >
folder('test1'){
pipelineJob('test1/seedJobTest') {
description 'seedJobTest'
logRotator {
daysToKeep 10
}
parameters {
stringParam("CLUSTER_ID", "cluster_id", "your description here")
stringParam("OPENSHIFT_ADMINSTRATION_BRANCH", "develop", "your description here")
}
definition {
cpsScm {
scm {
git {
remote {
credentials "xxx"
url 'xxx'
}
branches 'refs/head/master'
scriptPath 'Jenkinsfile'
extensions { }
}
}
}
}
configure { project ->
project / 'properties' / 'EnvInjectJobProperty' {
'on'('true')
}
project / 'properties' / 'org.jenkinsci.plugins.workflow.job.properties.DisableConcurrentBuildsJobProperty' {}
}
}
}
How to Figure this Stuff Out in the Future - XML Job To DSL (Jenkins Plugin)
Here's how I would go about figuring this kind of thing:
Manually create a temporary pipeline job with the things you want in your seed job (the one you want to automate).
Install (if only temporarily) the "XML Job To DSL" Jenkins plugin.
Go to the main Jenkins Dashboard
In the left navigation, you'll find "XML Job To DSL." Click it.
Select the temporary job you created and click "Convert selected to DSL"
When I went about getting the params snippet for this answer, I did as I described above, but simply created two parameters. I ended up with this:
pipelineJob("test") {
description()
keepDependencies(false)
parameters {
stringParam("CLUSTER_ID", "cluster_id", "your description here")
stringParam("OPENSHIFT_ADMINSTRATION_BRANCH", "develop", "your description here")
}
definition {
cpsScm {
"" }
}
disabled(false)
}
Read-Only Parameter Option
One more thing, in case it's useful to you (as it was to me). If you want to create a parameterized seed job but you don't want those to be editable at build time, you can install the "Readonly Parameter" Jenkins plugin; then, you'll be able to do this kind of thing:
jobs:
- script: >
pipelineJob("Param Example") {
description()
keepDependencies(false)
parameters {
wHideParameterDefinition {
name('AGENT')
defaultValue('docker-host')
description('Node on which to run.')
}
wHideParameterDefinition {
name('ENV_FILE_DIR')
defaultValue('local2')
description('Name of environment directory which houses .env')
}
booleanParam("include_search_stack", false, "Build/run the local Fess, Elasticsearch, and Kibana containers.")
booleanParam("SKIP_404_GENERATION", false, "Helpful sometimes during local development.")
}
definition {
cpsScm {
scm {
git {
remote {
url("https://myrepo/blah.git")
credentials("scm")
}
branch("master")
}
}
scriptPath("pipeline/main/Jenkinsfile")
}
}
disabled(false)
}
In this example, the top two params, AGENT and ENV_FILE_DIR are sort of "hard-coded" from CasC, because the those parameters are not editable at build-time. However, the include_search_stack and SKIP_404_GENERATION parameters are editable. I used this mixed example to show that either/both are usable in the same job.
Read-only parameters have been useful in some of my use cases.

Related

Job DSL plugin | Shared Library | Pipeline jobs | Github Hook not working

Please bear with me the description might be long but it might give a clean picture of the intent and issue.
I have used Job DSL Plugin to create a seeder job, which in turns creates two new Jobs. I have 2 separate repositories
For maintaining jenkins pipeline scripts.
For actual code to build.
First I have created a pipeline job in jenkins which in turns creates view and 2 jobs. Config shown below:
The Jenkinsfile given below uses Job DSL plugin api, reads the groovy script and creates the required 2 jobs.
node('master') {
checkout scm
jobDsl targets: ['dsl/seedJobBuilder.groovy'].join('\n'),
removedJobAction: 'IGNORE',
removedViewAction: 'IGNORE',
lookupStrategy: 'SEED_JOB'
}
seedJobBuilder.groovy creates a dsl pipeline job whose task would be to build the actual codebase.
listView('Build Pipelines') {
description('All build and deploy jobs')
jobs {
names(
'build',
'deploy',
)
}
columns {
status()
weather()
name()
lastSuccess()
lastFailure()
lastDuration()
buildButton()
}
}
def buildCommerce = pipelineJob('build') {
properties {
githubProjectUrl("${projectRepo}") // url of actual code repo not the jenkins script repo
}
definition {
cpsScm {
scm {
git {
remote {
url("${pipelineRepo}") // jenkins script repo url
credentials("somecredentials")
}
branch('${JENKINS_SCRIPT_BRANCH}')
}
scriptPath('pipelines/pipelineBuildEveryDay.groovy')
lightweight(false)
}
}
}
triggers {
githubPush()
}
}
Config of the above job created by Job DSL:
This job reads the pipelineBuildEveryDay groovy script, checkout the actual codebase and build and deploy.
The place where I am struggling is how do we trigger build on this second job through github hook or through ghprb. Since I don't want to manipulate manually the second job and the git url of the job is the script repo URL not the codebase URL. Is it possible to do this even? If yes what am I missing?
I have the webhook configured
pipelineBuildEveryDay.groovy
pipeline {
libraries {
lib("shared-library#${params.JENKINS_SCRIPT_BRANCH}")
}
agent {
node {
label 'master'
}
}
options {
skipDefaultCheckout(true) // No more 'Declarative: Checkout' stage
}
stages {
stage('Crazy Build Pipeline') {
tools {
jdk 'java11'
}
stages {
stage('Prepare build name') {
steps{
script{
currentBuild.displayName = "${currentBuild.number}-build"
}
}
}
stage('Checkout') {
steps {
cleanWs()
script {
checkoutRepository("${projectDir}", "${params.PROJECT_TAG}", "${params.PROJECT_REPO}")
}
}
}
stage('Run Tests') {
steps {
echo "Running test coming soon..."
}
}
}
}
}
// post build actions
post {
success {
echo "success"
}
failure {
echo "failure"
}
}
}
Well the suffering comes to an end. Posting this answer for anyone struggling with similar sort of issues.
Make sure you uncheck all other types of trigger, the only checked one should be pull request builder.
The part which screwed me was the Project URL. In my case in SCM part the github url was of the Jenkins-scripts repository URL not the URL of the codebase I want to build. So I tried to use my codebase repository URL in Github Project URL textbox.
But the real problem was using repository URL in the format 'https://code-base-repo-url.git' instead it should be 'https://code-base-repo-url'. Sounds stupid? Yeah I know!
Finally the complete Job config pipeline script if it helps:
def pipelineRepo = 'https://jenkins-script-repo'
def projectRepo = 'https://code-base-repo-url'
def projectTag = '${GIT_BRANCH}'
def buildCommerce = pipelineJob('build') {
properties {
githubProjectUrl("${projectRepo}")
}
definition {
cpsScm {
scm {
git {
remote {
url("${pipelineRepo}")
credentials("use-your-own-user-pass-cred")
}
branch('${JENKINS_SCRIPT_BRANCH}')
}
scriptPath('pipelines/pipelineBuildEveryDay.groovy')
lightweight(false)
}
}
}
triggers {
githubPullRequest {
admin('use_your_own_admin')
triggerPhrase('build please')
useGitHubHooks()
permitAll()
displayBuildErrorsOnDownstreamBuilds()
extensions {
commitStatus {
context('Jenkins')
completedStatus('SUCCESS', 'All is well')
completedStatus('FAILURE', 'Something went wrong. Investigate!')
completedStatus('ERROR', 'Something went really wrong. Investigate!')
}
}
}
}
}

Coalesce parameters in Jenkins Job DSL

I have a pipelineJob defined in Job DSL.
It runs a pipeline/Jenkinsfile which it checks out of git.
I want people to be able to type in the git branch from which to pull the Jenkinsfile - (i.e. in a stringParam) - or, if they have not typed in a branch, to default to a branch which I have set in a choiceParam (i.e. this will be 'develop' or 'master')
This does not work:
pipelineJob('some-job') {
parameters {
choiceParam('gitCreds', [gitCreds], 'Stash credential')
stringParam('gitUrl', 'https://some-repo.git', 'URL for the Stash repo')
stringParam('gitBranchOverride', '', 'Type in some feature branch here if you wish')
choiceParam('gitBranch', ['develop'], '...otherwise the job should default to a branch here')
}
definition {
cpsScm {
scm {
git {
branch('$gitBranchOverride' ?: '$gitBranch')
extensions {
wipeOutWorkspace()
}
remote {
credentials(gitCreds)
url ('$gitUrl')
}
}
}
}
}
}
It works if I enter a value into gitBranchOverride, but if I don't, it seems to enumerate all the branches, and check out a random one - i.e. it's not honouring the value in gitBranch
Don't know if i'm understanding your problem correctly but this is how I have my code for creating pipelinejobs:
def git_branch = getBinding().getVariable('GIT_BRANCH')
def gitrepo = "ssh://git#some.git.repo/somerepo.git"
def credential_id = "awesomecredentials"
pipelineJob("MyAwesomeJob") {
description("""This job is awesome\n\n__input__:\n* My parameter\n* Branch\n\n__branch__: ${git_branch}""")
parameters {
stringParam(name='MyParameter', description='AwesomeParameterHere')
stringParam('branch', defaultValue='origin/develop', description='Branch to build')
}
definition {
cpsScm {
scm {
git {
branch('$branch')
remote {
url("gitrepo")
credentials(credential_id)
}
}
scriptPath("jenkins/my_awesome_pipeline/Jenkinsfile")
}
}
}
}
With this, my job is created with a parameter for branch with a default one selected.

Build Periodically Syntax for Jenkins Configuration as Code Plug-In (JCasC)

I'm trying to use the configuration as code (JCasC) plug-in to create a pipeline job that builds periodically, but I can't find the syntax for this anywhere online. I'm writing the configuration in YAML.
The "Build Periodically" field is under Build Triggers in the pipeline jobs and has a text field called Schedule. My schedule is 0 6-19 * * *
Is this even possible to do?
This is the yaml file that I am trying to edit:
jobs:
- script: >
folder('test1'){
pipelineJob('test1/seedJobTest') {
description 'seedJobTest'
logRotator {
daysToKeep 10
}
definition {
cpsScm {
scm {
git {
remote {
credentials "xxx"
url 'xxx'
}
branches 'refs/head/master'
scriptPath 'Jenkinsfile'
extensions { }
}
}
}
}
configure { project ->
project / 'properties' / 'EnvInjectJobProperty' {
'on'('true')
'info' {
'propertiesContent'('BRANCH=master')
}
}
project / 'properties' / 'org.jenkinsci.plugins.workflow.job.properties.DisableConcurrentBuildsJobProperty' {}
}
}
}
If using JCasC to configure your build/pipeline configuration:
To build periodically, regardless of SCM changes, you can add this block:
triggers {
cron('0 6-19 * * *')
}
To build periodically, only if there were SCM changes, you can use this block:
triggers {
scm('0 6-19 * * *')
}
To view this answer in context, here is a code snippet example:
jobs:
- script: |
job('PROJ-unit-tests') {
scm {
git(gitUrl)
}
triggers {
cron('0 6-19 * * *')
}
steps {
maven('-e clean test')
}
}
Snippet taken and adjusted from: https://github.com/jenkinsci/configuration-as-code-plugin/issues/876

Jenkins dsl configure block makes duplicate tabs

I'm trying to create a job DSL which creates a multibranch-pipeline job,
The job is being created successfully but there are some missing configurations in the multi-pipeline job so I tried to use the "configure" block.
The configure block indeed was created but it created a duplicate "tag" of jenkins.branch.BranchSource I guess I am missing something' I tried tons of manipulations but nothing worked for me.
Any advice?
This is my groovy DSL:
multibranchPipelineJob('TestDocker_pipeline_DSL') {
branchSources {
git {
remote(gitUrl)
credentialsId('Dev_Builder_ssh')
//includes("(V[0-9]+.[0-9]+([.]+[0-9]+)*)|(master)")
}
configure {
it / sources / data / "jenkins.branch.BranchSource" << "jenkins.plugins.git.GitSCMSource" {
id("8fd33e1d-07b6-4cc4-8f1c-a18d955b4b6e")
remote(gitUrl)
credentialsId('Dev_Builder_ssh')
traits{
"jenkins.scm.impl.trait.RegexSCMHeadFilterTrait"{
regex("V[0-9]+.[0-9]+([.]+[0-9]+)*)|(master)")
}
}
}
}
}
factory {
workflowBranchProjectFactory {
scriptPath('main/Docker/DockerJenkinsfileSlave.groovy')
}
}
orphanedItemStrategy {
discardOldItems {
numToKeep(3)
}
}
}
And this is the job XML being created:
Well After a lot of struggling I think that my problem was that I didn't define some of the TAGS as plugins in the groovy DSL and removing the "git" section also helped.
So the Final groovy that finally worked was this one:
branchSources {
configure {
it / sources / data / "jenkins.branch.BranchSource" << source (class: "jenkins.plugins.git.GitSCMSource", plugin:"git#3.9.2") {
remote(gitUrl)
credentialsId('Dev_Builder_ssh')
includes('*')
excludes('')
ignoreOnPushNotifications(false)
traits{
"jenkins.scm.impl.trait.RegexSCMHeadFilterTrait"{
regex("(V[0-9]+.[0-9]+([.]+[0-9]+)*)|(master)")
}
}
}
}
}
Which resulted this beutifull XML job:

Job DSL to create "Pipeline" type job

I have installed Pipeline Plugin which used to be called as Workflow Plugin earlier.
https://wiki.jenkins-ci.org/display/JENKINS/Pipeline+Plugin
I want to know how can i use Job Dsl to create and configure a job which is of type Pipeline
You should use pipelineJob:
pipelineJob('job-name') {
definition {
cps {
script('logic-here')
sandbox()
}
}
}
You can define the logic by inlining it:
pipelineJob('job-name') {
definition {
cps {
script('''
pipeline {
agent any
stages {
stage('Stage 1') {
steps {
echo 'logic'
}
}
stage('Stage 2') {
steps {
echo 'logic'
}
}
}
}
}
'''.stripIndent())
sandbox()
}
}
}
or load it from a file located in workspace:
pipelineJob('job-name') {
definition {
cps {
script(readFileFromWorkspace('file-seedjob-in-workspace.jenkinsfile'))
sandbox()
}
}
}
Example:
Seed-job file structure:
jobs
\- productJob.groovy
logic
\- productPipeline.jenkinsfile
then productJob.groovy content:
pipelineJob('product-job') {
definition {
cps {
script(readFileFromWorkspace('logic/productPipeline.jenkinsfile'))
sandbox()
}
}
}
I believe this question is asking something how to use the Job DSL to create a pipeline job which references the Jenkinsfile for the project, and doesn't combine the job creation with the detailed step definitions as has been given in the answers to date. This makes sense: the Jenkins job creation and metadata configuration (description, triggers, etc) could belong to Jenkins admins, but the dev team should have control over what the job actually does.
#meallhour, is the below what you're after? (works as at Job DSL 1.64)
pipelineJob('DSL_Pipeline') {
def repo = 'https://github.com/path/to/your/repo.git'
triggers {
scm('H/5 * * * *')
}
description("Pipeline for $repo")
definition {
cpsScm {
scm {
git {
remote { url(repo) }
branches('master', '**/feature*')
scriptPath('misc/Jenkinsfile.v2')
extensions { } // required as otherwise it may try to tag the repo, which you may not want
}
// the single line below also works, but it
// only covers the 'master' branch and may not give you
// enough control.
// git(repo, 'master', { node -> node / 'extensions' << '' } )
}
}
}
}
Ref the Job DSL pipelineJob: https://jenkinsci.github.io/job-dsl-plugin/#path/pipelineJob, and hack away at it on http://job-dsl.herokuapp.com/ to see the generated config.
This example worked for me. Here's another example based on what worked for me:
pipelineJob('Your App Pipeline') {
def repo = 'https://github.com/user/yourApp.git'
def sshRepo = 'git#git.company.com:user/yourApp.git'
description("Your App Pipeline")
keepDependencies(false)
properties{
githubProjectUrl (repo)
rebuild {
autoRebuild(false)
}
}
definition {
cpsScm {
scm {
git {
remote { url(sshRepo) }
branches('master')
scriptPath('Jenkinsfile')
extensions { } // required as otherwise it may try to tag the repo, which you may not want
}
}
}
}
If you build the pipeline first through the UI, you can use the config.xml file and the Jenkins documentation https://jenkinsci.github.io/job-dsl-plugin/#path/pipelineJob to create your pipeline job.
In Job DSL, pipeline is still called workflow, see workflowJob.
The next Job DSL release will contain some enhancements for pipelines, e.g. JENKINS-32678.
First you need to install Job DSL plugin and then create a freestyle project in jenkins and select Process job DSLs from the dropdown in the build section.
Select Use the provided DSL script and provide following script.
pipelineJob('job-name') {
definition {
cps {
script('''
pipeline {
agent any
stages {
stage('Stage name 1') {
steps {
// your logic here
}
}
stage('Stage name 2') {
steps {
// your logic here
}
}
}
}
}
''')
}
}
}
Or you can create your job by pointing the jenkinsfile located in remote git repository.
pipelineJob("job-name") {
definition {
cpsScm {
scm {
git {
remote {
url("<REPO_URL>")
credentials("<CREDENTIAL_ID>")
}
branch('<BRANCH>')
}
}
scriptPath("<JENKINS_FILE_PATH>")
}
}
}
If you are using a git repo, add a file called Jenkinsfile at the root directory of your repo. This should contain your job dsl.

Resources