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

Agent variable is not resolved in 'if' condition in deployment job in template


Agent.MachineName variable is not resolved in 'if' condition in self-hosted deployment job template.

${{ if eq(s_t.resource, 'VM000000001') }}:

works fine, but

${{ if eq(s_t.resource, variables['Agent.MachineName']) }}:

does not work.

The template:

parameters:
- name: stage_name
  type: string
- name: azure_environment
  type: string
- name: depends_on_stage
  type: string
- name: startup_types
  type: object

# Usage:
# ...    
# startup_types:
# - resource: VM000000001
#   startup_type: Manual
#   start_service: false
# - resource: VM000000002
#   startup_type: Manual
#   start_service: false

stages:
- stage: ${{ parameters.stage_name }}
  dependsOn: ${{ parameters.depends_on_stage }}
  jobs:
  - deployment: ${{ parameters.stage_name }}
    workspace:
      clean: all
    environment: 
      name: ${{ parameters.azure_environment }}
      resourceType: VirtualMachine
    variables:
      ${{ each s_t in parameters.startup_types }}:
        # ${{ if eq(s_t.resource, variables['Agent.MachineName']) }}: # <=== Not working
        ${{ if eq(s_t.resource, 'VM000000001') }}:
          startup_type_resource: ${{ s_t.resource }}
          startup_type: ${{ s_t.startup_type }}
          start_service: ${{ s_t.start_service }}
    strategy:
      ...

With the nested each-if expression my intention is to select the startup type that belongs to the actual deployment agent.


Solution

  • The template expression "${{ xxxx }}" is evaluated at compile-time before runtime. However, not all the predefined variables are available in template expression. Because some predefined variables are evaluated are runtime.

    See "Template expressions".

    enter image description here

    In the documentation "Use predefined variables", only the predefined variables which are stated as "Yes" for "Available in templates?" can be available in template expression.

    enter image description here

    If the predefined variables are stated as "No" for "Available in templates?", or not stated, they are not available in template expression.

    enter image description here