Search code examples
azure-devopsyamlazure-pipelines

Checking for null object type parameter in Azure YAML


I'm setting up a build template and can't figure out the syntax for an optional object type parameter. In my pipeline I'm calling the template like this:

stages:
- template: aspnet-core.yml@templates
  parameters:
    database:
      name: 'SomeDatabase'
      server: 'SomeServer'

I have the parameter defined like this in the template:

parameters:
  database: null

I want to do a check like this in the template so I can run a task conditionally:

- ${{ if ne('${{ parameters.database }}', null) }}:

However, it's not liking the keyword null in the if statement, and I don't know how to represent the fact that it wasn't passed in. What are my options here?


Solution

  • You can use below expression to check if a parameter is empty. For below example

    - ${{if parameters.database}}:
    

    Below is my testing template and azure-pipeline.yml.

    the script task will only get executed when database is evaluated to true. I tested and found database: "" and database: will be evalutated to false. If it is defined as database: {}, it will be evaluated to true.

    Template: deploy-jobs.yaml

    parameters:
      database: {}
    
    stages:
    - stage: buildstage
      pool: Hosted VS2017
    
      jobs:
      - job: secure_buildjob
        steps:
        - ${{if parameters.database}}:
          - script: echo "will run if database is not empty"
            displayName: 'Base: Pre-build'
    

    azure-pipeline.yml:

    stages:
    - template: deploy-jobs.yaml
      parameters:
        database: ""
    

    To execute some tasks if database is empty you can use below statement:

     steps:
        - ${{if not(parameters.database)}}:
          - script: echo "will run if database is empty"
            displayName: 'Base: Pre-build'