Webhook| Gitlab | jenkins pipeline |Declarative syntax - jenkins

I'm trying to integrate Webhook with gitlab and jenkins. I have done it via upstream downstream jobs using the URL.
While trying to rece=reate the same via declarative pipeline, I'm in a stanstill
pipeline {
agent any
stages {
stage('fetchcodeFromGit') {
steps {
timeout(time: 30) {
git(url: 'http:<<>>/JenkinsPipeline.git', branch: 'master', credentialsId: 'QualityAssurance', poll: true)
}
}
}
Can anyone help with documents or any sample snippets?

If you choose pipeline script instead declarative pipeline, this post could be help you :
https://jrichardsz.github.io/devops/devops-with-git-and-jenkins-using-webhooks
Steps:
Configure required plugins in jenkins.
Jenkins user and password.
Create a jenkins job which will be triggered by your git provider. This job publish an http url ready to use. We will call webhook_url to this url.
Configure webhook_url in webhook section of your git provider of some repository.
Test this flow, pushing some change to your git repository or simulating it using comandline.

You can use this snippet:
pipeline {
options {
gitLabConnection('your-gitlab-conn')
}
triggers {
gitlab(
triggerOnPush: false,
triggerOnMergeRequest: true, triggerOpenMergeRequestOnPush: "both",
triggerOnNoteRequest: true,
noteRegex: "Jenkins please retry a build",
skipWorkInProgressMergeRequest: false,
ciSkip: false,
setBuildDescription: true,
addNoteOnMergeRequest: true,
addCiMessage: true,
addVoteOnMergeRequest: true,
acceptMergeRequestOnSuccess: false,
branchFilterType: "All",
secretToken: "NOTVERYSECRET")
}
stages {
...
more details here: https://github.com/jenkinsci/gitlab-plugin

Related

#jenkins_Unable to get subversion checkout using jenkins in Pipline build

i have created a jenkins pipe line build where using below pipline code when i try to build a error appears stating "Checking out http://192.160.142.39/Mobility/branches/AppiumTesting/test.automation at revision '2023-02-20T12:07:18.262 +0530'
Using sole credentials in realm ‘http://192.160.142.39:80 VisualSVN Server’
ERROR: Subversion checkout has been canceled"
i have tried suggestions mentioned in many threads as well , but not able to fix this issue . could you please suggest the issue :-
PipeLine COde:-
pipeline {
agent any
stages {
stage('Checkout') {
steps {
script {
def svnUrl = 'http://192.160.142.39/Mobility/branches/AppiumTesting/test.automation'
def svnCredsId = 'APatil' // ID of the SVN credentials in Jenkins
def workspace = pwd() // current working directory
// Checkout source code from SVN repository
svn url: svnUrl,
credentialsId: svnCredsId,
revision: 'HEAD',
depthOption: 'infinity',
ignoreExternals: true,
changelog: false,
workspaceUpdater: [$class: 'CheckoutUpdater'],
poll: false,
quiet: true,
workspaceUpdaterArguments: [location: workspace]
}
}
}
stage('Build and Package') {
steps {
// Build and package the code into a JAR file
withMaven(maven: 'maven-3.8.2') {
sh 'mvn clean package'
}
}
}
stage('Deploy to Nexus') {
steps {
// Deploy the JAR file to a Nexus repository
nexusPublisher nexusInstanceId: 'nexus',
nexusRepositoryId: 'maven-snapshots',
packages: [[$class: 'MavenPackage', mavenCoords: 'test.automation:core:1.0-SNAPSHOT',
file: 'target/core-1.0.jar']]
}
}
}
}

How to trigger a build on commit to branch in scripted pipeline

triggers { pollSCM('H */4 * * 1-5') } will this work for merge to branch
I see we have 3 options for triggers this seems to be fo declarative
corn
pollScm
upstream
where in for scripted pipeline is that something like this
properties([pipelineTrigger([triggers('gitPush')])])
OR
properties([pipelineTriggers([githubPush()])])// With this should I also enable a option on Jenkins instance
You can also use Generic Webhook Trigger plugin.
You will need to create a webhook in github and in Jenkins Pipeline something like below.
triggers {
GenericTrigger( genericVariables: [
[defaultValue: '', key: 'commit_author', regexpFilter: '', value: '$.pusher.name'],
[defaultValue: '', key: 'ref', regexpFilter: '', value: '$.ref']
],
causeString: '$commit_author committed to $ref',
printContributedVariables: false,
printPostContent: false,
regexpFilterText: '$ref',
regexpFilterExpression: 'refs/heads/develop',
token: '12345'
}
Hope this helps.
Use something like this in you Jenkinsfile. Use Only those option which you need. Remove which you don't want.
pipeline {
agent any
triggers {
github(
triggerOnPush: true,
triggerOnMergeRequest: true,
triggerOpenMergeRequestOnPush: "source",
branchFilterType: "All",
triggerOnNoteRequest: false)
}
stages {
...
}
}
NOTE: Make sure you have done all the webhook configuration bewteen github and jenkins. and installed webhook plaugin on jenkins

Trigger builds remotely (e.g., from scripts) syntax in Jenkinsfile

I am using this option in my freestyle jobs but now my team is moving to make a standard format so I have to write all my freestyle jobs in Pipeline script and I google a lot but didn't get how could I write this option in the Pipeline script.
You can trigger remote Jenkins jobs using triggerRemoteJob pipeline step.
Documentation: https://jenkins.io/doc/pipeline/steps/Parameterized-Remote-Trigger/
And here is a short example that illustrates how to use this step with authentication. I used Jenkins User Token for authentication - the token and user name was stored in the Jenkins credentials with id xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx (obfuscated id ofc). The remote job in the below example is triggered with a single parameter foo == qwe123, and it is configured to wait until the remote job gets completed, and if it fails, the job that triggered the remote job fails as well.
pipeline {
agent any
stages {
stage("Execute remote job") {
steps {
script {
def jobUrl = "https://remote-jenkins-host/job/remote-job-to-trigger/"
withCredentials([[$class: 'UsernamePasswordMultiBinding', credentialsId: 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx', usernameVariable: 'USERNAME', passwordVariable: 'TOKEN']]) {
def handle = triggerRemoteJob job: jobUrl,
blockBuildUntilComplete: true,
shouldNotFailBuild: true,
parameters: "foo=qwe123",
auth: TokenAuth(apiToken: env.TOKEN, userName: env.USERNAME)
echo "Remote tests status: ${handle.buildStatus.toString()}"
}
}
}
}
}
}
Hope it helps.

Trigger pipeline after a push on bitbucket server

I'm creating this new Job based on pipeline on jenkins. I want my jenkinsfile to be on bitbucket reposiotry : Let's say my config file is on bitbucket.org/config.git
The job mission is to clean install a project bitbucket.org/myProject.git
How can I configure the pipeline so it will trigger if any push is made in bitbucket.org/myProject.git and following the steps defined in bitbucket.org/config.git?
I do not want to create multi-branch pipeline and I do not want my jenkins file to be on the same repository than my project to compile.
My current config is:
pipeline {
agent any
parameters {
string(defaultValue: '', description: 'URL', name: 'GIT_URL')
string(defaultValue: '', description: 'Credential', name: 'CREDENTIAL_ID')
}
stages {
stage ('Initialize') {
steps {
git branch: 'develop', credentialsId: "${params.CREDENTIAL_ID}", url: "${params.GIT_URL}"
}
}
stage ('Build') {
steps {
sh 'mvn clean install '
echo 'build'
}
}
}
You can use shared Libraries in Jenkins. you would still need a Jenkinsfile in your code, but that would not contain any logic. It would simply refer the shared library and pass any params like git repo path.
For more information on shared libraries please refer this link https://jenkins.io/doc/book/pipeline/shared-libraries/.
For triggering the build, you can define a trigger in your pipeline. Example :
triggers {
pollSCM('H/5 * * * *')
}
or use webhooks if you don't want to poll.
Actually, i managed to make it work.
In my jenkins pipeline, i activated "Build when a change is pushed to BitBucket".
node {
checkout([$class: 'GitSCM',
branches: [[name: 'feature/test-b']],
doGenerateSubmoduleConfigurations: false,
extensions: [[$class: 'SubmoduleOption', disableSubmodules: false,
parentCredentials: false, recursiveSubmodules: true, reference: '',
trackingSubmodules: false]], submoduleCfg: [],
userRemoteConfigs: [[credentialsId: 'admin',
url: 'http://localhost:7990/scm/bout/boutique-a.git']]])
}
When a change is made in boutique-a in the branch 'feature/test-b' my job is triggered which is cool.
Now i have this other issue, how can i trigger when change are made in feature/*
It looks like i cannot access to env.BRANCH_NAME when im not in a multibranch pipeline

Jenkins pipeline job start by hook by release

I have a Bitbucked repo, and I want to satrt my Jenkins pipeline job only afrer commit with tag like "release-1.0.*"
So, I seted my job up with pipeline script:
pipeline {
agent any
stages {
stage ('Prepare') {
when {
tag "release*"
}
steps {
git branch: 'tag1', url: 'git#bitbucket.org:m*********ny/tests.git'
}
}
stage ('Deploy') {
steps {
sshPublisher(publishers: [sshPublisherDesc(configName: "JenkinsSrv", transfers: [sshTransfer(execCommand: 'pwd')])])
}
}
}
post ('POST BUILD'){
always {
echo 'This is post action!!!'
}
}
}
Also, I turned on Bitbucked webhook plugin, than my repo notify Jenkins about new changes.
But my solution doesn't work. Help me resolve this case.
enter image description here
According to the official documentation for a Jenkins pipeline, the option you are looking for is the changelog condition inside the when directive. For example:
when { changelog 'release*' }

Resources