Adding vnet integration for the multiple Azure webapp slots using powershell or azure cli - azure-web-app-service

I'm trying to Vnet integrate the multiple webapps and slots using powershell. Where enabling vnet integration for webapps is working fine, but in the same way for webapp slots its not working.
$RGName = "web app resource group name "
$vnetName = "yashvnet01"
$VnetRG = "vnet name"
$subnetName = "subnet name"
$Vnet = Get-AzVirtualNetwork -Name $vnetName -ResourceGroupName $VnetRG
$subnet = Get-AzVirtualNetworkSubnetConfig -Name $subnetName -VirtualNetwork $Vnet
$Vnet.Id
##Add vnet integration to the webapps in the specific Resource group
$Webapps=Get-AzWebApp -ResourceGroupName $RGname
$Webapps.Name
ForEach($webapp in $Webapps.Name)
{
Write-Host "Adding Vnet intergation to the $webapp"
az webapp vnet-integration add --resource-group $RGname --name $webapp --vnet $Vnet.Id --subnet $subnetName
Write-Host "Successfully added Vnet intergation to the $webapp"
}
How can we do the same for multiple webapp slot.
I would be glad if someone helps me on this.
Cheers
Rewanth

You can use the below script to apply v-net intergration on the webapps slots.
Connect-AzAccount
$RGName = "yourresourcegroupname"
$vnetName = "vnetname"
$VnetRG = "vnet resource group name"
$subnetName = "subnetname"
$Vnet = Get-AzVirtualNetwork -Name $vnetName -ResourceGroupName $VnetRG
$subnet = Get-AzVirtualNetworkSubnetConfig -Name $subnetName -VirtualNetwork $Vnet
$Vnet.Id
$Webapps=Get-AzWebApp -ResourceGroupName $RGname
$Webapps.Name
##Add vnet integration to the webapps slots in the specific Resource group
ForEach($webapp in $Webapps.Name)
{
#Webapp slot
$WebappsSlot = Get-AzWebAppSlot -ResourceGroupName $RGName -Name $webapp
$WebappsSlot.Name
ForEach($webappSlot in $WebappsSlot.Name) {
$s = $webappSlot -replace $webapp + "/"
Write-Host "Adding Vnet intergation to the $s"
az webapp vnet-integration add --resource-group $RGname --name $webapp --vnet $Vnet.Id --subnet $subnetName -s $s
Write-Host "Successfully added Vnet intergation to the $s"
}
}
Output for test:
Note:
Please make sure to use the updated az version while running the above code . The az cli version used for the above is 2.71.1 . You can upgrade az version using command az upgrade in powershell.

Related

Setup and deploy Azure function using PowerShell

I try to setup and deploy Azure Function by using PowerShell script based on this topic: Setup Azure Function from PowerShell
My script looks like this:
#=============Defining All Variables=========
$location = 'Central US'
$resourceGroupName = 'MyResourceGroup'
$subscriptionId = 'MysubscriptionId'
$functionAppName = 'MyfunctionAppName'
$appServicePlanName = 'ASP-test-8b50'
$tier = 'Dynamic'
$archivePath = 'd:\TestAzureFunc.zip'
Connect-AzAccount
#========Creating Azure Resource Group========
$resourceGroup = Get-AzResourceGroup | Where-Object { $_.ResourceGroupName -eq $resourceGroupName }
if ($resourceGroup -eq $null)
{
New-AzResourceGroup -Name $resourceGroupName -Location $location -force
}
#selecting default azure subscription by name
Select-AzSubscription -SubscriptionID $subscriptionId
Set-AzContext $subscriptionId
#========Creating App Service Plan============
New-AzAppServicePlan -ResourceGroupName $resourceGroupName -Name $appServicePlanName -Location $location -Tier $tier
$functionAppSettings = #{
ServerFarmId="/subscriptions/$subscriptionId/resourceGroups/$resourceGroupName/providers/Microsoft.Web/serverfarms/$appServicePlanName";
alwaysOn=$True;
}
#========Creating Azure Function========
$functionAppResource = Get-AzResource | Where-Object { $_.ResourceName -eq $functionAppName -And $_.ResourceType -eq "Microsoft.Web/Sites" }
if ($functionAppResource -eq $null)
{
New-AzResource -ResourceType 'Microsoft.Web/Sites' -ResourceName $functionAppName -kind 'functionapp' -Location $location -ResourceGroupName $resourceGroupName -Properties $functionAppSettings -force
}
#========Defining Azure Function Settings========
$AppSettings =#{}
$AppSettings =#{'FUNCTIONS_EXTENSION_VERSION' = '~2';
'FUNCTIONS_WORKER_RUNTIME' = 'dotnet';}
Set-AzWebApp -Name $functionAppName -ResourceGroupName $resourceGroupName -AppSettings $AppSettings
#========Deploy Azure Function from zip========
Publish-AzWebapp -ResourceGroupName $resourceGroupName -Name $functionAppName -ArchivePath $archivePath
The script works without errors. Resource group and Function App created as needed. But the list of functions of the Function App is empty.
Function details here:
My intuition tells me that I've forgotten something. But I don't know what.
Could you advise me on how to deploy my Azure function properly?
One of the workaround you can follow ,
Looking at your script we need to ensure that we are providing function app configuration as below cmdlts the link you followed:-
$AzFunctionAppSettings = #{
APPINSIGHTS_INSTRUMENTATIONKEY = $AppInsightsKey;
AzureWebJobsDashboard = $AzFunctionAppStorageAccountConnectionString;
AzureWebJobsStorage = $AzFunctionAppStorageAccountConnectionString;
FUNCTIONS_EXTENSION_VERSION = "~4";
FUNCTIONS_WORKER_RUNTIME = "dotnet";
}
And also make sure that the storage account connection string you provided in the function is same as here providing.
And then you can navigate to Kudu API to check the wwwroot folder is exist or not.
For more information please refer the below links:-
SO THREAD|Powershell command Publish-AzWebApp not publishing apllication
BLOG|How to Deploy Azure Function Apps With Powershell.

Fix for the Subnet Missing Required Delegation

I have a Azure Resource Group and it has a vnet. The vnet has a subnet which has two service endpoints configured namely Microsoft.keyVault and Microsoft.Storage and the subnet also has a subnet delegation to Microsoft.Web/serverFarms.
Now I want to add another service endpoint Microsoft.ServiceBus to the same vnet using Azure Powershell. I executed the below code for that.
$virtualNetwork = Get-AzVirtualNetwork -ResourceGroupName $ResourceGroupName
Set-AzVirtualNetworkSubnetConfig -Name $virtualNetwork.Subnets.Name -VirtualNetwork $virtualNetwork -AddressPrefix $virtualNetwork.Subnets.AddressPrefix -ServiceEndpoint "Microsoft.ServiceBus"
$virtualNetwork | Set-AzVirtualNetwork
But the above code is throwing error at the last line of code saying that the Subnet is missing Required Delegation
Subnet requires any of the following delegation(s) [Microsoft.Web/serverFarms] to reference service association link
StatusCode: 400
ReasonPhrase: Bad Request
ErrorCode: SubnetMissingRequiredDelegation
But in portal I see it has the required delegation. How to fix this error?
Even though i have already added these service endpoint in my specific subnet and subnet also has a subnet delegation to Microsoft.Web/serverFarms able to add another service endpoint Microsoft.ServiceBus.
I would suggest you to use the following PowerShell script:
PowerShell Script:
$subscription = "b83c1edXXXXXXX-XXX"
$subnets = #('TestSubnet')
$vnetName = "Vnet1"
$vnetRgName = "X-rasXXXX-XX"
$newEndpoint = "Microsoft.ServiceBus"
Set-AzContext -Subscription $subscription
foreach($snet in $subnets){
Write-Host "Modifying Service Endpoints for subnet: $snet" -fore red -back white
$virtualNetwork = Get-AzVirtualNetwork -Name $vnetName -ResourceGroupName $vnetRgName | Get-AzVirtualNetworkSubnetConfig -Name $snet
$addrPrefix = $virtualNetwork.AddressPrefix
#Get existing service endpoints
$ServiceEndPoint = New-Object 'System.Collections.Generic.List[String]'
$virtualNetwork.ServiceEndpoints | ForEach-Object { $ServiceEndPoint.Add($_.service) }
if ($ServiceEndPoint -notcontains $newEndPoint){
$ServiceEndPoint.Add($newEndpoint)
}
$delegation=$virtualNetwork.Delegations
#Add new service endpoint
Get-AzVirtualNetwork -Name $vnetName -ResourceGroupName $vnetRgName | Set-AzVirtualNetworkSubnetConfig -Name $snet -AddressPrefix $addrPrefix -ServiceEndpoint $ServiceEndPoint -Delegation $delegation | Set-AzVirtualNetwork
}
Reference : Azure Powershell - Applying multiple service endpoints to a subnet

How to copy custom images in Azure from one subscription to another

I am running my virtual machines on Azure which consists of multiple directories and each directory has two-three subscriptions in it. I made a custom image for my infrastructure environment under my default subscription (say "Visual Studio Enterprise: BizSpark").
I want to copy this custom image to other subscriptions under different directories so that this image is easily accessible throughout my Azure account.
I was following this link : Copy Managed Images by Michael S. Collier
but I got stuck at this snippet:
diskName=$(az vm show --resource-group linux -n vm --query "storageProfile.osDisk.name" -o tsv)
Error:
The Resource 'Microsoft.Compute/virtualMachines/vm' under resource group 'linux' was not found.
Any lead on this will be appreciated.
For a managed disk or managed image, you can not directly move it from one subscription to another subscription which is existed in a different tenant. The error may indicate that you have connected to a different tenant.
If the original managed disk exists, you could refer this blog to move Azure Managed Disk between Tenants
You can create a snapshot of the managed disk and move it to a storage
account in the source subscription, then copy the snapshot to a
storage account in the destination subscription and create a managed
disk out of the snapshot and a VM with the managed disk afterward.
Here are the main steps in PowerShell.
A: Download the disk snapshot to a storage account
$sourceSubscriptionId = ''
$sourceStorageAccountName = "SourceStorageAccount"
$sourceStorageAccountKey = "9O1...Kg=="
$sourceStorageAccountContainer = "containername"
# path of the download URL of the snapshot
$VHDDownloadUri = "https://....blob.core.windows.net/..."
$targetSnapshotName = "snapshot.vhd"
#download snapshot to StorageAccount-Source (the storage account is located in the source subscription)
Select-AzureRmSubscription -SubscriptionId $sourceSubscriptionId
$sourceStorageAccountContext = New-AzureStorageContext –StorageAccountName $sourceStorageAccountName -StorageAccountKey $sourceStorageAccountKey
Start-AzureStorageBlobCopy -AbsoluteUri $VHDDownloadUri -DestContainer $sourceStorageAccountContainer -DestContext $sourceStorageAccountContext -DestBlob $targetSnapshotName
B: Copy the snapshot to a storage account in the destination subscription of an other tenant:
$destSubscriptionId = ''
$destStorageAccount = "DestStorageAccount"
$destStorageAccountKey = "Pqn.../Q=="
$destStorageAccountContainer = "container"
Select-AzureRmSubscription -SubscriptionId $destSubscriptionId
$destStorageAccountContext = New-AzureStorageContext –StorageAccountName $destStorageAccount -StorageAccountKey $destStorageAccountKey
Get-AzureStorageBlobCopyState -Context $destStorageAccountContext -Blob $targetSnapshotName
$blobCopy = Start-AzureStorageBlobCopy -DestContainer $destStorageAccountContainer -DestContext $destStorageAccountContext -SrcBlob $targetSnapshotName -Context $sourceStorageAccountContext -SrcContainer $sourceStorageAccountContainer
Write-Host ($blobCopy | Get-AzureStorageBlobCopyState).CopyId
Write-Host ($blobCopy | Get-AzureStorageBlobCopyState).TotalBytes
Write-Host ($blobCopy | Get-AzureStorageBlobCopyState).BytesCopied
while(($blobCopy | Get-AzureStorageBlobCopyState).Status -eq "Pending")
{
Start-Sleep -s 5
#$blobCopy | Get-AzureStorageBlobCopyState
$output = "`r" + ($blobCopy | Get-AzureStorageBlobCopyState).BytesCopied
Write-Host $output -NoNewline
}
The copy process runs asynchronous. If you need to stop the copy process, get the CopyId and use the Stop-AzureStorageBlogCopy command: Stop-AzureStorageBlobCopy -Container $destStorageAccountContainer -Blob $targetSnapshotName -CopyId "<GUID>" -Context $destStorageAccountContext
C: Create a new VM and use the snapshot.vhd from the DestStorageAccount as base image for the managed disk:
$rgName = "DestResourceGroup"
$location = "northeurope"
$storageName = "MyVMstorage"
$storageType = "Standard_LRS"
$nicname = "MyVM-nic"
$subnet1Name = "MyVM-subnet"
$vnetName = "MyVM-vnet"
$vnetAddressPrefix = "10.0.0.0/16"
$vnetSubnetAddressPrefix = "10.0.0.0/24"
$vmName = "MyVM"
$vmSize = "Standard_D2s_v3"
$osDiskName = $vmName + "osDisk"
$osDiskUri = "https://deststorageaccount.blob.core.windows.net/container/snapshot.vhd"
$storageacc = New-AzureRmStorageAccount -ResourceGroupName $rgName -Name $storageName -Type $storageType -Location $location
$pip = New-AzureRmPublicIpAddress -Name $nicname -ResourceGroupName $rgName -Location $location -AllocationMethod Dynamic
$subnetconfig = New-AzureRmVirtualNetworkSubnetConfig -Name $subnet1Name -AddressPrefix $vnetSubnetAddressPrefix
$vnet = New-AzureRmVirtualNetwork -Name $vnetName -ResourceGroupName $rgName -Location $location -AddressPrefix $vnetAddressPrefix -Subnet $subnetconfig
$nic = New-AzureRmNetworkInterface -Name $nicname -ResourceGroupName $rgName -Location $location -SubnetId $vnet.Subnets[0].Id -PublicIpAddressId $pip.Id
$vm = New-AzureRmVMConfig -VMName $vmName -VMSize $vmSize
$vm = Add-AzureRmVMNetworkInterface -VM $vm -Id $nic.Id
$discStorageAcc = Get-AzureRmStorageAccount -ResourceGroupName $ResourceGroup -Name $destStorageAccount
$diskConfig = New-AzureRmDiskConfig -AccountType 'PremiumLRS' -Location $location -CreateOption Import -StorageAccountId ($discStorageAcc.Id) -SourceUri $osDiskUri
$disk = New-AzureRmDisk -Disk $diskConfig -ResourceGroupName $rgName -DiskName "managedsnapshot"
$vm = Set-AzureRmVMOSDisk -VM $vm -ManagedDiskId $disk.Id -CreateOption Attach -Windows
New-AzureRmVM -ResourceGroupName $rgName -Location $location -VM $vm -Verbose
first command just retrieves disk name, so if you know disk name you dont have to run it. just do:
diskName="diskname_goes_here"

Azure Powershell - Applying multiple service endpoints to a subnet

I have coded a powershell script to set an existing subnet to function as a service endpoint for multiple services. However, when I run the command line in the script, it doesn't add a new service endpoint, it just changes the existing one.
I am trying to parameterise this through Jenkins as well, which may be an added complication. I think if I can get the base syntax right then that shouldn't be a problem.
Syntax I am using is:
#Get vnet
$virtualnetwork = Get-AzureRmVirtualNetwork -Name $VN -ResourceGroupName $RG
#Configure service endpoint
Add-AzureRmVirtualNetworkSubnetConfig -Name $SN -AddressPrefix $SAP -
VirtualNetwork $virtualnetwork -ServiceEndpoint $EP
#Set configuration
$virtualnetwork | Set-AzureRmVirtualNetwork
You can use something like this to add as many endpoints as required:
$rgname = "amgar-dtl"
$vnName = "Dtlamgar-dtl"
$sname = "Dtlamgar-dtlSubnet"
$subnetPrefix = "10.0.0.0/20"
#Get vnet
$VirtualNetwork = Get-AzureRmVirtualNetwork -ResourceGroupName $rgname -Name $vnName | Get-AzureRmVirtualNetworkSubnetConfig -Name $sname
#Get existing service endpoints
$ServiceEndPoint = New-Object 'System.Collections.Generic.List[String]'
$VirtualNetwork.ServiceEndpoints | ForEach-Object { $ServiceEndPoint.Add($_.service) }
#Add new service endpoint
Get-AzureRmVirtualNetwork -ResourceGroupName $rgname -Name $vnName | Set-AzureRmVirtualNetworkSubnetConfig -Name $sname -AddressPrefix $subnetPrefix -ServiceEndpoint $ServiceEndPoint.Add("Microsoft.KeyVault") | Set-AzureRmVirtualNetwork
Hope this helps!
Successful syntax is:
#Vnet
$VN = "$ENV:VNET_NAME"
#Resource Group
$RG = "$ENV:RESOURCEGROUP_NAME"
#Subnet
$SN = "$ENV:SUBNET_NAME"
#Subnet Address Prexifx
$SAP = "$ENV:ADDRESS_PREFIX"
#ServiceEndpoint
$EP = "$ENV:SERVICE_ENDPOINT"
Write-Host "Importing the AzureRM module into the PowerShell session"
Import-Module AzureRM
Write-Host "Connect service principle account to Azure RM"
Connect-AzureRmAccount -ServicePrincipal -Credential $CREDS -TenantId $TID -Subscription $SID
#Get vnet
$VirtualNetwork = Get-AzureRmVirtualNetwork -ResourceGroupName $RG -Name $VN | Get-AzureRmVirtualNetworkSubnetConfig -Name $SN
#Get existing service endpoints
$ServiceEndPoint = New-Object 'System.Collections.Generic.List[String]'
$VirtualNetwork.ServiceEndpoints | ForEach-Object { $ServiceEndPoint.Add($_.service) }
$ServiceEndPoint.Add($EP)
#Add new service endpoint
Get-AzureRmVirtualNetwork -ResourceGroupName $RG -Name $VN | Set-AzureRmVirtualNetworkSubnetConfig -Name $SN -AddressPrefix $SAP -ServiceEndpoint $ServiceEndPoint | Set-AzureRmVirtualNetwork
Powershell does not appear to support the command $ServiceEndPoint.Add("Microsoft.KeyVault") with “|”. Once it was executed separately, the script worked.
Here is another version for those looking to process multiple subnets and to validate that the subnet doesn't already have the service endpoint enabled because it will error out if the same service is listed twice when modifying the subnet.
$subscription = "Enter Subscription ID here"
$subnets = #('my-subnet-1','my-subnet-2','my-subnet-3')
$vnetName = "MY-VNET"
$vnetRgName = "MY-VNET-RG"
$newEndpoint = "Microsoft.AzureCosmosDB"
Set-AzContext -Subscription $subscription
foreach($snet in $subnets){
Write-Host "Modifying Service Endpoints for subnet: $snet" -fore red -back white
$virtualNetwork = Get-AzVirtualNetwork -Name $vnetName -ResourceGroupName $vnetRgName | Get-AzVirtualNetworkSubnetConfig -Name $snet
$addrPrefix = $virtualNetwork.AddressPrefix
#Get existing service endpoints
$ServiceEndPoint = New-Object 'System.Collections.Generic.List[String]'
$virtualNetwork.ServiceEndpoints | ForEach-Object { $ServiceEndPoint.Add($_.service) }
if ($ServiceEndPoint -notcontains $newEndPoint){
$ServiceEndPoint.Add($newEndpoint)
}
#Add new service endpoint
Get-AzVirtualNetwork -Name $vnetName -ResourceGroupName $vnetRgName | Set-AzVirtualNetworkSubnetConfig -Name $snet -AddressPrefix $addrPrefix -ServiceEndpoint $ServiceEndPoint | Set-AzVirtualNetwork
}

how to create multiple vms in azure resourcemanager portal with same NIC using powershell

I am trying to create multiple vms in azure resourcemanager portal with same NIC using powershell. But single VM alone getting created. when I use array for this exception occurs.
$i = 1;
[System.Collections.ArrayList]$vmArray1=#()
Do
{
$i;
switch($i){
{$vmName="Namenode"+$i}
{$vmName="Namenode"+$i}
default {$vmName="Datanode"+($i-2)}
}
$vmconfig=New-AzureRmVMConfig -VMName $vmName -VMSize $vmSize
$vmArray1.Add($vmconfig)
$i +=1
} Until ($i -gt $NumberOfVM)
$vm=Set-AzureRmVMOperatingSystem -VM $vmconfig -Windows -ComputerName $vmArray1 -Credential $credvm -ProvisionVMAgent -EnableAutoUpdate
But an exception occurs. Please let me know how to resolve this.
I am not sure whether it's your typing error or not. Your Set-AzureRmVMOperatingSystem Command is not inside the loop. That means it will always run only once. Beside of Operating System, you also need to provide Source Image, OS Disk, and Network Interface.
I have written something for you, and I have tested it at my end. It will create a set of VMs in one resource group and one Virtual Network. If you want the VMs in different resource groups or VNet, you can move the creation commands of resource groups or Vnet into the loop.
$credvm = Get-Credential
$NumberOfVM = <the number of VM you want to create>;
$ResourceGroupName = "<your resource group name>"
$Location = "East Asia"
## Storage
$StorageName = "<your storage account name>"
$StorageType = "Standard_GRS"
# Resource Group, if resource group has been created comment this out.
New-AzureRmResourceGroup -Name $ResourceGroupName -Location $Location
## Network
$InterfaceName = "<your interface name>"
$Subnet1Name = "Subnet1"
$VNetName = "<your vnet name>"
$VNetAddressPrefix = "10.0.0.0/16"
$VNetSubnetAddressPrefix = "10.0.0.0/24"
## Compute
$vmSize = "Standard_A2"
# Network
$SubnetConfig = New-AzureRmVirtualNetworkSubnetConfig -Name $Subnet1Name -AddressPrefix $VNetSubnetAddressPrefix
$VNet = New-AzureRmVirtualNetwork -Name $VNetName -ResourceGroupName $ResourceGroupName -Location $Location -AddressPrefix $VNetAddressPrefix -Subnet $SubnetConfig
$i = 1;
Do
{
$i;
$vmName="Namenode"+$i
$vmconfig=New-AzureRmVMConfig -VMName $vmName -VMSize $vmSize
$vm=Set-AzureRmVMOperatingSystem -VM $vmconfig -Windows -ComputerName $vmName -Credential $credvm -ProvisionVMAgent -EnableAutoUpdate
$OSDiskName = $vmName + "osDisk"
# Storage
$StorageAccount = New-AzureRmStorageAccount -ResourceGroupName $ResourceGroupName -Name $StorageName$i -Type $StorageType -Location $Location
## Setup local VM object
$vm = Set-AzureRmVMSourceImage -VM $vm -PublisherName MicrosoftWindowsServer -Offer WindowsServer -Skus 2012-R2-Datacenter -Version "latest"
$PIp = New-AzureRmPublicIpAddress -Name $InterfaceName$i -ResourceGroupName $ResourceGroupName -Location $Location -AllocationMethod Dynamic
$Interface = New-AzureRmNetworkInterface -Name $InterfaceName$i -ResourceGroupName $ResourceGroupName -Location $Location -SubnetId $VNet.Subnets[0].Id -PublicIpAddressId $PIp.Id
$VirtualMachine = Add-AzureRmVMNetworkInterface -VM $vm -Id $Interface.Id
$OSDiskUri = $StorageAccount.PrimaryEndpoints.Blob.ToString() + "vhds/" + $OSDiskName + ".vhd"
$VirtualMachine = Set-AzureRmVMOSDisk -VM $VirtualMachine -Name $OSDiskName -VhdUri $OSDiskUri -CreateOption FromImage
## Create the VM in Azure
New-AzureRmVM -ResourceGroupName $ResourceGroupName -Location $Location -VM $VirtualMachine
$i +=1
}
Until ($i -gt $NumberOfVM)

Resources