Skip to content

Deploy with Environment Variables

In this tutorial, we will refactor the Jenkinsfile to use environment variables. This creates a cleaner and more maintainable pipeline by avoiding hardcoded values in multiple places.

Jenkinsfile

Here is the complete Jenkinsfile. You can find the source code in the GitHub repository.

pipeline {
  agent any
  options {
    disableConcurrentBuilds()
    disableResume()
    buildDiscarder(logRotator(numToKeepStr: '10'))
    timeout(time: 1, unit: 'HOURS')
  }
  tools {
    maven 'maven-3.6.3' 
  }
  parameters {
    choice(name: 'ENVIRONMENT', choices: ['dev', 'qa', 'prod'], description: 'Choose Environment')
  }
  environment {
    CONTEXT_PATH = "/helloworld"
    WAR_FILE_PATH = "webapp/target/*.war"
  }
  stages {
    stage ('Build') {
      steps {
        sh 'mvn clean package'
      }
    }
    stage ('Deploy to Dev') {
      when {
        environment name: "ENVIRONMENT", value: "dev"
      }
      steps {
        script {
          deploy adapters: [tomcat9(credentialsId: 'tomcat_credential', path: '', url: 'http://20.197.20.20:8080')], contextPath: "${env.CONTEXT_PATH}", onFailure: false, war: "${env.WAR_FILE_PATH}"
        }
      }
    }
    stage ('Deploy to Qa') {
      when {
        environment name: "ENVIRONMENT", value: "qa"
      }
      steps {
        script {
          deploy adapters: [tomcat9(credentialsId: 'tomcat-credential', path: '', url: 'http://20.197.20.30:8080')], contextPath: "${env.CONTEXT_PATH}", onFailure: false, war: "${env.WAR_FILE_PATH}"
        }
      }
    }
    stage ('Deploy to Prod') {
      when {
        environment name: "ENVIRONMENT", value: "prod"
      }
      steps {
        script {
          deploy adapters: [tomcat9(credentialsId: 'tomcat-credential', path: '', url: 'http://20.197.20.178:8080')], contextPath: "${env.CONTEXT_PATH}", onFailure: false, war: "${env.WAR_FILE_PATH}"
        }
      }
    }
  }
  post {
    always {
      deleteDir()
    }
  }
}

Explanation

environment

The environment directive allows you to define key-value pairs that are available as environment variables to all steps in the pipeline.

environment {
  CONTEXT_PATH = "/helloworld"
  WAR_FILE_PATH = "webapp/target/*.war"
}

Here, we defined CONTEXT_PATH and WAR_FILE_PATH. These variables are then reused in the deployment stages.

Accessing Variables

You can access these environment variables using the ${env.VARIABLE_NAME} syntax inside double quotes (GString):

contextPath: "${env.CONTEXT_PATH}", onFailure: false, war: "${env.WAR_FILE_PATH}"

This makes it easy to change the context path or war file location in one place without having to update every stage.

Reference

๐Ÿง  Quick Quiz โ€” Environment Variables

#

How do you access a custom environment variable defined in the environment block within a pipeline script?

๐Ÿ“ฌ DevopsPilot Weekly โ€” Learn DevOps, Cloud & Gen AI the simple way.
๐Ÿ‘‰ Subscribe here