Search code examples
azure-devops

Azure Pipeline: how to delete a variable inside Azure build pipeline


Currently we are migrating from XAML to Azure Pipelines. To prevent identical buildnumbers we are using a special variable for initialising the build number for the first migrated build definition. After the first build, the variable is obsolete and can be deleted inside the build. How to do this in Powershell?


Solution

  • How to do this in Powershell?

    It seems that you want to delete/remove unwanted build pipeline variable(Classic build pipeline?) via powershell task, you can use Definitions-Update rest api.

    PUT https://dev.azure.com/{organization}/{project}/_apis/build/definitions/{definitionId}?api-version=5.1
    

    Here's my working sample to delete the variable via PowerShell task inside the build:

    $url = "$($env:SYSTEM_TEAMFOUNDATIONSERVERURI)$env:SYSTEM_TEAMPROJECTID/_apis/build/definitions/$($env:SYSTEM_DEFINITIONID)?api-version=5.1"
    
    $response = Invoke-RestMethod -Uri $url -Method Get -Headers @{
        Authorization = "Bearer $env:SYSTEM_ACCESSTOKEN"
    }
    
    # Remove the variable you don't like.
    $response.variables.PSObject.Properties.Remove('InvalidVariable')
    
    $json = @($response) | ConvertTo-Json -Depth 99
    Invoke-RestMethod -Uri $url -Method Put -Body $json -ContentType "application/json" -Headers @{Authorization = "Bearer $env:SYSTEM_ACCESSTOKEN"}
    

    Step1: Make sure the job which contains the Powershell task allow scripts to access the OAuth token cause my script uses OAuth token instead of PAT to call rest api. (Click Agent Job Name=>Additional options)

    enter image description here

    Step2: Find your pipelines page and manage security for the specific build pipeline, Allow the Edit Build Pipeline for ProjectName Build Service(OrgName) user. (It it doesn't work, try allowing permission for Project Collection Build Service account)

    enter image description here

    enter image description here

    3.Use a normal Powershell task in Inline script mode to run my script above. All you need to modify is the variable name. If the Variable's name is MyVar, then $response.variables.PSObject.Properties.Remove('MyVar').

    Above script gets the Definition first and then remove the unwanted variable, finally update the build pipeline definitions with Definitions-Update rest api.

    Before running the PS task:

    enter image description here

    After running the PS task:

    enter image description here

    Unwanted variable would be removed.