How to use groovy constant from Shared Libray in Jenkins file (pipeline)? - jenkins

I want use grrovy constant from Shared Libray in my Jenkins pipeline. I try this but I have this error:
org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed: WorkflowScript: 27: Not a valid stage section definition: "def paramChecker = ParameterChecker.new(this)". Some extra configuration is required. # line 27, column 9. stage('Checkout') {
def libIdentifier = "project-jenkins-pipeline"
def libGitBranch = params.LIB_GIT_BRANCH
if(libGitBranch) {
libIdentifier += "#${libGitBranch}"
}
def com = library(identifier: libIdentifier, changelog: false).com
def Constants = com.project.Constants
def ParameterChecker = com.project.ParameterChecker
pipeline {
agent {
docker {
label "linux"
image "my-host:8082/project-build-java:jdk1.6-jdk1.8-mvn3.2.5"
registryUrl 'http://my-host:8082'
registryCredentialsId 'ReadNexusAccountService'
}
}
stages {
stage('Clean workspace') {
steps {
deleteDir()
}
}
stage('Checkout') {
def paramChecker = ParameterChecker.new(this)
paramChecker.checkProjectAndBranchNames()
checkoutGitSCM(
url: "${Constants.BITBUCKET_URL}/${paramChecker.projectName}.git",
tag: Constants.GIT_PROJECT_DEFAULT_BRANCH
)
}
stage('Compilation Maven') {
steps {
timestamps {
sh 'mvn -version'
}
}
}
}
}

I had script in steps in stage('Checkout')
def libIdentifier = "project-jenkins-pipeline"
def libGitBranch = params.LIB_GIT_BRANCH
if(libGitBranch) {
libIdentifier += "#${libGitBranch}"
}
def com = library(identifier: libIdentifier, changelog: false).com
pipeline {
agent {
docker {
label "linux"
image "my-host:8082/project-build-java:jdk1.6-jdk1.8-mvn3.2.5"
registryUrl 'http://my-host:8082'
registryCredentialsId 'ReadNexusAccountService'
}
}
stages {
stage('Clean workspace') {
steps {
deleteDir()
}
}
stage('Checkout') {
steps {
script {
def Constants = com.project.Constants
def ParameterChecker = com.project.ParameterChecker
def paramChecker = ParameterChecker.new(this)
paramChecker.checkProjectAndBranchNames()
checkoutGitSCM(
url: "${Constants.BITBUCKET_URL}/${paramChecker.projectName}.git",
tag: Constants.GIT_PROJECT_DEFAULT_BRANCH
)
}
}
}
stage('Compilation Maven') {
steps {
timestamps {
sh 'mvn -version'
}
}
}
}
}
Thanks at #Matt Schuchard and Jenkins: Cannot define variable in pipeline stage

Related

Jenkins pipeline execute job and get status

pipeline {
agent { label 'master' }
stages {
stage('test') {
steps {
script {
def job_exec_details = build job: 'build_job'
if (job_exec_details.status == 'Failed') {
echo "JOB FAILED"
}
}
}
}
}
}
I have a pipeline that executing build job, how can I get Job result in jenkins pipeline ?
It should be getResult() and status should be FAILURE not Failed.
so your whole code should be like this
pipeline {
agent { label 'master' }
stages {
stage('test') {
steps {
script {
def job_exec_details = build job: 'build_job', propagate: false, wait: true // Here wait: true means current running job will wait for build_job to finish.
if (job_exec_details.getResult() == 'FAILURE') {
echo "JOB FAILED"
}
}
}
}
}
}
Where is a second way of getting results:
pipeline {
agent { label 'master' }
stages {
stage('test') {
steps {
build(job: 'build_job', propagate: true, wait: true)
}
}
}
post {
success {
echo 'Job result is success'
}
failure {
echo 'Job result is failure'
}
}
}
}
You can read more about 'build' step here

jenkins pipeline updateGitlabCommitStatus not working

GITLAB_VERSION: GitLab Enterprise Edition 13.9.3-ee
JENKINS_VERSION: 2.263.4
I have crated a jenkins pipeline which is being triggered by change in gitlab, but its not updating gitlab status.
pipeline {
agent any
stages {
stage('cloning from gitlab'){
steps{
git credentialsId: '7d13ef14-ee65-497b-8fba-7519f5012e81', url: 'git#git.MYDOMAIN.com:root/popoq.git'
}
}
stage('build') {
steps {
echo 'Notify GitLab'
updateGitlabCommitStatus name: 'Jenkins-build', state: 'pending'
echo 'build step goes here'
}
}
stage('echoing') {
steps{
echo "bla blaa bla"
}
}
stage(test) {
steps {
echo 'Notify GitLab'
echo 'test step goes here'
updateGitlabCommitStatus name: 'Jenkins-build', state: 'success'
}
}
}
}
its not showing any pipline in gitlab, any suggestions?
I think you miss a "gitlabBuilds" command in an "option" block declaring the steps you will have in your build.
options {
gitLabConnection('xxx-gitlab')
gitlabBuilds(builds: ['step1', 'step2', 'step3'])
}
Then you can reference those steps with the "updateGitlabCommitStatus" but you'd better use the "gitlabCommitStatus" command like this:
pipeline {
agent any
options {
gitLabConnection('xxx-gitlab')
gitlabBuilds(builds: ['step1', 'step2', 'step3'])
}
stages {
stage('step1'){
steps{
gitlabCommitStatus(name:'step1') {
git credentialsId: '7d13ef14-e', url: 'xxxxxxx'
}
} // end steps
} // end stage
stage('step2'){
steps{
gitlabCommitStatus(name:'step2') {
.......
}
} // end steps
} // end stage
}
pipeline {
agent {
label 'agent_gradle'
}
options {
gitLabConnection('Gitlab Jenkins integration API connection test')
gitlabBuilds(builds: ['step1', 'step2'])
}
stages {
stage('Build') {
steps {
gitlabCommitStatus(name: 'step1') {
container(name: 'gradle') {
echo 'Building the application...'
}
}
}
}
stage('Test') {
steps {
gitlabCommitStatus(name: 'step2') {
container(name: 'gradle') {
echo 'Testing the application...'
}
}
}
}
}
}

create dsl job inside a job

When I run the job I should create a freestyle job with a parameter name and repo.
I already try this but it doesn't work.
freeStyleJob('seed') {
parameters {
stringParam("GITHUB_REPO_NAME", "", "repo_name")
stringParam("JOB_NAME", "", "name for the job")
}
steps {
dsl {
job('\$DISPLAY_NAME') {
}
}
}
}
You can create a job inside a job by using 'text': https://jenkinsci.github.io/job-dsl-plugin/#path/freeStyleJob-steps-dsl-text
steps {
dsl {
text('job ("name") {}')
}
}
Here is the script that will help you out. It will create a Freestyle Job named example with Build Parameters JOB_NAME and GITLAB_REPOSITORY_URL. This job will have Job DSL Scripts.
freeStyleJob('example') {
logRotator(-1, 10)
parameters{
stringParam('JOB_NAME', '', 'Set the Gitlab repository URL')
stringParam('GITLAB_REPOSITORY_URL', '', 'Set the Gitlab repository URL')
}
steps {
dsl {
external('**/project.groovy')
}
}
}
In project.groovy, I have written my DSL scripts.
project.groovy
import hudson.model.*
def thr = Thread.currentThread()
def build = thr?.executable
def jobname_param = "JOB_NAME"
def resolver = build.buildVariableResolver
def jobname = 'TEST/'+ resolver.resolve(jobname_param)
println "found jobname: '${jobname}'"
def project_url_param = "GITLAB_REPOSITORY_URL"
def resolver2 = build.buildVariableResolver
def project_url = resolver2.resolve(project_url_param)
println "found project_url: '${project_url}'"
def repoUrl = "https://example.com/gitlab/repoA/jenkinsfile-repo.git"
pipelineJob(jobname) {
parameters {
stringParam('GITLAB_REPOSITORY_URL', '', 'Set the Gitlab repository URL')
}
logRotator {
numToKeep(5)
daysToKeep(5)
}
definition {
cpsScm {
scm {
git {
remote {
url(repoUrl)
credentials('gitlab-test')
}
branches('master')
extensions {
cleanBeforeCheckout()
}
}
}
scriptPath("Jenkinsfile")
}
}
}
For more reference:
https://jenkinsci.github.io/job-dsl-plugin/#method/javaposse.jobdsl.dsl.DslFactory.freeStyleJob
https://jenkinsci.github.io/job-dsl-plugin/#method/javaposse.jobdsl.dsl.helpers.step.StepContext.dsl

How can I use post step in Jenkins pipeline with kubernetes plugin

I try to use the post steps with the Jenkins kubernetes plugin. Does anyone has an idea?
java.lang.NoSuchMethodError: No such DSL method 'post' found among steps
My pipeline:
podTemplate(
label: 'jenkins-pipeline',
cloud: 'minikube',
volumes: [
hostPathVolume(mountPath: '/var/run/docker.sock', hostPath: '/var/run/docker.sock'),
]) {
node('jenkins-pipeline') {
stage('test') {
container('maven') {
println 'do some testing stuff'
}
}
post {
always {
println "test"
}
}
}
}
As of this writing, Post is only supported in declarative pipelines.
You could have a look at their declarative example if you absolutely must use post.
pipeline {
agent {
kubernetes {
//cloud 'kubernetes'
label 'mypod'
containerTemplate {
name 'maven'
image 'maven:3.3.9-jdk-8-alpine'
ttyEnabled true
command 'cat'
}
}
}
stages {
stage('Run maven') {
steps {
container('maven') {
sh 'mvn -version'
}
}
}
}
}
This example shows how to use the post step using the Kubernetes plugin:
pipeline {
agent {
kubernetes {
label "my-test-pipeline-${BUILD_NUMBER}"
containerTemplate {
name "my-container"
image "alpine:3.15.0"
command "sleep"
args "99d"
}
}
}
stages {
stage('Stage 1') {
steps {
container('my-container') {
sh '''
set -e
echo "Hello world!"
sleep 10
echo "I waited"
echo "forcing a fail"
exit 1
'''
}
}
}
}
post {
unsuccessful {
container('my-container') {
sh '''
set +e
echo "Cleaning up stuff here"
'''
}
}
}
}

Jenkins shared library - how to define common options for a declarative pipeline

I have many similar configs in declarative pipelines, like agent, tools, options, or post section. Is there any option to define those option somehow, so that an individual job has only to define the steps (which may come from a shared library)?
There is a description at "Defining a more stuctured DSL", where there is something similar to that what I want to achieve, but this seems to apply to scripted pipelines.
pipeline {
agent {
label 'somelabel'
}
tools {
jdk 'somejdk'
maven 'somemaven'
}
options {
timeout(time: 2, unit: 'HOURS')
}
stages {
stage('do something') {
steps {
doSomething()
}
}
}
post {
failure {
emailext body: '${DEFAULT_CONTENT}', subject: '${DEFAULT_SUBJECT}',
to: 'some#mail.com', recipientProviders: [[$class: 'CulpritsRecipientProvider'], [$class: 'RequesterRecipientProvider'], [$class: 'DevelopersRecipientProvider']]
}
}
}
Actually, I tried something like that, trying to pass a closure to the pipeline, but this does not seem to work. Probably if it worked, there was some documentation on how to do it.
def call(stageClosure) {
pipeline {
agent {
label 'somelabel'
}
tools {
jdk 'somejdk'
maven 'somemaven'
}
options {
timeout(time: 2, unit: 'HOURS')
}
stages {
stageClosure()
}
post {
failure {
emailext body: '${DEFAULT_CONTENT}', subject: '${DEFAULT_SUBJECT}',
to: 'some#mail.com', recipientProviders: [[$class: 'CulpritsRecipientProvider'], [$class: 'RequesterRecipientProvider'], [$class: 'DevelopersRecipientProvider']]
}
}
}
}
and calling it somehow like this:
library 'my-library#master'
callJob{
stage('do something') {
steps {
doSomething()
}
}
}
I created a full flow
//SbtFlowDockerLarge.groovy
def call(int buildTimeout,String sbtVersion,List<String> fbGoals, List<String> masterGoals ){
def fbSbtGoals = fbGoals.join ' '
def masterSbtGoals = masterGoals.join ' '
pipeline {
agent { label DPgetLabelDockerLarge() }
options {
timestamps()
timeout(time: buildTimeout, unit: 'MINUTES')
disableConcurrentBuilds()
buildDiscarder(logRotator(daysToKeepStr: '35'))
}
stages {
stage('Prepare') {
steps {
setGitHubBuildStatus("Running Build", "PENDING")
echo "featureTask : ${fbSbtGoals}"
echo "masterTask : ${masterSbtGoals}"
}
}
stage('Build') {
when {
not { branch 'master' }
}
steps {
sbtTask tasks: "${fbSbtGoals}", sbtVersion: sbtVersion
}
}
stage('Deploy') {
when {
branch 'master'
}
environment {
TARGET_ENVIRONMENT='prod'
}
steps {
sbtTask tasks: "${masterSbtGoals}", sbtVersion: sbtVersion
}
}
}
post {
success {
setGitHubBuildStatus("Build complete", "SUCCESS")
}
failure {
setGitHubBuildStatus("Build complete", "FAILED")
}
always {
junit allowEmptyResults: true, testResults: '**/target/test-reports/*.xml'
dockerCleanup()
}
}
}
}
and here is the Jenkinsfile
#Library('aol-on-jenkins-lib') _
def buildTimeout = 60
def sbtVersion = 'sbt-0.13.11'
OathSbtFlowDockerLarge (buildTimeout, sbtVersion,['clean test-all'],['clean test-all publish'])

Resources