Reputation: 855
I have a groovy script that calls other jobs to stop and start tasks. (see below). I would like to re-use the code inside the steps {
over and over again. Can I do this without having to repeat the code?
Basically I want to have the next stage for another API that I can start or stop, then another, etc. These are then built with parameters on the Jenkins where radio buttons decide whether to stop or start.
#!/usr/bin/env groovy
pipeline {
environment {
containerInstanceIdsToStartOn = "463b8b6f-9388-4fbd-8257-b056e28c0a43"
region = "eu-west-1"
cluster = "mis-core-dev"
}
agent any
stages {
stage('Authentication API (dev)') {
environment {
apiName = "authentication_API"
taskDefinitionFamily = "mis-core-dev-authentication-api"
taskDefinition = "mis-core-dev-authentication-api"
}
steps {
script {
if (params."${apiName}".contains('Stop Task')) {
build(job: 'Stop ECS Task (utility)',
parameters: [
string(name: 'region', value: params."${region}"),
string(name: 'cluster', value: params."${cluster}"),
string(name: 'family', value: params."${taskDefinitionFamily}")
])
}
else if (params."${apiName}".contains('Start Task')) {
build(job: 'Start ECS Task (utility)',
parameters: [
string(name: 'region', value: params."${region}"),
string(name: 'cluster', value: params."${cluster}"),
string(name: 'taskDefinition', value: params."${taskDefinition}"),
string(name: 'containerInstanceIds', value: params."${containerInstanceIdsToStartOn}")
])
}
else if (params."${apiName}" == null || params."${apiName}" == "") {
echo "Did you forget to check a box?"
}
}
}
}
}
post {
always {
cleanWs()
}
}
}
Upvotes: 2
Views: 2089
Reputation: 47319
It is not possible to share parts of a declarative pipeline. The declarative pipeline DSL is processed in a special way at runtime where you can't split out some of the pieces. You could share some logic in how some of the blocks are executed (like the code used inside of a script
block), but the sharing capabilities are limited to basically the entire pipeline definition itself
From the Shared Library documentation:
Only entire pipelines can be defined in shared libraries as of this time. This can only be done in
vars/*.groovy
, and only in acall
method. Only one Declarative Pipeline can be executed in a single build, and if you attempt to execute a second one, your build will fail as a result.
Upvotes: 2