Search code examples
powershellazure-devopsazure-pipelinesspecial-charactersazure-cli

Add value with special characters to the key vault


Currently running a Powershell script in the pipeline to store the Standard Logic App Workflow URL to the Azure key vault. Running in the following issues: My script first calls en saves the result in a variable let's call it $result by using: az rest --method post --uri XXXX

(https://medium.com/@mail4ankitg/get-workflow-trigger-callback-url-in-azure-logic-app-standard-using-powershell-and-azure-cli-5cc7bf983131)

I retrieve the url by storing it in the following variable:

$urlResult = ($result | ConvertFrom-Json).value

The url usually looks something like this:

https://X.appserviceenvironment.net:443/api/NameWorkFlow/triggers/When_a_HTTP_request_is_received/invoke?api-version=2022-05-01&sp=%2Ftriggers%2FWhen_a_HTTP_request_is_received%2Frun&sv=1.0&sig=SIGVALUE

When I now try to add this workflow URL to the key vault:

az keyvault secret set --vault-name $keyVaultName --name "Name" --value $urlResult

My script exits with an error code:

Errors

I tried escaping the urlResult by using:

$escapedUrl = [System.Uri]::EscapeDataString($urlResult)

The script runs this time but in the key vault the following value is added:

https%3A%2F%2FX.appserviceenvironment.net%3A443%2Fapi%2FNameWorkFlow%2Ftriggers%2FWhen_a_HTTP_request_is_received%2Finvoke%3Fapi-version%3D2022-05-01%26sp%3D%252Ftriggers%252FWhen_a_HTTP_request_is_received%252Frun%26sv%3D1.0%26sig%3DSIGVALUE

Lastly I also tried using the '' around the value like:

az keyvault secret set --vault-name $keyVaultName --name "Name" --value '$urlResult'

But this of course only adds "$urlResult" to the key vault.

Currently running out of options, can somebody help?

Mentioned in the post above. Tried 2 approaches but both did not result in the desired result.


Solution

  • Dealing with special characters can be tricky.

    Try outputting the value into a text file, and then creating the secret using the --file option, instead of --value.

    Something like this (not tested):

    $secretFile = "$(Agent.TempDirectory)/secret.txt"
    
    # other commands here
    
    ($result | ConvertFrom-Json).value | Out-File $secretFile -NoNewline
    
    az keyvault secret set --vault-name $keyVaultName --name "Name" --file $secretFile --output none
    
    # files in $(Agent.TempDirectory) are automatically deleted after the pipeline finishes,
    # but better be safe than sorry
    Remove-Item $secretFile -Force
    

    EDIT 1

    It might be required to specify the encoding when generating the text file - e.g. utf8 or utf8NoBOM:

    ($result | ConvertFrom-Json).value | Out-File $secretFile -NoNewline -Encoding utf8NoBOM
    

    And/or setting the secret:

    az keyvault secret set --vault-name $keyVaultName --name "Name" --file $secretFile --encoding utf-8 --output none