Passing environment variables in Azure Pipelines allows you to configure your scripts and tasks dynamically. Here’s how you can set and use environment variables in your Azure Pipelines YAML configuration:
Method 1: Define Environment Variables in the YAML Pipeline
You can define environment variables directly in your YAML pipeline. Here’s an example:
trigger:
- main
pool:
vmImage: 'ubuntu-latest'
variables:
MY_VARIABLE: 'Hello, World!'
ANOTHER_VARIABLE: 'Azure DevOps'
steps:
- script: |
echo "Variable 1: $MY_VARIABLE"
echo "Variable 2: $ANOTHER_VARIABLE"
displayName: 'Print Environment Variables'
Explanation
- variables: This section defines environment variables that can be accessed throughout the pipeline.
- script: The script block uses the defined variables. In Bash, you access variables using the
$prefix.
Method 2: Pass Environment Variables to a Script
If you want to pass environment variables specifically to a shell script, you can do so in the script step:
trigger:
- main
pool:
vmImage: 'ubuntu-latest'
steps:
- script: |
export MY_VARIABLE='Hello from script'
./my_script.sh
displayName: 'Run Script with Environment Variable'
In Your Shell Script
In your shell script (my_script.sh), you can access the environment variable like this:
#!/bin/bash
echo "Inside the script: $MY_VARIABLE"
Method 3: Using Pipeline Variables as Environment Variables
You can also pass pipeline variables as environment variables to your scripts:
trigger:
- main
pool:
vmImage: 'ubuntu-latest'
variables:
MY_VARIABLE: 'Hello from Pipeline'
steps:
- script: |
echo "Variable from pipeline: $MY_VARIABLE"
displayName: 'Print Pipeline Variable'
Method 4: Using Azure DevOps Secrets
If you need to pass sensitive information (like API keys), you can use Azure DevOps secrets. Here’s how:
-
Define a Secret: Go to your Azure DevOps project, navigate to "Pipelines" > "Library," and create a new variable group. Add your secret variable and mark it as a secret.
-
Reference the Secret in Your Pipeline:
trigger:
- main
pool:
vmImage: 'ubuntu-latest'
variables:
- group: my-variable-group # Reference the variable group containing secrets
steps:
- script: |
echo "My secret variable: $MY_SECRET_VARIABLE"
displayName: 'Print Secret Variable'
Summary
By using these methods, you can effectively pass and manage environment variables in Azure Pipelines. This allows for greater flexibility and security in your CI/CD processes.
If you have any more questions or need further assistance, feel free to ask!
