How to Use Variables in Azure Pipeline: Simple Guide
In Azure Pipelines, you use
variables to store values that can be reused throughout your pipeline. Define variables in the variables section or inline, then reference them using $(variableName) syntax in your pipeline steps.Syntax
Variables in Azure Pipelines are defined under the variables section. You can assign a value to each variable. To use a variable, reference it with $(variableName) inside your pipeline steps.
Example parts:
- variables: Section where variables are declared.
- variableName: value Assigns a value to a variable.
- $(variableName) References the variable's value.
yaml
variables:
myVar: 'Hello World'
steps:
- script: echo $(myVar)Example
This example shows how to declare a variable and use it in a script step to print its value.
yaml
trigger: - main variables: greeting: 'Hello from Azure Pipelines' pool: vmImage: 'ubuntu-latest' steps: - script: echo $(greeting) displayName: 'Print greeting variable'
Output
Hello from Azure Pipelines
Common Pitfalls
Common mistakes when using variables include:
- Using incorrect syntax like
${variableName}instead of$(variableName). - Trying to use variables before they are defined.
- Not quoting variable values with spaces, which can cause errors.
- Confusing runtime variables with template parameters.
yaml
variables:
message: 'Hello World'
steps:
- script: echo ${message} # Wrong syntax, will not work
- script: echo $(message) # Correct syntaxQuick Reference
| Concept | Syntax | Description |
|---|---|---|
| Define variable | variables: varName: value | Declare variables at the top level. |
| Use variable | $(varName) | Reference variable in steps or scripts. |
| Variable with spaces | varName: 'value with spaces' | Quote values with spaces. |
| Override variable | variables: varName: newValue | Change variable value in different scopes. |
Key Takeaways
Define variables in the variables section using key-value pairs.
Reference variables with $(variableName) syntax inside steps.
Always quote variable values that contain spaces.
Avoid using incorrect syntax like ${variableName}.
Variables help reuse values and make pipelines easier to maintain.