I would like to reuse code between different Jenkins deployments. Is it possible to share, for example, both to staging and to production, such that the only differences are the environment variables?
I imagine it could look something like this (although this obviously doesn't work):
pipeline {
stage("Dev Deploy"){
environment {
PROP1 = "abc"
}
deploy ()
}
stage("Prod Deploy"){
environment {
PROP1 = "xyz"
}
deploy ()
}
}
deploy = steps{
sh "./gradlew deploy -Pproperty1=${env.PROP1}"
}
Step 1: Open Jenkins home page ( http://localhost:8080 in local) & click on New Item from the left side menu. Step 2: Enter Jenkins job name & choose the style as Pipeline & click OK. Step 3: Scroll down to the Pipeline section & copy-paste your first Declarative style Pipeline code from below to the script textbox.
1 Step 1: Create a Github repo with our pipeline code in a file named Jenkinsfile. Or you can use this Github repo for... 2 Step 2: Follow the same steps we used for creating a pipeline job. But instead of entering the code directly into the... 3 Step 3: Save the configuration and run the build. You should see a successful build. More ...
Even though the Jenkins application remains the primary environment for developing and deploying pipelines, the code for these pipelines can be placed in an external file known as the Jenkinsfile. This allows you to treat your pipeline code like any other text file.
Adopting pipeline code for all Jenkins workflows will give more control and streamlined pipelines for your CI/CD need. Extending your pipelines with a shared library lets you reuse the pipeline code for all implementations. Let us know your thoughts in the comment section below.
You are close. You can't quite do it in straight declarative, but if you mix in a little scripted you can accomplish this with a Closure. The "steps" has to be in each stage so you can run a "script", but the Closure defined as deploy
can have any normal steps in it.
def deploy = {
sh "./gradlew deploy -Pproperty1=${env.PROP1}"
}
pipeline {
agent any
stages {
stage("Dev Deploy"){
environment {
PROP1 = "abc"
}
steps {
script {deploy ()}
}
}
stage("Prod Deploy"){
environment {
PROP1 = "xyz"
}
steps {
script {deploy ()}
}
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With