Search code examples
azureazure-pipelinespipeline

Reading env variable from template.yaml


We need a help

We are trying to centralize our environment variables,

Name of the pipeline is "mytap-test"

my vars.yaml template contains:

variables:
- name: mytap-test
  value: 22

my pipeline.yaml template contains:

trigger: none

resources:
  repositories:
    - repository: Templates
      type: git
      name: DevSecOps/DevSecOps

variables:
- template: UTAP/Library/vars.yaml@Templates

stages:
  - stage: pull_image
    pool:
      name: LinuxJavaCIBuildAgents
    jobs:
      - job: pull_image
        workspace:
          clean: all
        steps:
        - script: |
            echo "##vso[task.setvariable variable=docker_version;]$(mytap-test)"
            echo ${docker_version}
          displayName: get version

docker_version must be equal to a version assigned to mytap-test from vars.yaml, so the echo ${docker_version} will return 22

BUT here is a challenge

I don't want to rely on the static name when running echo "##vso[task.setvariable variable=docker_version;]$(mytap-test)" INSTEAD I want to use the name of the pipeline that is easily accessible by calling $(Build.DefinitionName)

Please help!


Solution

  • I want to use $(Build.DefinitionName) instead of $(mytap-test), it doesn't work, it returns the name of pipeline instead of a version 22

    To meet your requirement, you need to nested variable to get the correct value. For example: $(${{variables['Build.DefinitionName']}})

    echo "##vso[task.setvariable variable=docker_version;]$(${{variables['Build.DefinitionName']}})"
    

    Here is YAML example:

    trigger: none
    
    resources:
      repositories:
        - repository: Templates
          type: git
          name: DevSecOps/DevSecOps
    
    variables:
    - template: UTAP/Library/vars.yaml@Templates
    
    stages:
      - stage: pull_image
        pool:
          name: LinuxJavaCIBuildAgents
        jobs:
          - job: pull_image
            workspace:
              clean: all
            steps:
            - script: |
                echo "##vso[task.setvariable variable=docker_version;]$(${{variables['Build.DefinitionName']}})"
              displayName: get version
            - script: |
                echo $(docker_version)
              displayName: get version
    

    Note: Since you are using logging command to set variable in pipeline, the new variable: docker_version will not work on the current task, but the variable value can be used in the next tasks.

    Refer to this doc: Set variables in scripts

    A script in your pipeline can define a variable so that it can be consumed by one of the subsequent steps in the pipeline.Set variables in scripts

    Result:

    enter image description here