Add CORS to Azure function app service with Azure CLI

Adding CORS to an Azure function app sounds easy but when you run it in a pipeline it is a bit more difficult. If you already added the origin to the list, a new entry is added when you run the pipeline for a second time. See this bug report for more information.

Here is a script to check if an origin is already added. If not, add it and otherwise skip the origin.

$FunctionAppName = "foo"
$ResourceGroupName = "bar"

# Configure CORS for Function App
Write-Host "Set CORS in function app"
$allowedOrigins = "https://dev.azure.com","https://localhost:3000"

foreach ($item in $allowedOrigins) {
    Write-Host "Check if allowedorigin '$item' is already set"
    $missesOrigin = az functionapp cors show --name "$FunctionAppName" --resource-group $ResourceGroupName --query "contains(to_string(length(allowedOrigins[?contains(@, '$item')])),'0')"
    if ($missesOrigin -eq "true") {
        Write-Host "Add allowedorigin '$item'"
        az functionapp cors add -n "$FunctionAppName" --allowed-origins $item
    }
    else {
        Write-Host "Allowedorigin '$item' already set"
    }
}