Using Environment Variables in Jenkinsfile

# Using Environment Variables in Jenkinsfile  

Environment variables in Jenkinsfiles help manage configurations dynamically across pipelines. Below are different ways to define and use them, along with key differences:  

---

## **1. Environment Variable Block (Global Scope)**  
Defined at the **pipeline top level**, these variables are **available across all stages**.  

### **Example:**  
```groovy
pipeline {
    agent any
    
    environment {
        GLOBAL_VAR = "value"          // Static value
        BUILD_NUM = "${env.BUILD_ID}" // Jenkins built-in variable
        CREDS = credentials('aws-key') // Secret credential (masked)
    }
    
    stages {
        stage('Example') {
            steps {
                echo "Global var: ${env.GLOBAL_VAR}"
                echo "Build ID: ${env.BUILD_NUM}"
            }
        }
    }
}
```  
### **Key Points:**  
✅ Available in **all stages**.  
✅ Supports **credentials masking** (e.g., `credentials()`).  
❌ Cannot be **modified** after declaration (immutable in `environment` block).  

---

## **2. Environment Variable per Stage (Stage-Specific)**  
Variables defined **inside a stage** are **only available in that stage**.  

### **Example:**  
```groovy
pipeline {
    agent any
    
    stages {
        stage('Stage 1') {
            environment {
                STAGE_VAR = "stage1_value"
            }
            steps {
                echo "Stage var: ${env.STAGE_VAR}"
            }
        }
        
        stage('Stage 2') {
            steps {
                // This will FAIL! STAGE_VAR is not accessible here.
                echo "Trying to access: ${env.STAGE_VAR}"
            }
        }
    }
}
```  
### **Key Points:**  
✅ Useful for **stage-specific configs** (e.g., test env vs. prod env).  
❌ **Not shared** across stages.  

---

## **3. Reusing a Variable Across Stages**  
To **pass a variable from one stage to another**, you must:  
- Use `script { }` block + **`env.VAR_NAME`** (for Jenkins environment variables).  
- Or use **`def` (temporary variable)** but it won’t persist across stages.  

### **Example:**  
```groovy
pipeline {
    agent any
    
    stages {
        stage('Stage A') {
            steps {
                script {
                    env.SHARED_VAR = "data"  // Available in all future stages
                    def tempVar = "temp"     // Only available in this script block
                }
            }
        }
        
        stage('Stage B') {
            steps {
                echo "Shared var: ${env.SHARED_VAR}"  // Works!
                echo "Temp var: ${tempVar}"          // Fails (not defined)
            }
        }
    }
}
```  
### **Key Points:**  
✅ `env.VAR_NAME` persists **globally**.  
❌ `def` variables are **local to the script block**.  

---

## **4. `def` vs `environment` Block Variables**  

| Feature               | `environment { VAR = ... }` | `env.VAR = ...` (script) | `def var = ...` |
|----------------------|----------------------------|--------------------------|----------------|
| **Scope**            | Global (all stages)        | Global (if using `env.`) | Local (script block only) |
| **Modifiable**       | ❌ No (immutable)          | ✅ Yes                   | ✅ Yes         |
| **Credentials**      | ✅ Supports `credentials()` | ✅ Yes                   | ❌ No          |
| **Built-in Jenkins vars** | ✅ `${env.BUILD_ID}` | ✅ `${env.BUILD_ID}` | ❌ No |

### **When to Use Which?**  
- **`environment { }`** → Best for **secrets & global constants**.  
- **`env.VAR = ...`** → Best for **dynamic values shared across stages**.  
- **`def`** → Best for **temporary calculations** (not reusable later).  

---

## **Summary Cheat Sheet**  
| Use Case                          | Recommended Approach          |
|----------------------------------|------------------------------|
| Global config (all stages)       | `environment { }` block      |
| Stage-specific config            | `environment { }` inside stage |
| Dynamic vars across stages       | `script { env.VAR = ... }`   |
| Temporary variables (math, loops)| `def var = ...`              |