Search code examples
azure-devopsazure-pipelinesazure-devops-rest-api

Is there a way to upload secure files to azure devops library automatically?


I'm trying to upload keys to azure devops as secure files to use in pipeline context, I only found manual upload but it is not option, Is there a way it can be automated thorough powershell or any pipeline tasks? please suggest.


Solution

  • You can use REST API to do this:

    POST https://dev.azure.com/{organization}/{project}/_apis/distributedtask/securefiles?api-version=5.0-preview.1&name={fileName}
    
    Content-Type=application/octet-stream
    

    Please check this topic on GitHUb.

    You will find there even powershell script:

    param
    (
        [Parameter(Mandatory=$true)] [string] $PAT,
        [Parameter(Mandatory=$True)][ValidateNotNullOrEmpty()]$AzureDevOpsOrg,
        [Parameter(Mandatory=$True)][ValidateNotNullOrEmpty()]$AzureDevOpsProjectID,
        [Parameter(Mandatory=$true)] [string] $SecureNameFile2Upload,
        [Parameter(Mandatory=$true)] [string] $SecureNameFilePath2Upload
    )
    
    try{
        $base64AuthInfo=[Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f "",$PAT)))
        $uploadSecureFileURI="https://dev.azure.com/$AzureDevOpsOrg/$AzureDevOpsProjectID/_apis/distributedtask/securefiles?api-version=5.0-preview.1&name=$SecureNameFile2Upload"
        $headers = @{
            Authorization=("Basic {0}" -f $base64AuthInfo)
        }
        Invoke-RestMethod -Uri $uploadSecureFileURI -Method Post -ContentType "application/octet-stream" -Headers $headers -InFile "$SecureNameFilePath2Upload"
    }
    catch
    {
        write-host -f Red "Error upload client certificate file [$SecureNameFilePath2Upload] to AzureDevOps secure file!" $_.Exception.Message
        throw "Error occors -> $_.Exception.Message"
    }