Bob Tway
Bob Tway

Reputation: 9613

Setting and checking null in Azure Pipeline YAML

I'm trying to add an option to one of our YAML pipelines that allows a user to set which parts of the project will and won't be deployed. To do this, I'm setting variables based on a user's checkbox selection like so:

 variables:
    - template:         variables.yml 
    - name: deliverStageOne
      ${{ if eq(parameters.DeliverStageOne, 'False') }}:
        value: ''
      ${{ if eq(parameters.DeliverStageOne, 'True') }}:
        value: 'STAGE_ONE'

The next part of the process takes all these variables as an array called dbNames and uses a for loop to process each with the same block of code:

steps:
  - ${{ each dbName in parameters.dbNames }}: 
    - ${{ if ne(dbName, '') }}:
      - powershell:               [powershell command]

The trouble I'm having with this is that the conditional inside the above loop never seems to work - it always evaluates to True.

I've tried setting value to x and using

- ${{ if ne(dbName, 'x') }}:

And that evaluates to true, even when I've checked the value of dbName with echo and confirmed that it is x.

So I figured that this was something to do with the way YAML handles strings, and since '' is clumsy syntax anyway, I thought it would be better and clearer to set it to null:

      ${{ if eq(parameters.DeliverStageOne, 'False') }}:
        value: null

Using this in an ne expression results in a compile error:

- ${{ if ne(dbName, null) }}:

And reading the documentation suggests I can just do:

- ${{ if dbName }}:

However, while the above compiles, it continues to treat the null as though it's a string 'null' and falls into th powershell step beneath.

How can I set this up so that YAML recognises that I've created a null value, and checks for it successfully?

Upvotes: 1

Views: 5695

Answers (2)

mrplatina
mrplatina

Reputation: 281

Checking length seems to be the best way to do this, if you try check a parameter on a object you might run into:

Kind 'Null' not supported. Only arrays, strings, dictionaries, or collections are supported for the length function.

The workaround to this is to do a join:

- ${{ if eq(length(join('', dbObject.dbName)), 0) }}:

Upvotes: 1

zionyx
zionyx

Reputation: 2085

For parameters, various data types are supported. See link.

But for variables, they are always of string data type, with or without quotes. In another words, '' is evaluated as an empty string, but not null. See link.

Since all variables are treated as strings in Azure Pipelines, an empty string is equivalent to null in this pipeline.

Instead, try to use this syntax to test if the variable is an empty string in your case:

- ${{ if eq(length(dbName), 0) }}:

Upvotes: 2

Related Questions