CodexBloom - Programming Q&A Platform

PowerShell Script Fails to Trigger CI/CD Pipeline on GitLab with Dynamic Environment Variables

👀 Views: 46 💬 Answers: 1 📅 Created: 2025-09-07
PowerShell GitLab CI/CD

I'm working on a personal project and This might be a silly question, but While refactoring our CI/CD pipeline in GitLab, I encountered a challenge with dynamically setting environment variables in my PowerShell script. The goal is to configure our deployment steps based on the branch being built. I've defined environment variables in the GitLab CI configuration, but they don’t seem to pass correctly to the PowerShell script. Here’s the core part of my GitLab CI configuration: ```yaml variables: STAGING_URL: 'https://staging.example.com' PRODUCTION_URL: 'https://production.example.com' stages: - build - deploy build: script: - echo "Building project..." deploy: script: - pwsh .\deploy.ps1 only: - main ``` In my `deploy.ps1`, I attempt to access these variables like so: ```powershell $environment = $Env:CI_COMMIT_REF_NAME $url = if ($environment -eq 'main') { $Env:PRODUCTION_URL } else { $Env:STAGING_URL } Write-Host "Deploying to $url" ``` Running the pipeline results in: ``` Deploying to ``` The variables seem not to be resolved correctly. I’ve verified that they exist in the pipeline as I can see their values in the CI/CD logs. I've also tried wrapping the variable access in `if` conditions to check if they are null before using them, but that didn’t help. Another approach I considered was using a `script` block to explicitly set these variables within PowerShell: ```powershell $Env:PRODUCTION_URL = 'https://production.example.com' $Env:STAGING_URL = 'https://staging.example.com' ``` Yet, that still leads to an empty value when attempting to echo `$url`. It feels like there’s a scoping issue at play, but I can't seem to pinpoint it. Any insights or recommendations on how to ensure that my PowerShell script correctly retrieves and utilizes these environment variables during the pipeline execution would be greatly appreciated. This is part of a larger web app I'm building. Has anyone else encountered this? What am I doing wrong? This issue appeared after updating to Powershell LTS. Am I missing something obvious?