Ravindra BagaleCourses & study guides Track your progress

Labs · DevOps

Lab: Create a Jenkins Pipeline Job from SCM with a Declarative Jenkinsfile That Installs, Tests and Archives a Node.js App

Intermediate60 minDocker · Jenkins LTS · Git · A Git repository you own

Course: DevOps · Chapter 21: Jenkins Pipeline and Jenkinsfile · Lesson: 21.5 Full declarative Jenkinsfile for badge-node

Chapter 21 explains every declarative block; this lab runs a real Jenkinsfile end to end.

Chala mitrano! Freestyle job madhe click click karun pipeline banavla tar kuNalach aathvat nahi. Aaj Jenkinsfile Git madhe thevuya.

Suppose we are…

Suppose we are on an Infosys delivery team. The build steps live in a freestyle job that one person configured by clicking. When that person is on leave, nobody knows what the job does. A Jenkinsfile keeps the pipeline in Git, next to the code, reviewed like code.

In this lab we run Jenkins locally in Docker, create a Pipeline job that reads the Jenkinsfile from our repository, and build a small Node.js app: install, test and archive.

Goal of this lab

By the end you will have:

  • Jenkins LTS running in Docker on http://localhost:8080.
  • A Pipeline job using Pipeline script from SCM.
  • A green build with stages Checkout, Install, Test and Archive, and a test report.

What you need

  • Docker on your laptop with about 2 GB free memory.
  • A Git repository you own with a small Node.js app (the badge-ci repo from the GitHub Actions lab works).
  • 60 minutes.

Safety

This Jenkins is for practice on your own laptop. Do not expose port 8080 to the internet, and keep the admin password private.

Part 1: Run Jenkins

  1. Start Jenkins LTS with a named volume for its data:

    docker volume create jenkins_home
    docker run -d --name jenkins -p 8080:8080 -v jenkins_home:/var/jenkins_home jenkins/jenkins:lts-jdk17
    
  2. Read the one-time admin password:

    docker exec jenkins cat /var/jenkins_home/secrets/initialAdminPassword
    

    What you should see: a 32-character hex string.

  3. Open http://localhost:8080, paste the password, choose Install suggested plugins, and create your own admin user.

    What you should see: the Jenkins dashboard with Welcome to Jenkins!

  4. Install Node.js inside the Jenkins container for this lab (the official image has none):

    docker exec -u root jenkins bash -c "apt-get update && apt-get install -y nodejs npm && node -v"
    

    In a real setup builds run on agents with tools installed, not on the controller (Chapter 27).

    What you should see: a Node version such as v18.x or newer.

Part 2: Write the Jenkinsfile

  1. In your repo, create Jenkinsfile at the top level:

    Jenkinsfile

    pipeline {
      agent any
      options {
        timeout(time: 15, unit: 'MINUTES')
        timestamps()
        disableConcurrentBuilds()
        buildDiscarder(logRotator(numToKeepStr: '10'))
      }
      environment {
        CI = 'true'
      }
      stages {
        stage('Checkout') {
          steps {
            checkout scm
            sh 'git log -1 --oneline'
          }
        }
        stage('Install') {
          steps {
            sh 'node -v && npm -v'
            sh 'npm install --no-audit --no-fund'
          }
        }
        stage('Test') {
          steps {
            sh 'npm test'
          }
        }
        stage('Archive') {
          steps {
            sh 'mkdir -p dist && tar czf dist/badge-ci-${BUILD_NUMBER}.tgz *.js package.json'
            archiveArtifacts artifacts: 'dist/*.tgz', fingerprint: true
          }
        }
      }
      post {
        success { echo "Build ${env.BUILD_NUMBER} passed" }
        failure { echo 'Build failed: read the first red line in the console' }
        always  { cleanWs() }
      }
    }
    

    timestamps() needs the Timestamper plugin and cleanWs() needs Workspace Cleanup; both come with the suggested plugins on current LTS. If not, install them from Manage Jenkins → Plugins.

  2. Commit and push it:

    git add Jenkinsfile
    git commit -m "Add declarative Jenkinsfile"
    git push
    

Part 3: Create the job and build

  1. In Jenkins click New Item, name it badge-ci, choose Pipeline, OK.

  2. Under Pipeline choose Definition: Pipeline script from SCM, SCM Git, paste your repository URL, branch */main, Script Path Jenkinsfile. For a private repo, add a credential (a token, stored in Jenkins credentials, never in the Jenkinsfile). Save.

  3. Click Build Now, then open the build and Console Output.

    What you should see: the four stages and Finished: SUCCESS; on the build page, Build Artifacts lists badge-ci-1.tgz.

  4. Break a test, push, and build again.

    What you should see: the Test stage turns red, Archive is skipped, and the console ends with Finished: FAILURE. Fix it and build once more to get green.

Clean up

  1. Stop Jenkins when you finish. Keep the volume if you want to continue tomorrow:

    docker stop jenkins
    # to remove everything:
    # docker rm -f jenkins && docker volume rm jenkins_home
    

Ravindra Bagale's Tip

Keep one Jenkinsfile per repository and change it only through pull requests. Then every pipeline change has a reviewer and a history.

Common mistakes

MistakeWhat happensFix
node: not foundInstall stage failsInstall Node on the agent or use the NodeJS plugin tool
Script Path wrongUnable to find JenkinsfileUse the exact file name and folder, case-sensitive
Pasting a token into the JenkinsfileSecret in Git historyUse Jenkins credentials and withCredentials
Exposing port 8080 publiclyAnyone can try to log inKeep it on localhost or behind a VPN

Self-check checklist

0 of 4 done

Try-at-home challenge

Add a parameters { booleanParam(name: 'RUN_TESTS', defaultValue: true) } block and a when { expression { params.RUN_TESTS } } on the Test stage. Build once with tests and once without, and explain why skipping tests on main is dangerous.

Samajla ka? Pipeline as code, reviewed like code. Aata pudhe jaauya webhook ani multibranch.