Jenkinsfile — Pipeline as Code

Jenkinsfile defines CI/CD pipeline as code (pipeline { agent any; stages { stage("Build") { steps {...} } } post { success/failure } }). Declarative pipeline = easy, structured, uses predefined syntax. Scripted pipeline = Groovy-based, flexible, handles complex logic. 7 main keywords: pipeline, agent, stages, stage, steps, post, environment.

Overview

Pipeline as code

A Jenkinsfile is a text file checked into the source repository that defines the entire CI/CD pipeline as code. Jenkins reads it automatically when a build triggers. Keeping the pipeline in the repository gives version control, peer review and reproducibility.

Here is what happens to one change, using the Declarative pipeline shown further down.

  • A developer runs git push or opens a pull request, and GitHub or GitLab sends a webhook that triggers a build.
  • Jenkins reads the Jenkinsfile from the repository.
  • The Build, Test and Docker Build stages run in order.
  • The Deploy stage runs on the main branch only.
  • The post section reacts to the result, with blocks for success, failure and always.

Behind those steps, the Jenkins controller does the job scheduling and pipeline orchestration and keeps the credentials, plugins and user access control. Agents do the work. A build agent compiles and runs unit tests for Java, Node or Python. A Docker agent builds the image and pushes it to a container registry such as ECR, Docker Hub or Nexus. A deploy agent runs kubectl apply or a cloud deploy. A full pipeline often takes code through build, test, scan and package before deploy.

Key concepts

  • Declarative vs Scripted
  • agent directive
  • post block
  • withCredentials
  • parallel stages
  • when directive

Interview questions

  • Write a Jenkinsfile with Build, Test, Docker Build, and Deploy stages.
  • What is the difference between declarative and scripted Jenkins pipelines?

Sign up free to read the full topic

More DevOps topics

Start free on Cariara · Coding problems · System design studio