Bird
Raised Fist0
Jenkinsdevops~10 mins

Environment variables access in Jenkins - Step-by-Step Execution

Choose your learning style10 modes available
Process Flow - Environment variables access
Start Jenkins Job
↓
Load Environment Variables
↓
Access Variables in Pipeline
↓
Use Variables in Steps
↓
Job Execution Continues
↓
Job Ends
This flow shows how Jenkins loads environment variables at job start, then the pipeline accesses and uses them during execution.
Execution Sample
Jenkins
pipeline {
  agent any
  stages {
    stage('Print Env') {
      steps {
        echo "PATH is ${env.PATH}"
      }
    }
  }
}
This Jenkins pipeline prints the PATH environment variable during the 'Print Env' stage.
Process Table
StepActionEnvironment Variable AccessedValue RetrievedOutput
1Start Jenkins JobN/AN/AJob starts, environment variables loaded
2Enter 'Print Env' stagePATH/usr/bin:/bin:/usr/sbin:/sbinReady to use PATH variable
3Execute echo stepPATH/usr/bin:/bin:/usr/sbin:/sbinPrints: PATH is /usr/bin:/bin:/usr/sbin:/sbin
4Stage completesN/AN/AStage finished successfully
5Job endsN/AN/AJob execution complete
💡 Job ends after all stages complete
Status Tracker
VariableStartAfter Step 2After Step 3Final
env.PATHN/A/usr/bin:/bin:/usr/sbin:/sbin/usr/bin:/bin:/usr/sbin:/sbin/usr/bin:/bin:/usr/sbin:/sbin
Key Moments - 2 Insights
Why do we use env.PATH instead of just PATH in the pipeline?
In Jenkins pipelines, environment variables are accessed via the env object (like env.PATH). This is shown in execution_table step 3 where echo uses ${env.PATH} to get the value.
What happens if we try to access an environment variable that does not exist?
If the variable does not exist, env.VAR returns null or empty string. The pipeline will print nothing or empty value. This is implied by the variable_tracker showing only existing variables.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is printed at step 3?
APATH is null
BPATH is empty
CPATH is /usr/bin:/bin:/usr/sbin:/sbin
DError accessing PATH
💡 Hint
Check the Output column at step 3 in the execution_table
At which step does the pipeline actually access the environment variable PATH?
AStep 1
BStep 3
CStep 2
DStep 4
💡 Hint
Look at the Environment Variable Accessed column in execution_table
If we tried to print a variable not set in the environment, what would happen?
APipeline prints an empty string or nothing
BPipeline prints the variable name
CPipeline crashes immediately
DPipeline prints 'undefined'
💡 Hint
Refer to key_moments explanation about missing variables
Concept Snapshot
Jenkins pipelines access environment variables via the env object.
Use syntax ${env.VAR_NAME} inside steps.
Variables are loaded at job start.
If variable missing, value is empty or null.
Use echo to print variables for debugging.
Full Transcript
This visual execution shows how Jenkins pipelines access environment variables. When a Jenkins job starts, it loads environment variables from the system. Inside the pipeline, these variables are accessed using the env object, for example env.PATH. The example pipeline prints the PATH variable during the 'Print Env' stage. The execution table traces each step: job start, entering the stage, accessing PATH, printing it, and job completion. The variable tracker shows env.PATH value remains constant during execution. Key moments clarify why env.PATH syntax is used and what happens if a variable is missing. The quiz tests understanding of when and how variables are accessed and printed. This helps beginners see environment variable usage in Jenkins pipelines step-by-step.

Practice

(1/5)
1. In a Jenkins Pipeline script, how do you access an environment variable named BUILD_NUMBER?
easy
A. Using BUILD_NUMBER directly without prefix
B. Using env.BUILD_NUMBER
C. Using getEnv('BUILD_NUMBER')
D. Using $BUILD_NUMBER inside the script block

Solution

  1. Step 1: Understand Jenkins environment variable access

    Jenkins Pipeline exposes environment variables via the env object.
  2. Step 2: Access the variable using the correct syntax

    You access BUILD_NUMBER as env.BUILD_NUMBER in the script.
  3. Final Answer:

    Using env.BUILD_NUMBER -> Option B
  4. Quick Check:

    env.VARIABLE_NAME = correct access [OK]
Hint: Always prefix environment variables with env. in Jenkins [OK]
Common Mistakes:
  • Trying to use variable name without env prefix
  • Using shell-style $VARIABLE inside Groovy script
  • Calling non-existent getEnv() method
2. Which of the following is the correct syntax to print the environment variable JOB_NAME in a Jenkins Pipeline script block?
easy
A. println("JOB_NAME")
B. echo $JOB_NAME
C. println(env.JOB_NAME)
D. print(JOB_NAME)

Solution

  1. Step 1: Identify the correct way to print env variables in Groovy script

    In Jenkins Pipeline Groovy scripts, use println(env.VARIABLE) to print environment variables.
  2. Step 2: Check each option

    println("JOB_NAME") prints the string "JOB_NAME" literally. echo $JOB_NAME uses shell syntax, invalid in Groovy. print(JOB_NAME) attempts to print JOB_NAME directly, but it's not available in Groovy scope without env prefix.
  3. Final Answer:

    println(env.JOB_NAME) -> Option C
  4. Quick Check:

    Use println(env.VARIABLE) to print env vars in script [OK]
Hint: Use println(env.VARIABLE) inside script blocks [OK]
Common Mistakes:
  • Using shell syntax like $VARIABLE inside Groovy
  • Printing variable name as string instead of value
  • Trying to access variables without env. prefix
3. Given this Jenkins Pipeline snippet:
pipeline {
  agent any
  stages {
    stage('Print Env') {
      steps {
        script {
          echo "Branch is: ${env.BRANCH_NAME}"
        }
      }
    }
  }
}

What will be the output if the environment variable BRANCH_NAME is set to feature-123?
medium
A. Branch is: feature-123
B. Branch is: ${env.BRANCH_NAME}
C. Branch is: BRANCH_NAME
D. Error: BRANCH_NAME not found

Solution

  1. Step 1: Understand string interpolation in Jenkins Pipeline

    Using double quotes with ${env.BRANCH_NAME} interpolates the variable value.
  2. Step 2: Substitute the environment variable value

    Since BRANCH_NAME is set to "feature-123", the output will be "Branch is: feature-123".
  3. Final Answer:

    Branch is: feature-123 -> Option A
  4. Quick Check:

    Double quotes + ${env.VAR} = variable value [OK]
Hint: Use double quotes and ${env.VAR} for variable interpolation [OK]
Common Mistakes:
  • Using single quotes which prevent interpolation
  • Printing variable name literally without ${}
  • Assuming env variables are undefined
4. You wrote this Jenkins Pipeline snippet:
pipeline {
  agent any
  environment {
    MY_VAR = 'hello'
  }
  stages {
    stage('Test') {
      steps {
        script {
          echo env.MY_VAR
        }
      }
    }
  }
}

But the output is empty. What is the likely cause?
medium
A. The environment block syntax is incorrect; use MY_VAR='hello' with quotes and no spaces around =
B. Environment variables must be accessed as env['MY_VAR'] not env.MY_VAR
C. The environment variable was not set correctly; use MY_VAR='hello' without spaces
D. You cannot access environment variables inside script blocks

Solution

  1. Step 1: Check environment block syntax

    In Jenkins Pipeline, environment variables must be assigned with no spaces around = and values in quotes, like MY_VAR='hello'.
  2. Step 2: Identify the syntax error in the snippet

    The snippet uses MY_VAR = 'hello' with spaces around = which is invalid and causes the variable not to be set.
  3. Final Answer:

    The environment block syntax is incorrect; use MY_VAR='hello' with quotes and no spaces around = -> Option A
  4. Quick Check:

    Use no spaces around = in environment block [OK]
Hint: No spaces around = in environment block assignments [OK]
Common Mistakes:
  • Adding spaces around = in environment variable assignment
  • Trying to access env vars incorrectly
  • Assuming script block can't access env vars
5. You want to pass a secret API key stored as an environment variable API_KEY to a shell command in Jenkins Pipeline. Which is the best way to do this securely?
hard
A. Use sh "curl -H 'Authorization: Bearer $API_KEY' https://api.example.com"
B. Use sh(script: "curl -H 'Authorization: Bearer ${env.API_KEY}' https://api.example.com")
C. Use sh(script: "curl -H 'Authorization: Bearer $API_KEY' https://api.example.com", environment: [API_KEY: env.API_KEY])
D. Use Jenkins credentials binding plugin to inject API_KEY and access it as env.API_KEY inside sh

Solution

  1. Step 1: Understand secure handling of secrets in Jenkins

    Secrets like API keys should be stored in Jenkins credentials and injected securely, not hardcoded or exposed in logs.
  2. Step 2: Use credentials binding plugin

    This plugin injects secrets as environment variables during the build, accessible as env.API_KEY inside sh without exposing them in logs.
  3. Final Answer:

    Use Jenkins credentials binding plugin to inject API_KEY and access it as env.API_KEY inside sh -> Option D
  4. Quick Check:

    Use credentials plugin for secrets, not plain env vars [OK]
Hint: Use Jenkins credentials plugin for secrets, not plain env vars [OK]
Common Mistakes:
  • Passing secrets directly in shell commands risking exposure
  • Using string interpolation exposing secrets in logs
  • Not using Jenkins credentials plugin for sensitive data
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard