DEV Community

Srinivasaraju Tangella
Srinivasaraju Tangella

Posted on

Where Should You Use Variables in Jenkins Declarative Pipelines?

Many beginners struggle with the question: “Where should I use variables in my Jenkins pipeline?” If you put them in the wrong place, your pipeline either won’t work or becomes messy. This guide will clear that confusion with simple, practical examples.

1.Global Pipeline Variables

Declared using the environment directive.

Available across all stages and steps.

Good for storing things like repo URLs, credentials IDs, branch names.

pipeline {
agent any
environment {
APP_NAME = "my-app"
GIT_BRANCH = "main"
}
stages {
stage('Build') {
steps {
echo "Building ${APP_NAME} from branch ${GIT_BRANCH}"
}
}
stage('Deploy') {
steps {
echo "Deploying ${APP_NAME}"
}
}
}
}

✅ Use when the variable is common for the whole pipeline.

2.Stage-Level Variables

Declared inside environment for a specific stage.

Available only within that stage.

stage('Test') {
environment {
TEST_ENV = "qa"
}
steps {
echo "Running tests in ${TEST_ENV} environment"
}
}

✅ Use when a variable is needed only in one stage.

3.Scripted/Temporary Variables

Declared inside script {} blocks.

Work like normal Groovy variables.

Exist only inside that block.

stage('Package') {
steps {
script {
def version = "1.0.${env.BUILD_NUMBER}"
echo "Packaging app version: ${version}"
}
}
}

✅ Use when a variable is computed dynamically during runtime.

4.Parameters as Variables

Declared using the parameters directive.

Accessible via params..

Useful for user inputs at runtime.

pipeline {
agent any
parameters {
string(name: 'BRANCH', defaultValue: 'main', description: 'Branch to build')
}
stages {
stage('Checkout') {
steps {
git branch: "${params.BRANCH}", url: 'https://github.com/my/repo.git'
}
}
}
}

✅ Use when you want user-defined inputs.

5.Injected from Config/Properties File

Variables can be loaded from a .properties file with readProperties.

Helps keep pipeline clean and maintainable.

stage('Load Config') {
steps {
script {
def props = readProperties file: 'config.properties'
echo "App Name: ${props.APP_NAME}"
}
}
}

✅ Use when variables are externalized for flexibility.

🔑 Rule of Thumb

Common for whole pipeline? → environment at pipeline level.

Only for one stage? → environment inside stage.

Dynamic/temporary? → script {} Groovy variable.

User input? → parameters.

Externalized configs? → .properties + readProperties.

Top comments (0)