Write a declarative Jenkinsfile with build, test, Docker push and a manual approval before prod.
AdvancedHands-onWrite-a-pipeline tasks
Answer
pipeline {
agent any
environment {
IMAGE = "myrepo/app:${env.GIT_COMMIT.take(7)}"
}
options {
timeout(time: 30, unit: 'MINUTES')
buildDiscarder(logRotator(numToKeepStr: '20'))
}
stages {
stage('Build') { steps { sh 'mvn -B -DskipTests package' } }
stage('Test') {
steps { sh 'mvn -B test' }
post { always { junit 'target/surefire-reports/*.xml' } }
}
stage('Docker') {
steps {
withCredentials([usernamePassword(credentialsId: 'dockerhub',
usernameVariable: 'U', passwordVariable: 'P')]) {
sh '''
echo "$P" | docker login -u "$U" --password-stdin
docker build -t "$IMAGE" .
docker push "$IMAGE"
'''
}
}
}
stage('Deploy prod') {
when { branch 'main' }
input {
message 'Deploy to production?'
ok 'Deploy'
}
steps { sh "helm upgrade --install app ./chart --set image.tag=${env.GIT_COMMIT.take(7)}" }
}
}
post { failure { echo 'Build failed - notify the team here' } }
}
Key trick → Use single-quoted sh '''...''' so Groovy doesn't interpolate the secret; the shell expands $P instead. Jenkins warns about Groovy string interpolation of secrets. An input inside a stage with agent any holds an executor while it waits, so in real setups put the approval stage on agent none.
More on Write-a-pipeline tasks
Write a GitHub Actions workflow that runs tests on every PR and push to main.BeginnerWrite a workflow that builds a Docker image and pushes it to ECR using OIDC (no access keys).IntermediateWrite a matrix job that tests on Python 3.10, 3.11 and 3.12 on Linux and Windows.BeginnerWrite a GitHub Actions deploy job that requires approval for production using environments.BeginnerWrite a reusable workflow and call it from another repo.IntermediateWrite a workflow that only runs the backend job when files under `backend/` change.Intermediate