Wednesday 14 October 2020

Azure PowerShell : Script to create Azure App Service

This PowerShell script is to create an Azure App Service with .NETCORE Web Application:
#Provide following variables:

$subscriptionname = ""
$Environment = ""
$webappName=""              #Provide Web App Name
$location="westus"                         #Provide Location
$resourceGroupName = ""     #Provide Resource Group
$AppServicePlan = ""   #Provide Service Plan
$BusinessOwner = ""
$Owner =""

$SubsId = Get-AzSubscription -SubscriptionName $subscriptionname

Select-AzSubscription -SubscriptionId $SubsId.Id

#Creating WebApp
New-AzWebApp -ResourceGroupName $resourceGroupName -Name $webappName `
-Location $location -AppServicePlan $AppServicePlan

Set-AzWebApp -ResourceGroupName $resourceGroupName `
-Name $webappName -AlwaysOn $true


#Setting .NET CORE
$dotnetResourceName = $webappName + "/metadata"

$PropertiesObject = @{
    "CURRENT_STACK" =  "dotnetcore"
}
New-AzResource -PropertyObject $PropertiesObject -ResourceGroupName $resourceGroupName `
-ResourceType Microsoft.Web/sites/config -ResourceName $dotnetResourceName -Force



#Creating App Insight
New-AzApplicationInsights -ResourceGroupName $resourceGroupName `
-Name $webappName -Location $location

# Collecting create app insight info
$appInsightsKey = Get-AzApplicationInsights -Name $webappName `
-ResourceGroupName $resourceGroupName


$errorpage = "https://"+ $webappName + 
".scm.azurewebsites.net/detectors?type=tools&name=eventviewer"

$appconnectionstring = "InstrumentationKey=" + $appInsightsKey.InstrumentationKey `
+";IngestionEndpoint=https://"+ $location + "-0.in.applicationinsights.azure.com/"


$app = Get-AzWebApp -ResourceGroupName $resourceGroupName -Name $webappName -ErrorAction Stop
$newAppSettings = @{} # case-insensitive hash map
# preserve non Application Insights application settings.
$app.SiteConfig.AppSettings | %{$newAppSettings[$_.Name] = $_.Value} 
$newAppSettings["ANCM_ADDITIONAL_ERROR_PAGE_LINK"] = $errorpage;
 # set the Application Insights instrumentation key
$newAppSettings["APPINSIGHTS_INSTRUMENTATIONKEY"] = $appInsightsKey.InstrumentationKey;
 # set the Application Insights connection string
$newAppSettings["APPLICATIONINSIGHTS_CONNECTION_STRING"] = $appconnectionstring;
 # enable the ApplicationInsightsAgent
$newAppSettings["ApplicationInsightsAgent_EXTENSION_VERSION"] = "~2";
$newAppSettings["XDT_MicrosoftApplicationInsights_Mode"] = "default";

$app = Set-AzWebApp -AppSettings $newAppSettings `
-ResourceGroupName $app.ResourceGroup -Name $app.Name -ErrorAction Stop

$Tags = @{App="Apps";BusinessOwner=$BusinessOwner;Owner=$Owner;Environment =$Environment};

Set-AzResource -ResourceGroupName $resourceGroupName `
-Name $webappName -ResourceType Microsoft.Web/sites -Tag $Tags -Force