Search code examples
azure-devopsyamlazure-yaml-pipelines

How to check if array contains string with Azure DevOps pipeline expressions


I have the following pipeline template that I want to use to conditionally execute stages based on the input parameter stages.

parameters:
- name: dryRun
  default: false
  type: boolean
- name: path
  type: string
  default: terraform
- name: stages
  type: object
  default:
  - test
  - prod

stages:
  - stage:
    pool: 
      vmImage: 'ubuntu-latest'
    displayName: "Deploy to test"
    condition: in('test', ${{ parameters.stages }})
    jobs:
    - template: terraform-job.yaml
      parameters:
        stage: test
        path: ${{ parameters.path }}
        dryRun: ${{ parameters.dryRun }}
  - stage:
    pool: 
      vmImage: 'ubuntu-latest'
    displayName: "Deploy to production"
    condition: in('prod', '${{ join(', ', parameters.stages) }}')
    jobs:
    - template: terraform-job.yaml
      parameters:
        stage: production
        path: ${{ parameters.path }}
        dryRun: ${{ parameters.dryRun }}

In the example you can see two of the approached I tried (I tried a lot...). The last one (in('prod', '${{ join(', ', parameters.stages) }}')) actually compiles but then the check only works partially as the array gets converted into a single string: 'test,prod' which will fail the in('test', 'test,prod') check.

And the first example (in('test', ${{ parameters.stages }})) is the one I think should work with logical thinking but I get the following error when compiling the template: /terraform-deployment.yml (Line: 19, Col: 16): Unable to convert from Array to String. Value: Array.

So now the question:

How do I check if a string is part of an array that was defined as a parameter?


Solution

  • 2022 update

    You can now use containsValue:

    condition: ${{ containsValue(parameters.stages, 'test') }}