Interview Prep/Real-World Interview/Write-a-pipeline tasks

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.

All Real-World Interview questions Roadmap: Interview readiness

More on Write-a-pipeline tasks