Search code examples
azure-devopsazure-pipelinesazure-pipelines-yaml

Azure DevOps: Is it possible to consume a variable inside a function, inside a template?


My scenario:

azure-pipelines.yml:

variables:
  - name: service
    value: Foo

jobs:
  - job:
    steps:
      - template: consume-variable.yml

consume-variable.yml:

steps:
  - task: Bash@3
    displayName: "Echo $(service) in lowercase"
    inputs:
      targetType: inline
      script: echo ${{ lower(service) }}

What I expect:

The displayName is resolved as Echo Foo in lowercase, and the script as echo foo.

What happens:

The displayName is resolved correctly, but the variable inside the lower() function is not resolved and throws an error.

What I have tried:

It is clear that calling the variable outside a function works, as I can use $(service) by itself anywhere (such as the displayName above). But I cannot figure out if there is a syntax that will resolve correctly inside a function. I have tried all combinations I know of, such as variables.service, variables[service], using [] instead of {{}}, etc.

I know I can pass a parameter to the template and that will resolve correctly. But I specifically want to know if there is a way to use a variable instead of a parameter here.


Solution

  • The variable will not be accessible at the point that the expression is trying to access it. You can get around this by parsing your variable to the template as a parameter, and then referencing the parameter in your template.

    See below example:

    main.yml:

    variables:
    - name: service
      value: Foo
    
    jobs:
    - job:
      steps:
      - template: consume-variable.yml
        parameters:
          service: ${{ variables.service }}
    

    consume.variable.yml:

    parameters:
    - name: service
    
    steps:
    - task: Bash@3
      displayName: "Echo $(service) in lowercase"
      inputs:
        targetType: inline
        script: echo ${{ lower(parameters.service) }}
    

    Output:

    Starting: Echo Foo in lowercase
    ==============================================================================
    Task         : Bash
    Description  : Run a Bash script on macOS, Linux, or Windows
    Version      : 3.231.5
    Author       : Microsoft Corporation
    Help         : https://docs.microsoft.com/azure/devops/pipelines/tasks/utility/bash
    ==============================================================================
    Generating script.
    Script contents:
    echo foo
    ========================== Starting Command Output ===========================
    /usr/bin/bash /home/vsts/work/_temp/ef0ad848-6b0b-4bbd-8601-7e3a200b3091.sh
    foo
    
    Finishing: Echo Foo in lowercase