Azure: Unable to find the resource (app insights) when creating a deployment - azure

When running a build in TeamCity, we run some azure scripts. But occasionally I get the error about unable to find the resource (application insights).
The error is:
ERROR: Deployment failed. Correlation ID: ############. {
"Code": "BadRequest",
"Message": "Unable to find the resource /subscriptions/###########/resourceGroups/myResourceGroup/providers/microsoft.insights/components/myAppInsight, please confirm that it exists."
}
The script we use is:
az extension add -n application-insights
az monitor app-insights component create --app $functionAppName --location $location --resource-group $rgTelemetryConfig --tags $tags
az functionapp create -n $functionAppName -g $rgTelemetryConfig --app-insights $functionAppName --storage-account $storageAccount --consumption-plan-location $location --tags $tags --runtime $runtime
az group deployment create --resource-group $rgTelemetryConfig --template-file ./templates/monitoring/config-template.json --parameters appInsights=$functionAppName
In the arm template, we do refer to the appInsights severl times, like:
"actionGroupId": "[resourceId('microsoft.insights/actionGroups', parameters('actionGroup'))]"
"scopes": [
"[resourceId('microsoft.insights/components', parameters('appInsights'))]"
]
"componentId": "[resourceId('microsoft.insights/components', parameters('appInsights'))]"
Does anyone know how I should fix it?

Related

Azure Function App - Swap deployment Slots stuck then crashing completely

Recently my function apps have stopped swapping slots, they worked fine for months but suddenly they have all stopped swapping by taking a long time then crashing. I have recreated the function apps using the same scripts and have replicated the issue but still can't fix.
Is there anything I am setting to stop the slots from switching?
Here is the fundamental build script I am using. I am able to run this but when trying to swap slots in Azure it freezes then crashes with a vague error message:
# Azure Login
az login
# Set deployment Environment
$environment = "stage"
# Resource Group Variables
$subscriptionId = ""
$domain = "test4"
$resourceGroup = "xx-platform-$domain-$environment"
$region = "northEurope"
# Functions app variables
$storageName = "xxfn$domain$environment" # must be less than 24 chars and all lower case
$functionAppDeploymentSlotName = "test"
$functionAppName = "xx-platform-$domain-fn-$environment"
$functionAppEnvironment = "AZURE_FUNCTIONS_ENVIRONMENT=Development"
$websiteRunFromPackage = "WEBSITE_RUN_FROM_PACKAGE=1"
#########################################################################################################################################################################
## Resource Group
Write-output "Creating resource group";
# Set subscription
az account set --subscription $subscriptionId
# Create resource group
az group create -l $region -n $resourceGroup
#########################################################################################################################################################################
## Functions App
Write-output "Creating Functions App";
# Create storage account
az storage account create --name $storageName --location $region --resource-group $resourceGroup --sku Standard_LRS
# Create functions app - using consumption plan
az functionapp create --name $functionAppName --storage-account $storageName --consumption-plan-location northEurope --resource-group $resourceGroup --functions-version 4
# Set functions app configuration settings
# Environment
az functionapp config appsettings set --name $functionAppName --resource-group $resourceGroup --settings $functionAppEnvironment
# WEBSITE_RUN_FROM_PACKAGE
az functionapp config appsettings set --name $functionAppName --resource-group $resourceGroup --settings $websiteRunFromPackage
# SET DOT NET FRAMEWORK ERSION
az functionapp config set --net-framework-version v6.0 -g $resourceGroup -n $functionAppName
# Create functions app deployment slot
az functionapp deployment slot create --name $functionAppName --resource-group $resourceGroup --slot $functionAppDeploymentSlotName
I have modified your script in initializing the variable values directly to the cmdlets:
# Azure Login
az login
az account set --subscription "<Ur_Azure_Subscription_Id>"
# Function App Create
az functionapp create --name dt-platform-fn-stage --storage-account dtfnstageenvironment --consumption-plan-location northEurope --resource-group HariTestRG --runtime dotnet --functions-version 4
# Environment
az functionapp config appsettings set --name dt-platform-fn-stage --resource-group HariTestRG --settings AZURE_FUNCTIONS_ENVIRONMENT=Development
# WEBSITE_RUN_FROM_PACKAGE
az functionapp config appsettings set --name dt-platform-fn-stage --resource-group HariTestRG --settings WEBSITE_RUN_FROM_PACKAGE=1
# SET DOT NET FRAMEWORK ERSION
az functionapp config set --net-framework-version v6.0 -g HariTestRG -n dt-platform-fn-stage
# Create functions app deployment slot
az functionapp deployment slot create --name dt-platform-fn-stage --resource-group HariTestRG --slot test
Created the Http Trigger Function using the cmdlets given in the below given MS Document.
For Continuous deployments, this app setting needs to be configured:
az functionapp config appsettings set --name dt-platform-fn-stage --resource-group HariTestRG --settings "SCM_DO_BUILD_DURING_DEPLOYMENT=true"
Deployed the Function to the Azure Functions using az cli cmdlet given in one of my workarounds.
By default, Auto Swap on Slots will be disabled:
It is working fine during the slot swapping and make sure you have followed the considerations mentioned in this MS Doc that also provides the list of az cli cmdlets for managing the slots like creating, listing, deleting, swapping and auto swapping configuration.
Above Azure CLI Commands have been taken from this MS Doc references.

Best way to deploy code and restore database in a managed Application on Azure MarketPlace

Our goal is publishing our offer to Azure MarketPlace. We created an ARM template for our infrastructure and had no issues with that.
Our main issue is how to deploy our code and DB schema through the purchase process.
Microsoft recommends Deployment Scripts so we made ours which contains, CLI commands to restore a .BACPAC sql file, app settings configurations and a CURL command for zip deployment via KUDU for the web application.
.BACPAC and zip package for code are in blob storage.
If we run our scripts in a custom ARM template deployment in Azure, they work fine !!
But when we run them through the marketplace purchase, they fail with no error logs.
Down below you can find our script commands.
"scriptContent": "
az sql db import -s $sqlserver -n $sqldatabase -g $rg -p $sqlpassword -u $sqlusername --storage-key $sqlstoragekey --storage-key-type $storagekeytype --storage-uri $storageuri \r\n
az webapp deployment user set --user-name $deploymentUser --password $deploymentPass \r\n
az webapp config connection-string set --name $applicationName --resource-group $rg --settings DefaultConnection=\"Server=tcp:$sqlserver.database.windows.net,1433;Initial Catalog=$sqldatabase;Persist Security Info=False;User ID=$sqlusername;Password=$sqlpassword;MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;\" --connection-string-type SQLAzure \r\n
az webapp config appsettings set --name $applicationName --resource-group $rg --settings PortalUrl=\https://$applicationName.azurewebsites.net/\ \r\n
az webapp config appsettings set --name $applicationName --resource-group $rg --settings AzureAd:Domain=\"$AADDomain\" \r\n
az webapp config appsettings set --name $applicationName --resource-group $rg --settings AzureAd:ClientId=\"$AADClientId\" \r\n
az webapp config appsettings set --name $applicationName --resource-group $rg --settings AzureAd:TenantId=\"$AADTenantId\" \r\n
az webapp config appsettings set --name $applicationName --resource-group $rg --settings AzureAd:ClientSecret=\"$AADClientSecret\" \r\n
az webapp restart --name $applicationName --resource-group $rg \r\n
curl -X PUT -u $deploymentUser:$deploymentPass https://$applicationName.scm.azurewebsites.net/api/zipdeploy -H \"Content-Type: application/json\" -d \"{'packageUri':'$applicationUri$applicationStorageKey'}\" \r\n
",
In case our approach is wrong, any example, documentation and suggestions will be super helpful.
Feel free to ask for more information if any.
Thank you

Unable to backup Function/Web App using Azure Cli az webapp config backup create

I am facing an issue when executing the Azure Cli command to backup my Azure App Service:
Cli Command :
az webapp config backup create --resource-group --webapp-name
--backup-name testbackup --container-url
I generated a new SaS key to be passed along with the command.
Is this the correct approach.
Cli Output:
{ "backupId": 64862, "backupItemName": "testbackup", "blobName": "testbackup", "correlationId": "3e9ae4d0-9aa9-46e0-9926-53ec1ef6ef2c", "created": "2020-09-22T08:50:35.555268+00:00", "databases": null, "finishedTimeStamp": null, "id": "value", "kind": null, "lastRestoreTimeStamp": null, "location": "Central US", "log": null, "name": "testbackuppr", "resourceGroup": "RG-POC", "scheduled": false, **"sizeInBytes": 0,** "status": "Created", "storageAccountUrl": "", "type": "Microsoft.Web/sites", "websiteSizeInBytes": null }
Log Information in the Portal : Storage access failed. The remote server returned an error: (404) Not Found.. Please delete and recreate backup schedule to mitigate.
Looks like something is not right with the Storage account or its access. Before you execute the az webapp config backup create command, please make sure that you have a valid Storage account, a storage container and a SAS token with the appropriate expiry date. The SAS token can be generated with the az storage container generate-sas command.
The following script worked for me:
#!/bin/bash
groupname="myResourceGroup"
planname="myAppServicePlan"
webappname=mywebapp$RANDOM
storagename=mywebappstorage$RANDOM
location="WestEurope"
container="appbackup"
backupname="backup1"
expirydate=$(date -I -d "$(date) + 1 month")
# Create a Resource Group
az group create --name $groupname --location $location
# Create a Storage Account
az storage account create --name $storagename --resource-group $groupname --location $location \
--sku Standard_LRS
# Create a storage container
az storage container create --account-name $storagename --name $container
# Generates an SAS token for the storage container, valid for one month.
# NOTE: You can use the same SAS token to make backups in App Service until --expiry
sastoken=$(az storage container generate-sas --account-name $storagename --name $container \
--expiry $expirydate --permissions rwdl --output tsv)
# Construct the SAS URL for the container
sasurl=https://$storagename.blob.core.windows.net/$container?$sastoken
# Create an App Service plan in Standard tier. Standard tier allows one backup per day.
az appservice plan create --name $planname --resource-group $groupname --location $location \
--sku S1
# Create a web app
az webapp create --name $webappname --plan $planname --resource-group $groupname
# Create a one-time backup
az webapp config backup create --resource-group $groupname --webapp-name $webappname \
--backup-name $backupname --container-url $sasurl
# List statuses of all backups that are complete or currently executing.
az webapp config backup list --resource-group $groupname --webapp-name $webappname
Output would be similar to:
References:
Back up an app using Azure CLI
az webapp config backup create
az storage container generate-sas

Azure Cli How to enable Application Insights for webapp

Consider the following code. It creates an application insight, then it retrieves the instrumentationkey and assigns it to my webapp.
az monitor app-insights component create -g $resourceGroup --app $webapp --application-type web --kind web --tags $defaultTags
$instrumentationKey = az monitor app-insights component show -g $resourceGroup -a $webapp --query 'instrumentationKey' -o tsv
az webapp config appsettings set -g $resourceGroup -n $webapp --settings APPINSIGHTS_INSTRUMENTATIONKEY=$instrumentationKey APPLICATIONINSIGHTS_CONNECTION_STRING=InstrumentationKey=$instrumentationKey
However, this does not turn on application insight for the webapp as shown in this screen capture. I cannot figure out how to turn it on from azure cli.
Using the link #Alex AIT provided the cli could be as follows.
Please note that you could also rely on the fact that if you don't create an App Insights instance an auto instance will be created and used.
# (...) Set up $plan, $resourcegroup and $region
az appservice plan create --name $plan --resource-group $resourcegroup --location $region --sku FREE
[String]$webapp="myapp"
az webapp create --name $webapp --plan $plan --resource-group $resourcegroup
[String]$appinsights=$webapp
az monitor app-insights component create --app $appinsights --location $region --resource-group $resourcegroup
# Get the instrumentation key
# '--output tsv', which is 'Tab-separated values, with no keys'
# is used to obtain the unquoted value
# as shown in https://learn.microsoft.com/en-us/cli/azure/query-azure-cli?view=azure-cli-latest#get-a-single-value
[String]$instrumentationKey = (az monitor app-insights component show --app $appinsights --resource-group $resourcegroup --query "instrumentationKey" --output tsv)
# Configure the app to use new app insights instance
# Based on https://learn.microsoft.com/en-us/azure/azure-monitor/app/azure-web-apps?tabs=net#enabling-through-powershell
az webapp config appsettings set --name $webapp --resource-group $resourcegroup --settings APPINSIGHTS_INSTRUMENTATIONKEY=$instrumentationKey APPLICATIONINSIGHTS_CONNECTION_STRING=InstrumentationKey=$instrumentationKey ApplicationInsightsAgent_EXTENSION_VERSION=~2
You need to set a couple more app settings to make it exactly like if you enabled it from the Azure Portal. I believe the second important key after the instrumentation key is ApplicationInsightsAgent_EXTENSION_VERSION.
https://learn.microsoft.com/en-us/azure/azure-monitor/app/azure-web-apps?tabs=net#automate-monitoring
Powershell example which you can adapt to AzureCLI:
$app = Get-AzWebApp -ResourceGroupName "AppMonitoredRG" -Name "AppMonitoredSite" -ErrorAction Stop
$newAppSettings = #{} # case-insensitive hash map
$app.SiteConfig.AppSettings | %{$newAppSettings[$_.Name] = $_.Value} # preserve non Application Insights application settings.
$newAppSettings["APPINSIGHTS_INSTRUMENTATIONKEY"] = "012345678-abcd-ef01-2345-6789abcd"; # set the Application Insights instrumentation key
$newAppSettings["APPLICATIONINSIGHTS_CONNECTION_STRING"] = "InstrumentationKey=012345678-abcd-ef01-2345-6789abcd"; # set the Application Insights connection string
$newAppSettings["ApplicationInsightsAgent_EXTENSION_VERSION"] = "~2"; # enable the ApplicationInsightsAgent
$app = Set-AzWebApp -AppSettings $newAppSettings -ResourceGroupName $app.ResourceGroup -Name $app.Name -ErrorAction Stop
There is a better approach than trying to manually set the app settings. Simply use this command (Link to docs provided):
az monitor app-insights component connect-webapp --app
--resource-group
--web-app
[--enable-debugger {false, true}]
[--enable-profiler {false, true}]
Connecting an application insights to a web app.

Delete deployment from Azure Subscription using Azure Cli

I am trying to delete the deployments from a given resource group (because it hits the max 800) via Azure Cli as below. But the script below doesnt work. Does anyone have any idea?
az Login
az account set --subscription "mysubscription"
$resourceGroupName = "myresourcegroup"
$deployments = az group deployment list --resource-group $resourceGroupName
Foreach ($deployment in $deployments)
{
az group deployment delete --name $deployment.name --resource-group $resourceGroupName
}
-Alan-
This happens because az cli outputs a json, not an object. you need to cast it to object for this to work:
$deployments = ( az group deployment list --resource-group $resourceGroupName ) |
ConvertFrom-Json
Foreach ($deployment in $deployments) {
az group deployment delete --name $deployment.name --resource-group $resourceGroupName
}

Resources