Vyas Bharghava
Vyas Bharghava

Reputation: 6510

Howto: Insert a template conditionally in Azure DevOps YAML?

Here's how I'm trying to accomplish inserting a template conditionally. Per requirement, I would like to either call fresh-deploy.yml or update.yml based on a pipeline variable supplied at run time. The user can edit a variable called 'freshInstall' to either true or false.

The main pipeline (entrypoint):

# azure-pipelines.yml
variables:
  shouldUpdate: 'false'

jobs:
  - job: TestJob
    pool:
      name: "Vyas' Local Machine"
    steps:
    - checkout: none
    - template: ./testIf.yml
      parameters:
        freshInstall: $(freshInstall)

The testif.yml:

# testIf.yml
parameters:
  - name: freshInstall
    type: string  # Can't be boolean as runtime supplied variable values ARE strings

steps:

  # set a preexisting variable valued 'false' to 'true'
  - powershell: |
      $shouldUpdate = 'true'
      Write-Host "##vso[task.SetVariable variable=shouldUpdate]$shouldUpdate"
    displayName: 'Set Should Update to $(shouldUpdate)'

  # Check if the parameter 'freshInstall' is passed in correctly
  - script: echo "Should freshInstall ${{ parameters['freshInstall'] }}"
    displayName: 'Is Fresh Install? ${{ parameters.freshInstall }}'

  # Should skip this
  - ${{ if eq(parameters.freshInstall, 'true') }}:
    - template: ./fresh-deploy.yml

  # Shoud include this
  - ${{ if eq(parameters.freshInstall, 'false') }}:
    - template: ./update.yml

  # Check variables vs parameters.  Include as per value set
  - ${{ if eq(variables.shouldUpdate, 'true') }}:
    - template: ./update.yml

  # Use all 3 syntaxes of variable access
  - script: echo "shouldUpdate is variables['shouldUpdate']"
    displayName: "Should Update? variables.shouldUpdate"

The mock file for fresh-deploy.yml:

# fresh-deploy.yml
steps:
  script: echo 'Kick off fresh deploy!'

The mock file for update.yml:

# update.yml
steps:
  script: echo 'Updating existing installation!'

Critical issue: The expectation is that the update.yml template is inserted and the script run when the variable 'freshInstall' is false.

Nice to know: I was also checking if I could somehow get this to work if it were a variable instead of a parameter. It'd be nice if I could be pointed to what I'm doing wrong with the variable displays.

Here's the result: enter image description here

Upvotes: 16

Views: 21546

Answers (2)

Luca Perico
Luca Perico

Reputation: 1425

This solution now works for me:

- ${{ if eq(parameters.generateSwaggerFiles, true) }}:
    - template: generate-swagger-files.yaml
      parameters:
        appName: 'example'
        swaggerVersions:
          - v1
          - v2

Check documentation here.

Upvotes: 23

raviabhiram
raviabhiram

Reputation: 720

I think your problem is now solved since runtime parameters are now allowed to be boolean. Check out Runtime Parameters. I had a similar use case and was able to achieve it using this.

Upvotes: 0

Related Questions