# I can't use environment variables in pipeline using when step

**URL:** <https://community.jenkins.io/t/i-cant-use-environment-variables-in-pipeline-using-when-step/11102>\
**Category:** Jenkinsfile Runner\
**Tags:** question, pipeline\
**Created:** [December 4, 2023, 4:56pm UTC](https://community.jenkins.io/t/i-cant-use-environment-variables-in-pipeline-using-when-step/11102 "2023-12-04T16:56:16Z")\
**Posts on this page:** 4\
**Page:** 1

<div class="post-metadata">

**Author:** ![cruyra](https://dub1.discourse-cdn.com/flex013/user_avatar/community.jenkins.io/cruyra/32/6318_2.png) [@cruyra](https://community.jenkins.io/u/cruyra)\
**Post date:** [December 4, 2023, 4:56pm UTC](https://community.jenkins.io/t/i-cant-use-environment-variables-in-pipeline-using-when-step/11102/1 "2023-12-04T16:56:16Z")

</div>

Hi,

In the following pipeline I need to perform the when depending on the result of a command within a stage.

```auto
pipeline {

    agent { label 'docker' }
    
    stages {
        
        stage("set env EXIST variable"){
            steps{
                container('docker') {
                    script{
                        EXIST = sh(script: "echo 'YES'", , returnStdout: true)
                    }
                }
            }
        } // END stage set env EXIST variable

        stage("control IMAGE"){
            steps{
                sh """
                #!/usr/bin/env bash
                echo "Value stage de EXIST is ${EXIST}"
                """
            }
        } // END stage control IMAGE

        stage("When"){
            when {
                anyOf {
                    **expression { EXIST == "YES" }**
                }
            }
            steps{
                sh """
                echo "IN WHEN with value ${EXIST}"
                """
            }
        } // END stage When
    } // END stages
} // END pipeline`Texto preformateado`

```

Always have the same result

_ **Stage “When” skipped due to when conditional** _

thanks

---

<div class="post-metadata">

**Author:** ![poddingue](https://dub1.discourse-cdn.com/flex013/user_avatar/community.jenkins.io/poddingue/32/985_2.png) [@poddingue](https://community.jenkins.io/u/poddingue)\
**Post date:** [December 14, 2023, 9:20am UTC](https://community.jenkins.io/t/i-cant-use-environment-variables-in-pipeline-using-when-step/11102/2 "2023-12-14T09:20:49Z")

</div>

Hello @cruyra and welcome to this community. 👋

The issue you’re experiencing could be linked to the scope of the `EXIST` variable. In Jenkins Pipeline, each stage has its own scope, and variables defined in one stage are not accessible in another stage.

To make the `EXIST` variable accessible across stages, you can define it at the pipeline level using the `environment` directive. Here’s how you maybe could modify your pipeline:

```auto
pipeline {
    agent { label 'docker' }

    environment {
        EXIST = ""
    }

    stages {
        stage("set env EXIST variable"){
            steps{
                container('docker') {
                    script{
                        env.EXIST = sh(script: "echo 'YES'", , returnStdout: true).trim()
                    }
                }
            }
        } // END stage set env EXIST variable

        stage("control IMAGE"){
            steps{
                sh """
                #!/usr/bin/env bash
                echo "Value stage of EXIST is ${env.EXIST}"
                """
            }
        } // END stage control IMAGE

        stage("When"){
            when {
                expression { env.EXIST == "YES" }
            }
            steps{
                sh """
                echo "IN WHEN with value ${env.EXIST}"
                """
            }
        } // END stage When
    } // END stages
} // END pipeline

```

In this modified pipeline, `EXIST` is defined as an environment variable at the pipeline level, and it’s accessed as `env.EXIST` in the stages. The `trim()` function is used to remove any leading or trailing whitespace from the output of the `sh` step.

---

<div class="post-metadata">

**Author:** ![cruyra](https://dub1.discourse-cdn.com/flex013/user_avatar/community.jenkins.io/cruyra/32/6318_2.png) [@cruyra](https://community.jenkins.io/u/cruyra)\
**Post date:** [January 9, 2024, 6:54am UTC](https://community.jenkins.io/t/i-cant-use-environment-variables-in-pipeline-using-when-step/11102/3 "2024-01-09T06:54:26Z")

</div>

Thank you very much @poddingue, and happy new year.  
I have tried the pipeline and it doesn’t work as expected.  
The environment variable loses its value in the second stage and does not fulfil the expression in the When stage.

```auto
@Library('ci-library') _

pipeline {
    agent { label 'docker' }

    environment {
        EXIST = ""
    }

    stages {
        stage("set env EXIST variable"){
            steps{
                container('docker') {
                    script{
                        env.EXIST = sh(script: "echo 'YES'", , returnStdout: true).trim()
                    }
                }
            }
        } // END stage set env EXIST variable

        stage("control IMAGE"){
            steps{
                sh """
                #!/usr/bin/env bash
                echo "Value stage of EXIST is ${env.EXIST}"
                """
            }
        } // END stage control IMAGE

        stage("When"){
            when {
                expression { env.EXIST == "YES" }
            }
            steps{
                sh """
                echo "IN WHEN with value ${env.EXIST}"
                """
            }
        } // END stage When
    } // END stages
} // END pipeline

```

Result

```auto
Agent docker-agent-smm01 is provisioned from template docker-agent
Running on docker-agent-smm01 in /home/jenkins/agent/workspace/prueba_lectura de ECR
[Pipeline] {
[Pipeline] withEnv
[Pipeline] {
[Pipeline] stage
[Pipeline] { (set env EXIST variable)
[Pipeline] container
[Pipeline] {
[Pipeline] script
[Pipeline] {
[Pipeline] sh
+ echo YES
[Pipeline] }
[Pipeline] // script
[Pipeline] }
[Pipeline] // container
[Pipeline] }
[Pipeline] // stage
[Pipeline] stage
[Pipeline] { (control IMAGE)
[Pipeline] sh
+ echo Value stage of EXIST is null
Value stage of EXIST is null
[Pipeline] }
[Pipeline] // stage
[Pipeline] stage
[Pipeline] { (When)
Stage "When" skipped due to when conditional
[Pipeline] }
[Pipeline] // stage
[Pipeline] }
[Pipeline] // withEnv
[Pipeline] }
[Pipeline] // node
[Pipeline] End of Pipeline
Finished: SUCCESS

```

---

<div class="post-metadata">

**Author:** ![cruyra](https://dub1.discourse-cdn.com/flex013/user_avatar/community.jenkins.io/cruyra/32/6318_2.png) [@cruyra](https://community.jenkins.io/u/cruyra)\
**Post date:** [January 9, 2024, 7:11am UTC](https://community.jenkins.io/t/i-cant-use-environment-variables-in-pipeline-using-when-step/11102/4 "2024-01-09T07:11:43Z")

</div>

if I use this pipeline  
I have the variables but it doesn’t fit in the When  
I don’t know if the conditional expression is correct.

```auto
@Library('ci-library') _

pipeline {

    agent { label 'docker' }
    
    stages {
        
        stage("set env EXISTE variable"){
            steps{
                container('docker') {
                    script{
                        EXISTE = sh(script: "echo 'YES'", , returnStdout: true)
                    }
                }
            }
        } // END stage set env EXISTE variable

        stage("control IMAGE"){
            steps{
                sh """
                #!/usr/bin/env bash
                echo "El valor en el stage de EXISTE es ${EXISTE}"
                """
            }
        } // END stage control IMAGE

        stage("When"){
// when {
// anyOf {
// expression { EXISTE == "YES" }
// }
// }
            steps{
                sh """
                echo "ENTRA EL WHEN con el valor ${EXISTE}"
                """
            }
        } // END stage When
    } // END stages
} // END pipeline

```

Result

```auto
Agent docker-agent-1ns0g is provisioned from template docker-agent
Running on docker-agent-1ns0g in /home/jenkins/agent/workspace/prueba_lectura de ECR
[Pipeline] {
[Pipeline] stage
[Pipeline] { (set env EXISTE variable)
[Pipeline] container
[Pipeline] {
[Pipeline] script
[Pipeline] {
[Pipeline] sh
+ echo YES
[Pipeline] }
[Pipeline] // script
[Pipeline] }
[Pipeline] // container
[Pipeline] }
[Pipeline] // stage
[Pipeline] stage
[Pipeline] { (control IMAGE)
[Pipeline] sh
+ echo El valor en el stage de EXISTE es YES

El valor en el stage de EXISTE es YES

[Pipeline] }
[Pipeline] // stage
[Pipeline] stage
[Pipeline] { (When)
[Pipeline] sh
+ echo ENTRA EL WHEN con el valor YES

ENTRA EL WHEN con el valor YES

[Pipeline] }
[Pipeline] // stage
[Pipeline] }
[Pipeline] // node
[Pipeline] End of Pipeline
Finished: SUCCESS

```
