'Condition in yaml pipeline doesnt work when selecting template reference

I am trying to use conditions in azure pipelines, when using it with condition: for step it works fine, but when trying to put the same condition with if it doesn't work and always executes code from else block.

jobs:
- job:
  timeoutInMinutes: 100
  cancelTimeoutInMinutes: 10
  strategy:
   matrix:
    AAA_1:
      build: "dev"
    BBB_1:
      build: "release"
    BBB_2:
      build: "rc-1"
 steps:
 - checkout: repo-to-checkout
   fetchDepth: 1
   path: s/path-to-checkout
   clean: true
   condition: startsWith(variables['Agent.JobName'], 'BBB_')  #works here

 - ${{ if startsWith(variables['Agent.JobName'], 'BBB_') }}:  #doesnt work here, always go to else block
   - template: build-template.yml@templates
     parameters:
      param1: $(build)
 - ${{ else }}:
   - template: build-another-template.yml@templates
     parameters:
      param1: $(build)

I also tried with ${{ if startsWith('$(Agent.JobName)', 'BBB_') }}: but it always executes the code from else block.



Solution 1:[1]

I'm afraid that agents variables are not available for template expressions. I could not find that in documentation but this should prove that statement:

- job: PipelineVariablesViaExpression
  strategy:
    matrix:
      linux:
        imageName: 'ubuntu-latest'
      mac:
        imageName: 'macOS-latest'
      windows:
        imageName: 'windows-latest'
  steps:
  - pwsh: Write-Host "${{ convertToJson(variables) }}"
    displayName: 'Print all variables via expression'

And then I got:

{
   system: build,
  system.hosttype: build,
  system.servertype: Hosted,
  system.pipelineStartTime: 2021-09-22 18:28:06+00:00,
  system.teamProject: DevOps Dojo,
  system.teamProjectId: c0a01e9c-d88c-419c-b063-1e0958c965ed,
  system.definitionId: 276,
  build.definitionName: Display pipeline variables,
  build.definitionVersion: 2,
  build.queuedBy: Krzysztof Madej,
  build.queuedById: daec281a-9c41-4c66-91b0-8146285ccdcb,
  build.requestedFor: Krzysztof Madej,
  build.requestedForId: daec281a-9c41-4c66-91b0-8146285ccdcb,
  build.requestedForEmail: [email protected],
  build.sourceVersion: 65adfe640db9439312b6354f13b51eceacc2b22a,
  build.sourceBranch: refs/heads/main,
  build.sourceBranchName: main,
  build.reason: Manual,
  system.pullRequest.isFork: False,
  system.jobParallelismTag: Public,
  system.enableAccessToken: SecretVariable,
  DB_HOSTNAME: 10.123.56.222,
  DB_PORTNUMBER: 1521,
  USERNAME: TEST,
  PASSWORD: TEST,
  SCHEMANAME: SCHEMA,
  ACTIVEMQNAME: 10.123.56.223,
  ACTIVEMQPORT: 8161
}

For instance on build variables you have information about this:

enter image description here

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Krzysztof Madej