Search code examples
azure-devopsazure-pipelinesazure-pipelines-release-pipeline

Override manual Post Deploy Approval in DevOps from within a Release Stage


At the company I work at we use manual post-deploy approvals for deployments in each stage but we'd like to be able to automatically approve a deployment under certain conditions. Updating approvals works great by using 'release/approvals' service of the Devops API but this does not work from within the stage because no approval exists prior to the stage has finished completely.

Are there ways to accomplish this?


Solution

  • I'm afraid there is no default feature that can meet your needs. As a workaround, you can create a new pipeline to approve your stage using REST API Approvals - Update and trigger this pipeline via a webhook when the statue of the deployment is PartiallySucceeded.

    1. Create a webhook and an "Incoming Webhook" service connection.

      To create a webhook, please go to Project Settings -> Service hooks.

    • Trigger on this type of event: Release deployment approval pending
    • Release pipeline name: Your target release pipeline
    • Stage name: The stage used for deployment
    • Approval type: Post-deployment

    enter image description here

    Follow the detailed steps from Generic webhook based triggers for YAML pipelines to finish the following steps and create an "Incoming Webhook" service connection.

    1. Create a yaml pipeline to run REST API Approvals - Update to approve your stage.
        trigger:
          - none
        
        resources:
          webhooks:
            - webhook: pendingapprove          ### Webhook name
              connection: approveSC    ### Incoming webhook service connection name
              filters:
                - path: resource.deployment.operationStatus      ### JSON path in the payload
                  value: PhasePartiallySucceeded 
        
        pool:
          vmImage: windows-latest
        
        steps:
        - task: PowerShell@2
          inputs:
            targetType: 'inline'
            script: |
              $headers = New-Object "System.Collections.Generic.Dictionary[[String],[String]]"
              $headers.Add("Content-Type", "application/json")
              $headers.Add("Authorization", "Basic {PAT}")
              $url = "https://vsrm.dev.azure.com/{Org name}/{Project name}/_apis/release/approvals/${{parameters.pendingapprove.resource.approval.id}}?api-version=7.1-preview.3"
              $body = @"
              {
              `"status`": `"approved`",
              `"comments`": `"Good to go!`"
              }
              "@
              $response = Invoke-RestMethod -Uri $url -Method 'PATCH' -Headers $headers -Body $body
    
    

    You can get the approvalId from parameters.{webhook name}.resource.approval.id.