Disable AFD Backend Pool's Backend Host with Azure Cli or Azure REST API - azure

Im trying to update an existing backend host of a AFD backend pool to have its status from Enabled to Disabled.
Is there a way to update existing backend host of Front Door backend pools?
currently, i can only see add, list and remove in the following azure front door cli docs:
az network front-door backend-pool backend add
az network front-door backend-pool backend list
az network front-door backend-pool backend remove
Is there one for update?
I've also looked into the Azure REST API docs and have not found an endpoint to update a backend host of AFD backend pools.

I am able to achieve your ask using PowerShell.
Here is the script:
$resourceGroup1 = "frontdoor"
$frontDoor1 = "msrini"
$afd = Get-AzFrontDoor -ResourceGroupName $resourceGroup1 -name $frontDoor1
$loadBalancingSetting1=$afd.LoadBalancingSettings
$afd.BackendPools.backends[0].EnabledState = "Disabled"
$backendpool1=$afd.BackendPools
$frontendEndpoint1 = $afd.FrontendEndpoints
$healthProbeSetting1= $afd.HealthProbeSettings
$routingrule1 = $afd.RoutingRules
$backendpoolsettings1 = $afd.BackendPoolsSetting
Set-AzFrontDoor -Name $frontDoor1 -ResourceGroupName $resourceGroup1 -RoutingRule $routingrule1 -BackendPool $backendpool1 -FrontendEndpoint $frontendEndpoint1 -LoadBalancingSetting $loadBalancingSetting1 -HealthProbeSetting $healthProbeSetting1 -BackendPoolsSetting $backendpoolsettings1

I was able to resolve my issue, the below script requires using azure cli with a logged in service principle.
Param(
[string]$desiredState, #"Enabled" or "Disabled"
[string]$frontDoorName,
[string]$resourceGroupName,
[string]$targetBackendPool,
[string]$targetBackendHost
)
# Get Access Token
$token = az account get-access-token | ConvertFrom-Json
$accessToken = $token.accessToken
$subscriptionId = $token.subscription
$tenantId = $token.tenant
$uri = "https://management.azure.com/subscriptions/$($subscriptionId)/resourceGroups/$($resourceGroupName)/providers/Microsoft.Network/frontDoors/$($frontDoorName)?api-version=2019-05-01"
$headers = #{ "Authorization" = "Bearer $accessToken" }
$contentType = "application/json"
# Get AFD Configuration.
Write-Host "Invoking Azure REST API to get AFD configuration"
$afdConfig = Invoke-WebRequest -method get -uri $uri -headers $headers | ConvertFrom-Json
# Edit AFD Configuration to toggle backend host state
Write-Host "Checking BackendHost: $targetBackendHost In Backend Pool: $targetBackendPool"
foreach ($backendPool in $afdConfig.properties.backendPools) {
if ($backendPool.name -eq $targetBackendPool) {
foreach ($backends in $backendPool.properties.backends) {
if ($backends.address -eq $targetBackendHost) {
$currentState = $backends.enabledState
Write-Host "Current State of $targetBackendHost is $currentState"
if ($currentState -eq $desiredState) {
Write-Host "$targetBackendHost is already in the desired state of $desiredState"
exit
}
$backends.enabledState = $desiredState
Write-Host "$targetBackendHost Updated to $desiredState."
}
}
}
}
$updateRequest = $afdConfig | ConvertTo-Json -Depth 100
# Update AFD Configuration.
Write-Host "Invoking Azure REST API to update AFD configuration"
Invoke-WebRequest -method put -uri $uri -headers $headers -ContentType $contentType -body $updateRequest
# Poll current state until the change has been fully propogated in azure
Write-Host "Polling AFD until update is complete."
do {
$afdConfig = Invoke-WebRequest -method get -uri $uri -headers $headers | ConvertFrom-Json
foreach ($backendPool in $afdConfig.properties.backendPools) {
if ($backendPool.name -eq $targetBackendPool) {
foreach ($backends in $backendPool.properties.backends) {
if ($backends.address -eq $targetBackendHost) {
$currentState = $backends.enabledState
}
}
}
}
Write-Host "$targetBackendHost is currently in $currentState"
Start-Sleep -Seconds 1
} until ($currentState -eq $desiredState)
Write-Host "$targetBackendHost has successfully been updated to $desiredState"

I did it using Powershell
$FrontDoor = Get-AzFrontDoor -ResourceGroupName "FrontDoorResourceGroupName" -Name "FrontDoorName"
$FrontDoor.BackendPools.Backends[0].EnabledState = "Disabled"
Set-AzFrontDoor -InputObject $FrontDoor

Related

Export all API names Azure APIM

I am trying to export all the url endpoints of my APIs which are stored in Azure APIM.
I need them listed in the format [POST]: https://apim-resource-name.azure-api.net/api-name/api-function, or something similar, so I am trying to enumerate all the endpoints first and the VERB that can be used much like what SwaggerUI or one of the OpenAPI docs might show.
I have this code so far but cannot get the output I would like, am I on the right track or is there any easier way to do this even via UI? I have also tried exporting the template and parsing the script, but it seemed overly complicated for this task.
#az login
$token = az account get-access-token | ConvertFrom-Json
$token = $token.accessToken -replace "`n","" -replace "`r",""
$headers = #{Authorization="Bearer $token.accessToken"}
$subscriptionId = 'subscriptionid'
$resourceGroupName = 'resourcegroupname'
$resourceName = 'resourcename'
$apiName = 'apiname'
$url_getapiexport = "https://management.azure.com/subscriptions/$subscriptionId/resourceGroups/$resourceGroupName/providers/Microsoft.ApiManagement/service/$resourceName/apis/$apiName`?format=swagger-link&export=true&api-version=2021-08-01" #GET
$url_getapiexport
#Invoke-RestMethod -Uri $url_getapiexport -Method GET -Headers #{Authorization="Bearer $token"} -ContentType "application/json"
$url_getapibytags = "https://management.azure.com/subscriptions/$subscriptionId/resourceGroups/$resourceGroupName/providers/Microsoft.ApiManagement/service/$resourceName/apisByTags?&includeNotTaggedApis=true&api-version=2021-08-01" #GET
$url_getapibytags
$api_tags = Invoke-RestMethod -Uri $url_getapibytags -Method GET -Headers #{Authorization="Bearer $token"} -ContentType "application/json"
$api_tags
foreach ($api in $api_tags) {
write-host API: $api.value.api.name
}
So if you want to export all APIM APIs and their service URLs you can do like this (replace xxx with correct values). Example in PHP
<?php
echo "[INFO] API Names and Service Urls \n\n";
$apiList = shell_exec('az apim api list --resource-group "xxx" --service-name "xxx" ');
$apis = json_decode($apiList, true);
$cli = "az rest --method get --url";
foreach ($apis as $api)
{
$name = $api["name"];
$apiRequest = "$cli " . "\"https://management.azure.com/subscriptions/xxx/resourceGroups/xxx/providers/Microsoft.ApiManagement/service/xxx/apis/$name?api-version=2021-08-01\"";
$json = shell_exec($apiRequest);
$apiInfo = json_decode($json, true);
$displayName = $apiInfo["properties"]["displayName"];
$serviceUrl = $apiInfo["properties"]["serviceUrl"];
printf("%s: %s \n", $displayName, $serviceUrl);
}
?>

Can we add label to tiles on Azure Dashboard [duplicate]

Is it possible to show custom information in azure dashboards?
I was searching on how to add custom content in azure dashboards but did not find anything. The only thing close was the markdown tile which allows html to be displayed.
With this in mind and after a lot of digging I found a solution:
Basically we needed a custom tile that displays data retrieved from our REST api.
1. Create a new, empty 'Markdown' tile on a new or existing dashboard, give it a 'Title'
2. Share the dashboard
3. Navigate to All services, Filter by 'dashboards' in the ResourceGroup filter
- Click on the dashboard which contains the 'Markdown' tile
- Take a note of the 'RESOURCE ID'
In our scenario, we used Azure Automation Runbooks. In this scenario we utilized the Azure Resource Manager REST api.
4. Create a new RunBook [Powershell Runbook]
The following steps concern the following:
- Login to the ResourceManagerAPI
- Get Azure Resource by ID [The Resource ID above]
- Update Azure Resource by ID [The Resource ID above]
Before we continue, we need to get our client credentials. To do so:
- Click on Cloud Shell in the Portal Menu bar
- Type 'az'
- Type 'az ad sp create-for-rpac -n "runbooks"' //runbooks is just a name, feel free to input a different string
- The above command should list out the credentials needed. If an error occurs, kindly contact your Azure admin and run it from their account.
5. In your empty powershell runbook, add the following 2 variables:
$ExpectedTileName = "Extension/HubsExtension/PartType/MarkdownPart"
$MarkdownTileTitle = "<The Markdown title you've set in the first step>"
6. Getting the Access_Token [The variables <> represent the values retrieved from the previous step]
#Get Bearer Token
$TenantId = '<Your tenantID>'
$LoginUri = "https://login.microsoftonline.com/"+$TenantId+"/oauth2/token"
$params = #{
"grant_type"="client_credentials";
"client_id"="<appId>";
"client_secret"="<password>";
"resource"="https://management.azure.com";
}
$LoginResponse = Invoke-RestMethod -Uri $LoginUri -Method Post -Body $params
$Access_Token = $LoginResponse.access_token;
$Access_TokenString = "Bearer " + $Access_Token
7. Getting the DashboardResource by ResourceID:
#Get Resource
$RMUri = "https://management.azure.com/"+ $DashboardId +"?api-version=2015-08-01-preview"
$DashboardResource = (Invoke-RestMethod -Uri $RMUri -Method Get -Headers #{'Authorization'=$Access_TokenString}) | ConvertTo-Json -Depth 100 | ConvertFrom-Json
8. Looping through all tiles within the dashboard. Please note that tiles are not contained within an array, thus you may need to increase/decrease the length of the for loop.
#Loop through all tiles within the dashboard
$Parts = $DashboardResource.properties.lenses.0.0.parts
For ($i=0; $i -lt 200; $i++)
{
$Part = $Parts | Select-Object -Property $i.toString()
if($Part.$i)
{
if($Part.$i.metadata.type -eq $ExpectedTileName -And $Part.$i.metadata.settings.content.settings.title -eq $MarkdownTileTitle)
{
$Part.$i.metadata.settings.content.settings.content = <CustomValue ex: invoke a get request to your api>
}
}
else
{
break
}
}
9. Finally we need to update the dashboard resource
#Update Resource
$UpdateUri = "https://management.azure.com/"+ $DashboardId +"?api-version=2015-08-01-preview"
$JsonValue = $DashboardResource | ConvertTo-Json -Depth 100
Invoke-RestMethod -Uri $UpdateUri -Method Put -Headers #{'Authorization'=$Access_TokenString; 'Content-type'='application/json'} -Body $JsonValue
To sum it up:
$ExpectedTileName = "Extension/HubsExtension/PartType/MarkdownPart"
$MarkdownTileTitle = "<The Markdown title you've set in the first step>"
#Get Bearer Token
$TenantId = '<Your subscriptionID>'
$LoginUri = "https://login.microsoftonline.com/"+$TenantId+"/oauth2/token"
$params = #{
"grant_type"="client_credentials";
"client_id"="<appId>";
"client_secret"="<password>";
"resource"="https://management.azure.com";
}
$LoginResponse = Invoke-RestMethod -Uri $LoginUri -Method Post -Body $params
$Access_Token = $LoginResponse.access_token;
$Access_TokenString = "Bearer " + $Access_Token
#Get Resource
$RMUri = "https://management.azure.com/"+ $DashboardId +"?api-version=2015-08-01-preview"
$DashboardResource = (Invoke-RestMethod -Uri $RMUri -Method Get -Headers #{'Authorization'=$Access_TokenString}) | ConvertTo-Json -Depth 100 | ConvertFrom-Json
#Loop through all tiles within the dashboard
$Parts = $DashboardResource.properties.lenses.0.0.parts
For ($i=0; $i -lt 200; $i++)
{
$Part = $Parts | Select-Object -Property $i.toString()
if($Part.$i)
{
if($Part.$i.metadata.type -eq $ExpectedTileName -And $Part.$i.metadata.settings.content.settings.title -eq $MarkdownTileTitle)
{
$Part.$i.metadata.settings.content.settings.content = <CustomValue ex: invoke a get request to your api>
}
}
else
{
break
}
}
#Update Resource
$UpdateUri = "https://management.azure.com/"+ $DashboardId +"?api-version=2015-08-01-preview"
$JsonValue = $DashboardResource | ConvertTo-Json -Depth 100
Invoke-RestMethod -Uri $UpdateUri -Method Put -Headers #{'Authorization'=$Access_TokenString; 'Content-type'='application/json'} -Body $JsonValue
Conclusion
With this newly created runbook we can now schedule it to run every 1 hour. In our case, 1 hour was too much. The following article shows how we can schedule the runbook to run every 1 minute.
https://blogs.technet.microsoft.com/stefan_stranger/2017/06/21/azure-scheduler-schedule-your-runbooks-more-often-than-every-hour/

How to make an Azure app registration with platform SPA via Powershell

We use PowerShell to set up an Azure deployment, which, among other Azure resources, creates an app registration.
The simplified code is as follows:
$appRegistration = New-AzADApplication `
-DisplayName $applicationName `
-HomePage "$webAppUrl" `
-IdentifierUris "api://$webAppName";
To it, we add redirect uris, like this:
if ($redirectUris -notcontains "$webAppUrl") {
$redirectUris.Add("$webAppUrl");
Write-Host "Adding $webAppUrl to redirect URIs";
}
if ($redirectUris -notcontains "$webAppUrl/aad-auth") {
$redirectUris.Add("$webAppUrl/aad-auth");
Write-Host "Adding $webAppUrl/aad-auth to redirect URIs";
}
Update-AzADApplication `
-ApplicationId $applicationId `
-IdentifierUris "api://$applicationId" `
-ReplyUrl $redirectUris | Out-Null
This works great, and an app registration with the "web" platform is created. It looks like this:
My question is how can we get these redirect uris to be under the "SPA" platform, using PowerShell? Like in the image below, which was done manually on the Portal.
Looks there is no feature in the built-in command to do that, you could call the MS Graph - Update application in the powershell directly.
You could refer to the sample below work for me, make sure your service principal/user acount logged in Az via Connect-AzAccount has the permission to call the API.
$objectId = "xxxxxxxxxxxxxxxx"
$redirectUris = #()
$webAppUrl = "https://joyweb.azurewebsites.net"
if ($redirectUris -notcontains "$webAppUrl") {
$redirectUris += "$webAppUrl"
Write-Host "Adding $webAppUrl to redirect URIs";
}
if ($redirectUris -notcontains "$webAppUrl/aad-auth") {
$redirectUris += "$webAppUrl/aad-auth"
Write-Host "Adding $webAppUrl/aad-auth to redirect URIs";
}
$accesstoken = (Get-AzAccessToken -Resource "https://graph.microsoft.com/").Token
$header = #{
'Content-Type' = 'application/json'
'Authorization' = 'Bearer ' + $accesstoken
}
$body = #{
'spa' = #{
'redirectUris' = $redirectUris
}
} | ConvertTo-Json
Invoke-RestMethod -Method Patch -Uri "https://graph.microsoft.com/v1.0/applications/$objectId" -Headers $header -Body $body
Check the result in the portal:
There was a similar thread where someone was trying to programmatically add the redirect URIs for SPA and could not do it because it defaults under the Web section.
He was able to resolve this by posting with Azure CLI to the Graph API:
az rest `
--method PATCH `
--uri 'https://graph.microsoft.com/v1.0/applications/{id}' `
--headers 'Content-Type=application/json' `
--body "{spa:{redirectUris:['http://localhost:3000']}}"

List Cloud Service Classic use PowerShell and Azure Rest API

I Have a problem. Could you please help me view list Cloud Service Classic use PowerShell and Azure Rest API. When I used script for Web APP I show list Web APP, but when I used scrip for Cloud Service Classic I show error.
# Variables
$TenantId = "" # Enter Tenant Id.
$ClientId = "" # Enter Client Id.
$ClientSecret = "" # Enter Client Secret.
$Resource = "https://management.core.windows.net/"
$SubscriptionId = "" # Enter Subscription Id.
$RequestAccessTokenUri = "https://login.microsoftonline.com/$TenantId/oauth2/token"
$body = "grant_type=client_credentials&client_id=$ClientId&client_secret=$ClientSecret&resource=$Resource"
$Token = Invoke-RestMethod -Method Post -Uri $RequestAccessTokenUri -Body $body -ContentType 'application/x-www-form-urlencoded'
Write-Host "Print Token" -ForegroundColor Green
Write-Output $Token
# Get Azure Resource Groups
$ResourceGroupApiUri = "https://management.core.windows.net/$SubscriptionId/services/hostedservices"
$Headers = #{}
$Headers.Add("Authorization","$($Token.token_type) "+ " " + "$($Token.access_token)")
$ResourceGroups = Invoke-RestMethod -Method Get -Uri $ResourceGroupApiUri -Headers $Headers
Write-Host "Print Resource groups" -ForegroundColor Green
Write-Output $ResourceGroups
Invoke-RestMethod : ForbiddenErrorThe server failed to authenticate the request. Verify that the certificate is valid and
is associated with this subscription.
Actually, there is a built-in ASM PowerShell to list the cloud services associated with the current subscription.
Get-AzureService
Reference - https://learn.microsoft.com/en-us/powershell/module/servicemanagement/azure/get-azureservice?view=azuresmps-4.0.0
Besides, if you insist on calling the ASM rest api with powershell, you could refer to this article, the sample calls the Get Deployment api, just change it to List Cloud Services.
#Request Headers required to invoke the GET DEPLOYMENT REST API
$method
=
“GET”
$headerDate
= ‘2009-10-01’
$headers
= #{“x-ms-version”=“$headerDate“}
#Retrieving the subscription ID
$subID
= (Get-AzureSubscription
-Current).SubscriptionId
$URI
=
https://management.core.windows.net/$subID/services/hostedservices/kaushalz/deployments/4f006bb7d2874dd4895f77a97b7938d0
#Retrieving the certificate from Local Store
$cert
= (Get-ChildItem
Cert:\CurrentUser\My
|
?{$_.Thumbprint -eq
“B4D460D985F1D07A6B9F8BFD67E36BC53A4490FC”}).GetRawCertData()
#converting the raw cert data to BASE64
body
=
“<Binary>—–BEGIN CERTIFICATE—–`n$([convert]::ToBase64String($cert))`n—–END CERTIFICATE—–</Binary>”
#Retrieving the certificate ThumbPrint
$mgmtCertThumb
= (Get-AzureSubscription
-Current).Certificate.Thumbprint
#Passing all the above parameters to Invoke-RestMethod cmdlet
Invoke-RestMethod
-Uri
$URI
-Method
$method
-Headers
$headers
-CertificateThumbprint
” B4D460D985F1D07A6B9F8BFD67E36BC53A4490FC”
-ContentType
$ContentType

Azure WebApp - version controlled configuration/user data deployed separately from app

I've developed an WebApp (API) which is hosted in Azure & uses VSTS for CI/CD/version control.
I'd like to give the customer (owner) of this API the ability to update various configuration/data files under wwwroot, however I'd like those files to be under version control (source of truth - a separate repository to the API source code). Creating/Updating/Deleting one of those files in the repository should cause the file to be uploaded/removed in the WebApp (in a folder under wwwroot).
Modifying (creating/deleting) one of these files should not trigger a full redeployment (of the WebApp)
How can I achieve this? So far I've thought about a VSTS release pipeline for a GIT artefact however I couldn't see a low-friction way to make the changes in the Azure webapp (KUDU API seems a bit complex and heavy-handed)
**EDIT: ** Sample PowerShell script to sync Configuration files in WebApp w/ a build-artefact (PUT/DELETE only invoked when necessary).
# The idea behind this script is to synchronize the configuration files on the server with what's in the repo, only updating files where necessary
param (
[string]$resourceGroupName = "XXX",
[Parameter(Mandatory=$true)][string]$webAppName,
[Parameter(Mandatory=$true)][string]$latestConfigFilesPath
)
function Get-AzureRmWebAppPublishingCredentials($resourceGroupName, $webAppName, $slotName = $null) {
if ([string]::IsNullOrWhiteSpace($slotName)) {
$resourceType = "Microsoft.Web/sites/config"
$resourceName = "$webAppName/publishingcredentials"
} else {
$resourceType = "Microsoft.Web/sites/slots/config"
$resourceName = "$webAppName/$slotName/publishingcredentials"
}
$publishingCredentials = Invoke-AzureRmResourceAction -ResourceGroupName $resourceGroupName -ResourceType $resourceType -ResourceName $resourceName -Action list -ApiVersion 2015-08-01 -Force
return $publishingCredentials
}
function Get-KuduApiAuthorisationHeaderValue($resourceGroupName, $webAppName, $slotName = $null) {
$publishingCredentials = Get-AzureRmWebAppPublishingCredentials $resourceGroupName $webAppName $slotName
return ("Basic {0}" -f [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f $publishingCredentials.Properties.PublishingUserName, $publishingCredentials.Properties.PublishingPassword))))
}
function Get-KuduInode($kuduHref) {
return Invoke-RestMethod -Uri $kuduHref `
-Headers #{"Authorization"=$kuduApiAuthorisationToken;"If-Match"="*"} `
-Method GET `
-ContentType "application/json"
}
function Get-AllFilesUnderKuduHref($kuduHref) {
$result = #()
$inodes = (Get-KuduInode $kuduHref)
Foreach ($inode in $inodes) {
if ($inode.mime -eq "inode/directory") {
$result += (Get-AllFilesUnderKuduHref $inode.href)
} else {
$result += $inode.href
}
}
return $result
}
function Get-LocalPathForUri([System.Uri]$uri) {
$latestConfigFilesUri = [System.Uri]$latestConfigFilesPath
$localFileUri = [System.Uri]::new($latestConfigFilesUri, $uri)
return $localFileUri.LocalPath
}
function Get-RemoteUri([System.Uri]$uri) {
return [System.Uri]::new($configurationHref, $uri)
}
function Files-Identical($uri) {
$localFilePath = Get-LocalPathForUri $uri
$localFileHash = Get-FileHash $localFilePath -Algorithm MD5
# Download the remote file so that we can calculate the hash. It doesn't matter that it doesn't get cleaned up, this is running on a temporary build server anyway.
$temporaryFilePath = "downloded_kudu_file"
$remoteFileUri = [System.Uri]::new($configurationHref, $uri)
Invoke-RestMethod -Uri $remoteFileUri `
-Headers #{"Authorization"=$kuduApiAuthorisationToken;"If-Match"="*"} `
-Method GET `
-OutFile $temporaryFilePath `
-ContentType "multipart/form-data"
$remoteFileHash = Get-FileHash $temporaryFilePath -Algorithm MD5
return $remoteFileHash.Hash -eq $localFileHash.Hash
}
function CalculateRelativePath([System.Uri]$needle, [System.Uri]$haystack) {
return $haystack.MakeRelativeUri($needle).ToString();
}
function Put-File([System.Uri]$uri) {
Write-Host "Uploading file $uri"
$localFilePath = Get-LocalPathForUri $uri
$remoteFileUri = Get-RemoteUri $uri
Invoke-RestMethod -Uri $remoteFileUri `
-Headers #{"Authorization"=$kuduApiAuthorisationToken;"If-Match"="*"} `
-Method PUT `
-InFile $localFilePath `
-ContentType "multipart/form-data"
}
function Delete-File([System.Uri]$uri) {
Write-Host "Deleting file $uri"
$remoteFileUri = Get-RemoteUri $uri
Invoke-RestMethod -Uri $remoteFileUri `
-Headers #{"Authorization"=$kuduApiAuthorisationToken;"If-Match"="*"} `
-Method DELETE `
}
# Script begins here
$configurationHref = [System.Uri]"https://$webAppName.scm.azurewebsites.net/api/vfs/site/wwwroot/Configuration/"
$kuduApiAuthorisationToken = Get-KuduApiAuthorisationHeaderValue -resourceGroupName $resourceGroupName -webAppName $webAppName
$filenamesOnServer = Get-AllFilesUnderKuduHref $configurationHref $kuduApiAuthorisationToken | % { $configurationHref.MakeRelativeUri($_).OriginalString }
Write-Host "Files currently on server" $filenamesOnServer
$filesCurrentlyInRepo = Get-ChildItem -Path $latestConfigFilesPath -Recurse -File
$filenamesInRepo = $filesCurrentlyInRepo | Select-Object -ExpandProperty FullName | % { CalculateRelativePath $_ $latestConfigFilesPath}
Write-Host "Files currently in repo" $filenamesInRepo
$intersection = $filenamesOnServer | ?{$filenamesInRepo -contains $_}
Write-Host "Intersection: " $intersection
$onlyOnServer = $filenamesOnServer | ?{-Not($filenamesInRepo -contains $_)}
$onlyInRepo = $filenamesInRepo | ?{-Not($filenamesOnServer -contains $_)}
Write-Host "Only on server" $onlyOnServer
Write-Host "Only in repo" $onlyInRepo
Write-Host
Foreach ($uri in $onlyInRepo) {
Put-File $uri
}
Foreach ($uri in $onlyOnServer) {
Delete-File $uri
}
Foreach ($uri in $intersection) {
if (-Not (Files-Identical $uri)) {
Write-Host "Configuration file $uri needs updating"
Put-File $uri
} else {
Write-Host "Configuration file $uri is identical, skipping"
}
}
Write-Host "Sync complete"
With Azure App Service deploy task, you can upload files to app service, but can’t delete files (Uncheck Publish using Web Deploy optioin and specify the folder path in Package or folder input box).
So, the better way is using Kudu API to delete/upload files during build/release.
There is the thread and a blog about using Kudu API:
How to access Kudu in Azure using power shell script
Interacting with Azure Web Apps Virtual File System using PowerShell and the Kudu API

Resources