GIT URL in Jenkins pipeline - jenkins

I am trying to parameterize a Jenkins pipeline. The only input parameter will be GITHUB_URL. I have a Jenkinsfile as a part of the repo. I want to use this variable (defined as parameter) in my pipeline configuration as "Repository URL". How can I access the parameter ?
I have tried $GITHUB_URL, ${GITHUB_URL} and ${params.GITHUB_URL}. No luck
Any other suggestions?

Because you are telling you have a jenkinsfile inside your git repo I suppose you do not mean that you want to call a Jenkinsfile using parameters from a shared library.
It's also not sure if you are using a declarative or scripted pipeline.
I will explain the "recommended" declarative pipeline:
pipeline {
agent any
parameters {
string(defaultValue: "https://github.com", description: 'Whats the github URL?', name: 'URL')
}
stages {
stage('Checkout Git repository') {
steps {
git branch: 'master', url: "${params.URL}"
}
}
stage('echo') {
steps {
echo "${params.URL}"
}
}
}
}
In this pipeline you will add a string parameter to which you can add a URL. When you run the build it will ask for the parameter:
To use this parameter use "${params.URL}":
This pipeline will clone the github repo in the first stage and print the URL in the next (echo) stage:
[Pipeline] // stage
[Pipeline] stage
[Pipeline] { (echo)
[Pipeline] echo
https://github.com/lvthillo/docker-ghost-mysql.git
[Pipeline] }

Related

How to pass down variables to credential parameters in JenkinsFiles?

I'm trying to write a JenkinsFile that automatically will reach to a git repo via ssh and perform some actions but I want to make the repo and ssh key use variables with the ssh id stored in Jenkins but I seem to be missing the Jenkins documentation for how to pass down variables to Jenkins Files as I'm not able to pass values down into the credentials key. The variables being passed down to the sh commands resolve perfectly fine though...
Example Pipeline Below:
pipeline {
parameters {
string(name: 'SSH_priv', defaultValue: 'd4f19e34-7828-4215-8304-a2d1f87a2fba', description: 'SSH Credential with the private key added to Jenkins and the public key to the username stored in Git Server, this id can be found in the credential section of Jenkins post its creation.')
string(name: 'REPO', defaultValue: 'git#--------------------')
}
stages {
stage ('Output Variables'){
// checks I can get these variables
steps{
sh("echo ${params.SSH_priv}")
sh("echo ${params.REPO}")
}
}
stage('Do Something') {
steps {
// this below commented line, does not work.
// sshagent (credentials: ['${params.SSH_priv}']){
// this line does work
sshagent (credentials: ['d4f19e34-7828-4215-8304-a2d1f87a2fba']){
sh("git clone --mirror ${params.REPO} temp")
dir("temp"){
// start doing fancy stuff ...
....
....
}
}
}
}
The aim is a Pipeline that my fellow developers could call and will work with their own repos and own ssh id's that I'm not using. When I try to run this with the SSH_priv parameter passing down the value I get the below failure in Jenkins.
The JenkinsFile works perfectly fine with the credential id hard-coded- as shown below:
So after testing different things a friend solved this in sub 5 minutes. Quotation mark types matter in Groovy Script
Changing
sshagent (credentials: ['${params.SSH_lower}']){
To
sshagent (credentials: ["${params.SSH_lower}"]){
Solved the issue.
Better to use environment step in pipeline.
pipeline {
agent any
environment {
AN_ACCESS_KEY = credentials('an_access_key_id')
}
stages {
stage('Example') {
steps {
sh 'printenv'
}
}
}
}
And credentials should exist in jenkins with id an_access_key_id
Take a look at official documentation here

Trouble reading Secrets from Jenkins Credential Manager in Multi Branch Pipeline job using Credential Parameter

I have a Jenkins multi branch pipeline job that uses a secret value in Jenkinsfile:
pipeline {
agent any
stages {
stage('Test') {
steps {
echo "DOCKER_REGISTRY_USER is ${env.DOCKER_REGISTRY_USER_NSV}"
}
}
}
}
The secret value is stored in Credentials Manager as secret text with the ID DOCKER_REGISTRY_USER_NSV:
I'm trying to read this value in Jenkinsfile as shown above but I get the following output that prints out the value null for my secret:
[Pipeline] }
[Pipeline] // stage
[Pipeline] withEnv
[Pipeline] {
[Pipeline] stage
[Pipeline] { (Test)
[Pipeline] echo
DOCKER_REGISTRY_USER is null
[Pipeline] sh
I also tried referencing the secret text in my pipeline like this:
echo "DOCKER_REGISTRY_USER is ${DOCKER_REGISTRY_USER_NSV}"
But then I get this error when running the Jenkins job:
groovy.lang.MissingPropertyException: No such property: DOCKER_REGISTRY_USER_NSV for class: groovy.lang.Binding
at groovy.lang.Binding.getVariable(Binding.java:63)
at org.jenkinsci.plugins.scriptsecurity.sandbox.groovy.SandboxInterceptor.onGetProperty(SandboxInterceptor.java:264)
I think I need to bind that credential to the job but I don't see an option to do that for a Multi-Branch Pipeline job, the way you can for a Freestyle or Pipeline job.
How can I use a secret credential in a Multi Branch Pipeline job?
You can use credentials() helper method to archive your purpose.
pipeline {
agent any
environment {
DOCKER_REGISTRY_USER = credentials('DOCKER_REGISTRY_USER_NSV')
// put the ID of credential as credentials()'s parameter.
}
stages {
stage('Test') {
steps {
echo "DOCKER_REGISTRY_USER is ${DOCKER_REGISTRY_USER}"
}
}
}
}

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*' }

How to build docker images using a Declarative Jenkinsfile

I'm new to using Jenkins....
I'm trying to automate the production of an image (to be stashed in a repo) using a declarative Jenkinsfile. I find the documentation to be confusing (at best). Simply put, how can I convert the following scripted example (from the docs)
node {
checkout scm
def customImage = docker.build("my-image:${env.BUILD_ID}")
customImage.push()
}
to a declarative Jenkinsfile....
You can use scripted pipeline blocks in a declarative pipeline as a workaround
pipeline {
agent any
stages {
stage('Build image') {
steps {
echo 'Starting to build docker image'
script {
def customImage = docker.build("my-image:${env.BUILD_ID}")
customImage.push()
}
}
}
}
}
I'm using following approach:
steps {
withDockerRegistry([ credentialsId: "<CREDENTIALS_ID>", url: "<PRIVATE_REGISTRY_URL>" ]) {
// following commands will be executed within logged docker registry
sh 'docker push <image>'
}
}
Where:
CREDENTIALS_ID stands for key in Jenkis under which you store credentials to your docker registry.
PRIVATE_REGISTRY_URL stands for url of your private docker registry. If you are using docker hub then it should be empty.
I cannot recommend the declarative syntax for building a Docker image bcos it seems that every important step requires falling back to the old scripting syntax. But if you must, a hybrid approach seems to work.
First a detail about the scm step: when I defined the Jenkins "Pipeline script from SCM" project that fetches my Jenkinsfile with a declarative pipline from git, Jenkins cloned the repo as the first step in the pipeline even tho I did not define a scm step.
For the build and push steps, I can only find solutions that are a hybrid of old-style scripted pipeline steps inside the new-style declarative syntax. For example see gustavoapolinario's work at Medium:
https://medium.com/#gustavo.guss/jenkins-building-docker-image-and-sending-to-registry-64b84ea45ee9
which has this hybrid pipeline definition:
pipeline {
environment {
registry = "gustavoapolinario/docker-test"
registryCredential = 'dockerhub'
dockerImage = ''
}
agent any
stages {
stage('Cloning Git') {
steps {
git 'https://github.com/gustavoapolinario/microservices-node-example-todo-frontend.git'
}
}
stage('Building image') {
steps{
script {
dockerImage = docker.build registry + ":$BUILD_NUMBER"
}
}
}
stage('Deploy Image') {
steps{
script {
docker.withRegistry( '', registryCredential ) {
dockerImage.push()
}
}
}
}
stage('Remove Unused docker image') {
steps{
sh "docker rmi $registry:$BUILD_NUMBER"
}
}
}
}
Because the first step here is a clone, I think he built this example as a standalone pipeline project in Jenkins (not a Pipeline script from SCM project).

Create new Jenkins jobs using Pipeline Job and Groovy script

I have Jenkins pipeline Job with parameters (name, group, taskNumber)
I need to write pipeline script which will call groovy script (this one?: https://github.com/peterjenkins1/jenkins-scripts/blob/master/add-job.groovy)
I want to create new job (with name name_group_taskNamber) every times when I build main Pipeline Job.
I don't understand:
Where do I need to put may groovy script ?
How does Pipeline script should look like? :
node{
stage('Build'){
def pipeline = load "CreateJob.groovy"
pipeline.run()
}
}
You can use and configure a shared library like here (a git repo): https://github.com/lvthillo/shared-library . You need to configure this in your Jenkins global configuration.
It contains a folder vars/. Here you can manage pipelines and groovy scripts like my slackNotifier.groovy. The script is just a groovy script to print the build result in Slack.
In the jenkins pipeline job we will import our shared library:
#Library('name-of-shared-pipeline-library')_
mavenPipeline {
//define parameters
}
In the case above also the pipeline is in the shared library but this isn't necessary.
You can just write your pipeline in the job itself and call only the function from the pipeline like this:
This is the script in the shared library:
// vars/sayHello.groovy
def call(String name = 'human') {
echo "Hello, ${name}."
}
And in your pipeline:
final Lib= library('my-shared-library')
...
stage('stage name'){
echo "output"
Lib.sayHello.groovy('Peter')
}
...
EDIT:
In new declarative pipelines you can use:
pipeline {
agent { node { label 'xxx' } }
options {
buildDiscarder(logRotator(numToKeepStr: '3', artifactNumToKeepStr: '1'))
}
stages {
stage('test') {
steps {
sh 'echo "execute say hello script:"'
sayHello("Peter")
}
}
}
post {
always {
cleanWs()
}
}
}
def sayHello(String name = 'human') {
echo "Hello, ${name}."
}
output:
[test] Running shell script
+ echo 'execute say hello script:'
execute say hello script:
[Pipeline] echo
Hello, Peter.
[Pipeline] }
[Pipeline] // stage
We do it by using the https://wiki.jenkins.io/display/JENKINS/Jobcopy+Builder+plugin, try build another step in pipeline script and pass the parms which are to be considered

Resources