Set dependsOn to previous stage without hardcoding the value in Azure Pipelines

An if condition to check whether the depends_on parameter is empty while also setting the parameter default to “” allowed me to workaround this issue allowing me to set the depends_on parameter for the first DEV deploy stage while not setting it for the others.

As @Krzysztof Madej stated in his answer/comments, no such variable exists to set the previous stage for dependsOn but will automatically depend on the previous stage if not set.

# azure-pipelines.yml

# LINES REMOVED #

stages:
  # Terraform Plan (DevTest)
  - template: templates/plan.yml
    parameters:
      az_service_connection: DevTest-Terraform
      environment: DevTest

  # Terraform Plan (Stage)
  - template: templates/plan.yml
    parameters:
      az_service_connection: Stage-Terraform
      environment: Stage

  # Terraform Plan (Prod)
  - template: templates/plan.yml
    parameters:
      az_service_connection: Prod-Terraform
      environment: Prod

  # Terraform Deploy (DevTest)
  - template: templates/deploy.yml
    parameters:
      az_service_connection: DevTest-Terraform
      depends_on:
        - DevTest_Plan
        - Stage_Plan
        - Prod_Plan
      environment: DevTest

  # Terraform Deploy (Stage)
  - template: templates/deploy.yml
    parameters:
      az_service_connection: Stage-Terraform
      environment: Stage

  # Terraform Deploy (Prod)
  - template: templates/deploy.yml
    parameters:
      az_service_connection: Prod-Terraform
      environment: Prod

# templates/deploy.yml

parameters:
  - name: az_service_connection
    type: string
  - name: depends_on
    type: object
    default:
  - name: environment
    type: string

stages:
  # Terraform Deploy
  - stage: ${{ parameters.environment }}_Deploy
    displayName: Terraform Deploy (${{ parameters.environment }})
    condition: and(succeeded(), in(variables['Build.Reason'], 'IndividualCI', 'BatchedCI', 'Manual'))
    ${{ if ne(length(parameters.depends_on), 0) }}:
      dependsOn:
        ${{ parameters.depends_on }}

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top