Environment Variables and Credentials
You'll learn how to define environment variables in Jenkins pipelines and securely inject credentials without hardcoding secrets.
The Core Idea
In Jenkins pipelines, environment variables let you configure behavior dynamically (like API endpoints, build versions, or deployment targets), while credentials provide secure access to secrets (passwords, tokens, SSH keys) without exposing them in your code or logs.
Think of environment variables as configuration dials you can adjust per build, and credentials as locked safes that Jenkins opens only when needed—handing your pipeline the secret inside without ever showing it to anyone watching.
Defining Environment Variables
Use the environment directive at pipeline or stage level to declare variables:
pipeline {
agent any
environment {
APP_VERSION = '1.2.3'
DEPLOY_ENV = 'staging'
}
stages {
stage('Build') {
steps {
echo "Building version ${APP_VERSION} for ${DEPLOY_ENV}"
}
}
}
}
Variables defined at the pipeline level are available everywhere; stage-level variables only exist within that stage.
Injecting Credentials Securely
Use the credentials() helper to access stored credentials from Jenkins:
pipeline {
agent any
environment {
API_KEY = credentials('my-api-key-id')
}
stages {
stage('Deploy') {
steps {
sh 'curl -H "Authorization: Bearer $API_KEY" https://api.example.com/deploy'
}
}
}
}
Jenkins automatically masks these values in console logs, showing **** instead of the actual secret.
Key Takeaway: Use environment blocks for configuration variables and the credentials() function to securely access secrets—keeping sensitive data out of your pipeline code and logs.