skip to Main Content

I have a devops pipeline that is designed to do some deployment. Due to some requirements , I need to delete the branch that triggered the pipeline once the deployment is completed. The first approach I thought was using below script snippet is bash/script task:

          git remote remove origin
          
          git remote add origin https://<PAT>@<company_machineName>.visualstudio.com:/<path-to-git-repo>
          
          git push -d origin $branch

The problems with this is the usage of PAT in the authentication step. I don’t want to use it as if the person that owns the PAT leaves the organization , then we have to change this PAT again. Is there any other way to achieve the same ? Can we do the authentication with a service connection

2

Answers


  1. You may use AzureCLI@2 to run az command line through a service connection. Check az repos ref delete subcommand.

    Required Parameters
    –name Name of the reference to delete (example: heads/my_branch).

    Login or Signup to reply.
  2. Instead of service connection, i suggest you to use $(system.accesstoken) which is a DevOps built-in token.

    1. Make sure the build service account has contribute and Force push (rewrite history, delete branches and tags) on the repositories.

    enter image description here

    1. To delete the source branch, you can use azure cli az repos ref delete, you could need to provide ref objectid of the sourcebranch which can get from az repos ref list command.

    For example, i have a CI build as below, i add the deletion task to the end:

    trigger: 
      - main
      - dev1
      - dev2
    
    pool:
      vmImage: ubuntu-latest
    
    steps:
    
    - bash: |
        objectid=$(az repos ref list | jq -r '.[] | select(.name=="$(Build.SourceBranch)") | .objectId')
        echo $objectid
        az repos ref delete --name heads/$(Build.SourceBranchName) --object-id $objectid --detect true --project $(System.TeamProject) --repository $(Build.Repository.Name)
      env:
        AZURE_DEVOPS_EXT_PAT: $(System.AccessToken)
    

    It will delete the source branch dev1 which triggers the build:

    enter image description here

    Please note the build service account could be different due to your project setting, it could be collection-scoped(Project Collection Build Service ({OrgName})) or project-scoped({Project Name} Build Service ({Org Name})) . please refer to the doc for more details, grant repo permission above on correct identity.

    enter image description here

    In addition, above yaml sample is basic build, it could happen the build is triggered by a pull request, other repository…etc, make sure to use correct predefined variables for the parameters of azure cli.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search