Home DevOpsJenkins Pipeline as Code: Declarative Jenkinsfile on Ubuntu

Jenkins Pipeline as Code: Declarative Jenkinsfile on Ubuntu

by Knowledge Base Linux
Clean technical illustration of jenkins pipeline as code with build stages flowing into a deployment server, no text in image

Clicking through the Jenkins web interface to configure every build job works fine for one job, but it breaks down fast at scale: settings drift, nobody knows what changed, and rebuilding a lost controller means recreating jobs from memory. Jenkins pipeline as code solves this by defining the entire build, test, and deploy workflow in a version-controlled Jenkinsfile that lives next to your application source code. Every change is reviewed in a pull request, every build is reproducible, and a new Jenkins controller can pick up the same pipeline in minutes.

Clean technical illustration of jenkins pipeline as code stages checkout build test deploy as a flow diagram, no text in image

In this guide you will write a complete declarative Jenkinsfile for a Node.js application, create a pipeline job in Jenkins that tracks it from Git, run a build, and learn how to diagnose the most common failures. This jenkins pipeline as code workflow is the same pattern used by production teams, so everything here applies directly to a real project. We assume Jenkins is already installed; if it is not, see our guide on installing Jenkins on Ubuntu 24.04 first.

What Jenkins Pipeline as Code Means

Pipeline as Code means the pipeline definition is a text file stored in source control rather than configuration stored in Jenkins itself. Jenkins offers two syntaxes: Scripted Pipeline, which is a full Groovy script, and Declarative Pipeline, which is a structured, opinionated syntax built on top of it. For most teams, Declarative is the right choice: it is easier to read, it validates syntax before running, and the Jenkins UI renders it as a visual stage view.

A declarative pipeline has a fixed structure. The pipeline block contains an agent section (where the build runs), environment variables, options, stages (each with steps), and a post section that runs actions after the build finishes, whatever the result. Jenkins checks out the repository, reads the Jenkinsfile from the branch being built, and executes the stages in order on the chosen agent. Because the definition lives in Git, adopting jenkins pipeline as code also gives you a full audit trail: every pipeline change has an author, a timestamp, and a review.

Prerequisites

  • A Jenkins controller running on Ubuntu 24.04 with administrator access, plus at least one agent (the built-in node is fine for learning, but a separate agent is recommended for production).
  • Docker installed on the agent, if your pipeline builds container images as in this guide.
  • A Git repository (GitHub, GitLab, or self-hosted) containing your application and the Jenkinsfile at the repository root.
  • The Pipeline, Git, SSH Agent, and Workspace Cleanup plugins installed. Most are bundled with a standard Jenkins installation; install any missing ones from Manage Jenkins, then Plugins.
  • An SSH credential in Jenkins for deployment, if your pipeline deploys over SSH. Create it under Manage Jenkins, then Credentials, and note its ID.

Write a Declarative Jenkinsfile for Jenkins Pipeline as Code

Create a file named Jenkinsfile at the root of your repository. This complete example checks out the code, builds a Docker image, runs the test suite inside the image, and deploys only from the main branch. Replace the registry hostname, image name, and credential IDs with your own values.

pipeline {
    agent any

    environment {
        REGISTRY = 'registry.example.com'
        IMAGE = 'myapp'
    }

    options {
        timestamps()
        timeout(time: 30, unit: 'MINUTES')
        buildDiscarder(logRotator(numToKeepStr: '10'))
    }

    stages {
        stage('Checkout') {
            steps {
                checkout scm
            }
        }
        stage('Build') {
            steps {
                sh "docker build -t ${REGISTRY}/${IMAGE}:${BUILD_NUMBER} ."
            }
        }
        stage('Test') {
            steps {
                sh "docker run --rm ${REGISTRY}/${IMAGE}:${BUILD_NUMBER} npm test"
            }
        }
        stage('Deploy') {
            when {
                branch 'main'
            }
            steps {
                sshagent(['deploy-ssh-key']) {
                    sh "docker save ${REGISTRY}/${IMAGE}:${BUILD_NUMBER} | ssh [email protected] 'docker load'"
                    sh "ssh [email protected] 'docker stop myapp || true && docker rm myapp || true && docker run -d --name myapp -p 3000:3000 ${REGISTRY}/${IMAGE}:${BUILD_NUMBER}'"
                }
            }
        }
    }

    post {
        always {
            cleanWs()
        }
        success {
            echo 'Build and deploy succeeded.'
        }
        failure {
            echo 'Build failed. Check the failing stage in the console output.'
        }
    }
}

A few details worth noting. The when { branch 'main' } guard means feature branches build and test but never deploy, which is exactly the safety net you want. The environment block keeps values like the registry hostname in one place instead of repeating them in every step. The post block always cleans the workspace so disk usage does not grow unbounded, and it reports success or failure clearly in the log.

For secrets, never hardcode passwords or tokens in the Jenkinsfile. Use Jenkins credentials instead: reference a secret text credential with credentials('my-credential-id') inside the environment block, or wrap steps in withCredentials. Jenkins masks credential values in console output automatically, but only if you use the credentials system rather than plain variables. This discipline is part of doing jenkins pipeline as code properly, since the Jenkinsfile is visible to everyone with repository access.

Create the Pipeline Job in Jenkins

With the Jenkinsfile committed and pushed, create the job that tracks it:

  1. In the Jenkins dashboard, click New Item, enter a name such as myapp-pipeline, select Pipeline, and click OK.
  2. Under Pipeline, set Definition to Pipeline script from SCM.
  3. Set SCM to Git and enter your Repository URL. If the repository is private, select the matching credential or add one with the Add button.
  4. Set Branch Specifier to */main (or your default branch) and Script Path to Jenkinsfile. Leave Lightweight checkout enabled unless your Jenkinsfile loads shared libraries from the same repository.
  5. Click Save. Jenkins will not run a build until you trigger one, unless you also configure a build trigger such as a webhook or polling schedule.

For automatic builds on every push, add a webhook in your Git provider pointing at https://jenkins.example.com/github-webhook/ for GitHub, or enable Poll SCM with a schedule such as H/5 * * * * if webhooks are not possible. If you manage several branches, consider a Multibranch Pipeline job instead: it discovers branches automatically and builds a Jenkinsfile from each one. Either way, the jenkins pipeline as code definition stays the same; only the job type that discovers it changes.

Run and Inspect Your Jenkins Pipeline as Code Build

Click Build Now on the job page. The Stage View shows each stage as it runs, turning green on success or red on failure. Click a stage, then Console Output, to read the log for that stage only, which is much faster than scrolling through the full log of a long build.

For a richer visual view, install the Blue Ocean plugin and open the build from the Open Blue Ocean link. Blue Ocean renders the pipeline as a flow diagram, shows test results per stage, and lets you replay a single failed stage from the point of failure using the Replay feature. Replay is also available from the classic UI on the build page, and it is invaluable when debugging: you can edit the Jenkinsfile in the replay editor and rerun without committing.

Check the build history over time. The buildDiscarder option in our example keeps the last 10 builds, which bounds disk usage while retaining enough history to compare a failing build against the last good one. If you need to compare console output between two builds, open both build pages and diff the failing stage logs side by side. Over weeks of runs, this history becomes a useful record of how your jenkins pipeline as code setup evolves alongside the application.

Troubleshooting Jenkins Pipeline as Code

Symptom Likely cause and fix
WorkflowScript: ... Expected a step or similar syntax error Invalid declarative syntax. Validate before committing with the Jenkins CLI declarative linter: java -jar jenkins-cli.jar -s http://localhost:8080/ declarative-linter < Jenkinsfile. Also use the Pipeline Syntax snippet generator at /pipeline-syntax/ on your Jenkins controller.
Build waits forever for an executor No agent matches the agent label, or all executors are busy. Check Manage Jenkins, then Nodes, and confirm an online agent carries the requested label.
docker: command not found Docker is not installed on the agent, or the jenkins user is not in the docker group. Install Docker on the agent and add the user with sudo usermod -aG docker jenkins, then reconnect the agent.
Credential not found, or authentication fails in Deploy The credential ID in the Jenkinsfile does not match any credential in Jenkins, or the credential is stored in the wrong scope. Verify the exact ID under Manage Jenkins, then Credentials, and remember IDs are case-sensitive.
Deploy runs on feature branches The when condition is missing or misspelled. Confirm the branch name matches exactly, including case, and that the condition sits inside the Deploy stage, not at pipeline level.
Workspace fills the disk The cleanWs() step requires the Workspace Cleanup plugin. If it is missing, the post block fails silently or errors; install the plugin and confirm cleanup runs in the log.

One more habit pays off quickly: keep a staging job that mirrors production but deploys to a test server. Test pipeline changes there first, especially changes to the Deploy stage, so a typo never takes down the live application. A staging job costs almost nothing and protects the jenkins pipeline as code workflow from its most embarrassing failure mode. For an alternative runner-based approach to CI, compare with our guide on GitHub Actions self-hosted runners on Linux. The official Jenkins Pipeline syntax documentation is the authoritative reference for every directive used here.

Conclusion

Jenkins pipeline as code turns your build process from fragile point-and-click configuration into a reviewed, versioned, repeatable asset. You wrote a declarative Jenkinsfile with checkout, build, test, and guarded deploy stages, wired it to a pipeline job tracking Git, and learned how to read stage output and fix the failures you are most likely to meet.

From here, natural next steps are a shared library for steps repeated across repositories, parallel test stages to cut build time, and a Multibranch Pipeline so every pull request gets its own build before merge. Each of these builds on the same jenkins pipeline as code foundation you have just set up.

You may also like

KbLinux

Typically replies within a day

Hello, Welcome to the site. Please click below button for chatting me through Telegram.