Split jenkins variable and trigger multiple jobs - jenkins

I need to clean up some Kubernete namespaces(hello_namespace, second,my_namespace1, my_namespace45,my_namespace44 for example and I do it with a jenkins job.
I read with kubectl the namespace I need to clean up and then I want to fire a job to delete it, My code should be something like that
pipeline {
agent { label 'master' }
stages {
stage('Clean e2e') {
steps {
script {
sh "kubectl get namespace |egrep 'my_namespace[0-9]+'|cut -f1 -d ' '>result.txt"
def output=readFile('result.txt').trim()
}
}
}
The ouput of this code will be the variable $output with the values:
my_namespace1
my_namespace45
my_namespace44
Separated by line, now I want to fire a job with the namespace like parameter , how can I do that? (My problem is to read the file and fire independent job for each namespace)
while (output.nextLine() callJob)
The job call should be like
build job: 'Delete temp Stage', parameters:
[string(name: 'Stage', value: "${env.stage_name}")]

I already got it :)
#!groovy
pipeline {
agent { label 'master' }
stages {
stage('Clean up stages') {
steps {
script {
sh '(kubectl get namespace |egrep "namespace[0-9]+"|cut -f1 -d " "|while read i;do echo -n $i";" ; done;)>result.txt'
def stages = readFile('result.txt').trim().split(';')
for (stage in stages) {
if (stage?.trim()) {
echo "deleting stage: $stage"
build job: 'Delete temp Stage', parameters:
[string(name: 'Stage', value: "$stage")]
}
}
}
}
}
}
}

Related

Re-run a pipeline using script jenkins

I have a pipeline with some information detailed behind
pipeline {
parameters {
booleanParam(name: 'RERUN', defaultValue: false, description: 'Run Failed Tests')
}
stage('Run tests ') {
steps {
runTest()
}
}
post {
always {
reRun()
}
}
}
def reRun() {
if ("SUCCESS".equals(currentBuild.result)) {
echo "LAST BUILD WAS SUCCESS"
} else if ("UNSTABLE".equals(currentBuild.result)) {
echo "LAST BUILD WAS UNSTABLE"
}
}
but I want that after the stage "Run tests" execute, if some tests fail I want to re-run the pipeline with parameters RERUN true instead of false. How can I replay via script instead of using plugins ?
I wasn't able to find how to re-run using parameters on my search, if someone could help me I will be grateful.
First of you can use the post step to determine if the job was unstable:
post{
unstable{
echo "..."
}
}
Then you could just trigger the same job with the new parameter like this:
build job: 'your-project-name', parameters: [[$class: 'BooleanParameterValue', name: 'RERUN', value: Boolean.valueOf("true")]]

How to build pipeline job inside the POST section in Jenkins pipeline

I have a Jenkins pipeline which, among multiple steps should have a final step that should be executed regardless of the status of previous steps. For that to happen, I've tried using post section which looks like this:
pipeline {
agent {
label 'master'
}
stages {
stage('Stage 1') {
steps {
build job: 'stage 1 job', parameters: [
...
]
}
}
stage('Stage 2') {
steps {
build job: 'stage 2 job', parameters: [
...
]
}
}
}
post {
always {
build job: "cleanup", parameters: [
...
]
}
}
}
However, I'm getting following error when trying to execute something like this:
No such DSL method '$' found among steps
Question: Is it even possible to use build job inside post action? If not, what would be good alternative to achieve that "cleanup" job is always executed at the end (regardless of the status of stages above)
Yes, it is possible to use build a job inside post action. Here is the pipeline script:
pipeline {
agent any
stages {
stage('1') {
steps {
script {
echo "Hello"
}
}
}
}
post {
always {
build job: 'schedule-job', parameters: [string(name: 'PLATFORM', value: 'Windows')]
}
}
}
In the above example, I have schedule-job which accepts parameters PLATFORM and it will Always run, regardless of build status
Here is the output:

Pass variable from jenkins pipeline job to other pipeline job

Pass variable from jenkins pipeline job to other pipeline job:
I have a following job:
stage ('Upgrade') {
steps {
build job: 'Upgrade',
parameters: [string(name: 'sourcePath', value: '%publishPath%"\"%folderBuild%')]
}
}
Call to other job
pipeline {
agent { label 'master' }
stages {
stage('Upgrade') {
steps {
sh "ansible-playbook -i inventory playbook.yml --extra-vars "name=build_path value=%sourcePath%"
}
}
}
}
Question: what's wrong?
stage ('Upgrade') {
steps {
build job: 'Upgrade', parameters: [string(name: 'sourcePath', value: env.buildPath)]
}
}
In following this job you have to define String parameter called SourcePath
stages {
stage('Upgrade') {
steps {
sh label: '', script: 'ansible-playbook -i inventory upgrade.yml -e "buildPath=${sourcePath}"'
}
}
}
In Ansible create env var as following:
vars:
build_path: "{{ buildPath }}" // buildPath from Jenkins job

Using Jenkins job parameter in a bat command

I'm trying to configure a parameter in Jenkins pipeline and then execute it within bat command:
pipeline {
agent {
label 'master'
}
parameters {
string (
defaultValue: '"someExe.exe"',
description: '',
name : 'varExe'
)
}
stages {
stage("hi") {
steps {
script {
bat '${params.varExe}'
}
}
}
}
}
Unfortunately, i'm getting this error:
'${varExe}'is not recognized as an internal or external command
For some reason, Jenkins doesn't use varExe value.
I've also tried bat '${varExe}' but still no luck.
Any ideas ?
You need to use a double quote here to replace the variable.
bat "${params.varExe}"
You have to be careful with single and double quotes. For the following example, the first one would echo someExe.exe, while the second one would throw a Bad substitution error.
pipeline {
agent any
parameters {
string (
defaultValue: '"someExe.exe"',
description: '',
name : 'varExe')
}
stages {
stage ('Test') {
steps {
script {
sh "echo '${params.varExe}'"
sh 'echo "${params.varExe}"'
}
}
}
}
}
I think for bat command should be like below
bat ''' echo %varExe% '''
reference : pass parameter from jenkins parameterized build to windows batch command

Declarative Jenkins Pipeline; How to declare a variable and use it in script or mail notification?

(update below)
I have a declarative pipeline job which can take an argument VERSION.
pipeline {
parameters {
string(name: VERSION, defaultValue: '')
}
// ...
}
If no VERSION is given, like when Gitlab send a hook to this job, I want to compute it from git, so I do something like this
stages {
stage('Prepare') {
steps {
// ...
if (! env.VERSION) {
VERSION = sh(script: "git describe", returnStdout: true).trim()
}
}
}
}
Now I want to "inject" this variable to
my build script. It needs to find "VERSION" in the environment variables
to the jenkins mail notificator. And get it to retreive ${VERSION} in subject or body text
I tried changing above code with
stages {
stage('Prepare') {
steps {
// ...
if (! env.VERSION) {
env.VERSION = sh(script: "git describe", returnStdout: true).trim()
}
}
}
}
Got this error groovy.lang.MissingPropertyException: No such property: VERSION for class: groovy.lang.Binding
I then tried to add a "environment" step below
environment {
VERSION = ${VERSION}
}
but it didn't solve my problem.
I'm looking for any help to solve it.
UPDATE
I now have a working pipeline which looks like
pipeline {
agent any
parameters {
string(name: 'VERSION', defaultValue: '')
}
environment {
def VERSION = "${params.VERSION}"
}
stages {
stage('Prepare & Checkout') {
steps {
script {
if (! env.VERSION) {
VERSION = sh(script: "date", returnStdout: true).trim()
}
echo "** version: ${VERSION} **"
}
}
}
stage('Build') {
steps {
// sh "./build.sh"
echo "** version2: ${VERSION} **"
}
}
} // stages
post {
always {
mail to: 'foo#example.com',
subject: "SUCCESS: ${VERSION}",
body: """<html><body><p>SUCCESS</p></body></html>""",
mimeType: 'text/html',
charset: 'UTF-8'
deleteDir()
}
}
} // pipeline
I needed to add the "environment" step to be able to get $VERSION in all Stages (not only in the one it is manipulated).
I still need to find a way to inject this $VERSION variable in the environment variables, so that my build script can find it.
If you want to inject the variable in the environment so that you can use it later, you could define another variable that is equal to env.VERSION or the output of the shell scrip. Then use that variable in your pipeline eg:
pipeline {
parameters {
string(name: VERSION, defaultValue: '')
}
def version = env.VERSION
stages {
stage('Prepare') {
steps {
// ...
if (!version) {
version = sh(script: "git describe", returnStdout: true).trim()
}
}
}
mail subject: "$version build succeeded", ...
}
If you want other jobs to be able to access the value of VERSION after the build is run, you can write it in a file and archive it.
Edit:
In order for your script to be able to use the version variable, you can either make your script take version as a parameter or you can use the withEnv step.
Assuming you are using Parametrized pipelines, you should call variable as ${params.parameterName}
Although parameters are available in env they currently are created before the first time the pipeline is run, therefore you should access them via params:
In your case:
${params.VERSION}

Resources