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

2

6

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?

Sadiras answered 17/8, 2020 at 15:56 Comment(0)
G
11

2022 update

You can now use containsValue:

condition: ${{ containsValue(parameters.stages, 'test') }}
Gal answered 7/2, 2022 at 20:48 Comment(1)
beware containsValue is case-insensitiveOffing
H
6

Try contains instead:

condition: contains('${{ join(';',parameters.stages) }}', 'test')

Hysteria answered 18/8, 2020 at 9:30 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.