How to define variables in YAML?

QuestionsQuestions8 SkillsProYour First Linux LabDec, 05 2025
0269

Defining variables in YAML for Azure Pipelines is straightforward and allows you to manage configuration settings, secrets, and other parameters dynamically. Here’s how to define and use variables in your Azure Pipelines YAML configuration:

1. Basic Variable Definition

You can define variables directly in your YAML pipeline under the variables section. 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 Variables'

Explanation

  • variables: This section is where you define your variables. Each variable is defined as a key-value pair.
  • Accessing Variables: In the script, you can access the variables using the $ prefix (e.g., $MY_VARIABLE).

2. Using Variable Groups

If you have a set of variables that you want to reuse across multiple pipelines, you can create a variable group in Azure DevOps:

  1. Create a Variable Group: Go to your Azure DevOps project, navigate to "Pipelines" > "Library," and create a new variable group. Add your variables there.

  2. Reference the Variable Group in Your Pipeline:

trigger:
- main

pool:
  vmImage: 'ubuntu-latest'

variables:
- group: my-variable-group  # Reference the variable group

steps:
- script: |
    echo "My variable from group: $MY_VARIABLE"
  displayName: 'Print Variable from Group'

3. Defining Environment Variables

You can also define environment variables that can be accessed in your scripts:

trigger:
- main

pool:
  vmImage: 'ubuntu-latest'

variables:
  MY_ENV_VAR: 'Environment Variable Value'

steps:
- script: |
    echo "Environment Variable: $MY_ENV_VAR"
  displayName: 'Print Environment Variable'

4. Using Secrets

If you need to store sensitive information, you can define secret variables in a variable group:

  1. Create a Secret Variable: In the variable group, mark the variable as a secret.

  2. Reference the Secret Variable:

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'

5. Default Variables

Azure DevOps also provides a set of predefined variables that you can use in your pipelines, such as $(Build.BuildId), $(Build.SourceBranch), etc. You can reference these variables directly in your scripts.

Summary

Defining variables in YAML for Azure Pipelines allows you to manage configurations effectively and securely. You can define basic variables, use variable groups for reuse, and handle sensitive information with secret variables.

If you have any more questions or need further assistance, feel free to ask!

0 Comments

no data
Be the first to share your comment!