jenkins yaml Jcasc triggers and poll scm to add jobs automatically - jenkins

I have the following jenkins yaml which works and puts in the jobs automatically. it wont add the credentials unless I go into UI and select the same ID "github" or allow me add polling or triggering
I have tried a number of combinations that either crash the deploy or don not add the jobs at all.
triggers {
pollSCM 'H/10 * * * *'
}
triggers {
cron (H/10 * * * *)
}
I would like to add cron and poll scm as once job is run manually its picked up from the repo jenkinsfile
jenkins:
systemMessage: "Jenkins: configured automatically with JCasC plugin\n\n"
tool:
git:
installations:
- home: "git"
name: "Default"
jobs:
- script: >
pipelineJob('my_pipleline_build') {
definition {
cpsScm {
scriptPath 'Jenkinsfile'
scm {
git {
remote { url 'https://github.com/my_pipleline_build.git' }
branch '*/master'
credentials: ('github')
extensions {}
}
}
}
}
}
- script: >
pipelineJob('my_other_pipleline_build') {
definition {
cpsScm {
scriptPath 'Jenkinsfile'
scm {
git {
remote { url 'https://github.com/cloud/my_other_pipleline_build.git' }
branch '*/my_pipleline_build'
credentials: ('github')
extensions {}
}
}
}
}
}

I was able to achieve using below,
- script: >
pipelineJob('my_other_pipleline_build') {
definition {
cpsScm {
scriptPath 'Jenkinsfile'
scm {
git {
remote { url 'https://github.com/cloud/my_other_pipleline_build.git'
credentials('github')
}
branch '*/my_pipleline_build'
extensions {}
}
triggers {
cron("H 12 * * 6")
}
}
}
}
}

Related

Trigger Jenkins Pipeline job on merge event for gitlab MR

this should be fairly basic, but when I research I come to things like gerrit triggrs and whatnot, which seem way too complicated for doing something simple like this.
I would like to do something like either this in the JobDSL script:
pipelineJob('deploy-game') {
definition {
environmentVariables {
env('ENVIRONMENT', "${ENVIRONMENT}")
keepBuildVariables(true)
}
cpsScm {
scm {
git{
remote {
url('https://blabla.git')
credentials('gitlab-credentials')
}
branches('${gitlabsourcebranch}')
}
}
scriptPath('path/to/this.jenkinsfile')
}
triggers {
gitlabPush {
buildOnMergeRequestEvents(true)
if ($gitlabMergeRequestState == 'merged') // this part
}
}
}
}
Or, trigger on all MR events, and then filter out in the pipeline script:
pipeline {
agent none
environment {
ENVIRONMENT = "${ENVIRONMENT}"
}
triggers {
$gitlabMergeRequestState == 'merged' // this one
}
stages {
stage ('do-stuff') {
agent {
label 'agent'
}
steps {
sh 'some commands ...'
}
}
}
}
How do I do this ?
So this is how it should be, I hope this is what you are looking for it.
pipelineJob('Job_Name') {
definition {
cpsScm {
lightweight(true)
triggers {
gitlabPush {
buildOnMergeRequestEvents(true) // it will trigger build when MR is opened.
buildOnPushEvents(true)
commentTrigger('retry a build') // When you write the comment on MR on gitlab. it will also trigger build
enableCiSkip(true)
rebuildOpenMergeRequest('source')
skipWorkInProgressMergeRequest(false)
targetBranchRegex('.*master.*|.*release.*') //This mean only push happened to master or release then only trigger jenkins build. Do not trigger build on normal feature branch push until the MR is opened.
}
}
configure {
it / triggers / 'com.dabsquared.gitlabjenkins.GitLabPushTrigger' << secretToken('ADD_TOKEN_FROM_JENKINS_JOB')
}
scm {
git {
remote {
credentials('ID')
url("git#URL.git")
branch("refs/heads/master")
}
}
}
scriptPath("jenkinsfile")
}
}
}

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

DSL Seed Job for Multibranch pipeline with Bitbucket branch plugin suppress auto build of branches

Have a DSL job to create multibranch pipeline jobs in jenkins, running Jenkins 2.107.1 with plugins: 'Branch API Plugin' 2.0.18, 'Bitbucket Branch Source Plugin' 2.2.10.
I'm unable to find a proper configuration function to enable property to "Suppress automatic SCM triggering", please help.
Here is my job that works but its just triggers the build as soon as it scans for branch:
multibranchPipelineJob("job") {
configure {
it / sources / data / 'jenkins.branch.BranchSource' / source(class: 'com.cloudbees.jenkins.plugins.bitbucket.BitbucketSCMSource') {
credentialsId('..')
id("..")
checkoutCredentialsId("..")
repoOwner("owner")
repository("my-repo")
includes()
excludes("PR-*")
}
}
}
This is how it works now... with the help of the following source code:
https://github.com/jenkinsci/bitbucket-branch-source-plugin
multibranchPipelineJob("job") {
branchSources {
branchSource {
source {
bitbucket {
credentialsId("myid")
repoOwner("iam")
repository("job")
traits {
headWildcardFilter {
includes("branchestoinclude")
excludes("toexclude")
}
}
}
}
strategy {
defaultBranchPropertyStrategy {
props {
// keep only the last 8 builds
buildRetentionBranchProperty {
buildDiscarder {
logRotator {
daysToKeepStr("-1")
numToKeepStr("8")
artifactDaysToKeepStr("-1")
artifactNumToKeepStr("-1")
}
}
}
}
}
}
}
}
// Branch behaviour
configure {
def traits = it / sources / data / 'jenkins.branch.BranchSource' / source / traits
traits << 'com.cloudbees.jenkins.plugins.bitbucket.BranchDiscoveryTrait' {
strategyId(3) // detect all branches -refer the plugin source code for various options
}
}
orphanedItemStrategy {
discardOldItems {
numToKeep(8)
}
}
}

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