List all the vm in a particular Subnet in Azure - azure

Just wondering how to retrieve the VMs details in a given particular subnet in Azure.
I have used the below but it does not work anymore in powershell (Cloud shell)
Listing all azure vm belonging to particular subnet
Any help will be appreciated.
Thanks

The following code snippet has been tested against my environment :
$vms = Get-AzVM
$tgtSubnet = "MySubnet"
foreach($vm in $vms)
{
$networkInterface = Get-AzNetworkInterface -Name ($vm.NetworkProfile.NetworkInterfaces[0].Id.Split('/')[-1])
$subnetName = $networkInterface.IpConfigurations[0].Subnet.Id.split('/')[-1]
if($subnetName -eq $tgtSubnet)
{
Write-Output $vm
}
}
output:
Make sure Azure PowerShell is installed on your machine.

Related

Can't configure network config on two azure web apps

Facing a problem about VNET and Azure Web Apps I don't understand.
My issue
This is my setting:
Two web apps on the same service plan SP1 (SP1 (P1v2: 1)) and a VNET, VNET1:
Both subnets have Microsoft.Web/serverFarms delegation.
I want to add network config on my webapps webapps1 and webapps4.
I run this PowerShell script:
properties = #{
subnetResourceId = "/subscriptions/XXX/resourceGroups/RG1/providers/Microsoft.Network/virtualNetworks/vnet1/subnets/sub01"
}
$vNetParams = #{
ResourceName = "mywebapps1/VirtualNetwork"
Location = "West Europe"
ResourceGroupName = "RG1"
ResourceType = "Microsoft.Web/sites/networkConfig"
PropertyObject = $properties
}
$result = New-AzResource #vNetParams -Force
$properties = #{
subnetResourceId = "/subscriptions/XXX/resourceGroups/RG1/providers/Microsoft.Network/virtualNetworks/vnet1/subnets/sub02"
}
$vNetParams = #{
ResourceName = "mywebapps4/VirtualNetwork"
Location = "West Europe"
ResourceGroupName = "RG1"
ResourceType = "Microsoft.Web/sites/networkConfig"
PropertyObject = $properties
}
$result = New-AzResource #vNetParams -Force
First new-azresource works fine:
But the second one throw this error message:
New-AzResource : {"Code":"Conflict","Message":"Adding this VNET would
exceed the App Service Plan VNET limit of 1
What I did
I search for this error message. But found only one situation that did not help me or maybe I did not understand.
What I need
Understand what it means.
How I should do
Thank you
Regional virtual integration can use One virtual interface per worker means one regional virtual network integration per App Service plan. All the apps in the same App Service plan can only use the same virtual network integration to a specific subnet.
Gate-way required virtual network integration Enables an app to connect to only one virtual network at a time.
This can Enables up to five virtual networks to be integrated within an App Service plan.
Refer to this documentation for more information about different virtual network integrations and their limitations as well.
For more information you can refer to these similar threads:
https://social.msdn.microsoft.com/Forums/en-US/a8b51183-d94b-48c9-9b6c-e6a4dbec9919/vnet-integration-limit-of-1?forum=azureappconfiguration
As per my understanding you're getting desired output. Please note that you are using New-AzResource which basically creates resources instead you should use Set-AzResource command.
Suggestion
Use Set-AzResource instead of New-AzResource
Configure VNet Integration
$subnetResourceId = "/subscriptions/$subscriptionId/resourceGroups/$resourceGroupName/providers/Microsoft.Network/virtualNetworks/$vNetName/subnets/$integrationSubnetName"
$webApp = Get-AzResource -ResourceType Microsoft.Web/sites -ResourceGroupName $resourceGroupName -ResourceName $siteName
$webApp.Properties.virtualNetworkSubnetId = $subnetResourceId
$webApp | Set-AzResource -Force
Regional VNet integration feature basically creates association or link between Microsoft.Network/VirtualNetwork and Microsoft.Web/Serverfarm resources using Rest API call.
In this scenario you're using New-AzResoruce which invoke REST API for creation of service association which is already existed hence its throwing error. If you try to do it from portal you shouldn't get that as portal validation takes care of type of REST API call.

Getting vnet integration infos from a service plan

CONTEXT
Whe deploy an Azure Function with a vnet integration with a code like this:
$properties = #{
subnetResourceId = $subnet.Id
}
$vNetParams = #{
ResourceName = "$webapp/VirtualNetwork"
Location = $Location
ResourceGroupName = $ResourceGroupName
ResourceType = "Microsoft.Web/sites/networkConfig"
PropertyObject = $properties
}
$result = New-AzResource #vNetParams -Force
This works fine.
The project get $subnet by looking an available subnet into a spoke VNET.
So I don't want to run the previous code when a VNET integration already exists.
WHAT I NEED
A way to know if a Function has already a VNET integration
WHAT I TESTED
Get-AzFunctionApp -ResourceGroupName $ResourceGroupName -Name $webapp
Get-AzFunctionAppPlan -ResourceGroupName $ResourceGroupName -Name $servicePlan
Get-AzAppServicePlan -ResourceGroupName $ResourceGroupName -Name $servicePlan
Returns no vnet informations
Get-AzResource doesn't work with this resource: "$webapp/VirtualNetwork" (not found)
To check if a function app has already a vnet integration, just use the command below.
$VnetName = (Get-AzFunctionApp -ResourceGroupName <groupname> -Name <functionappname>).SiteConfig.VnetName
if($VnetName){
Write-Output "already intergration"
}
There is a way to figure this in portal.
Navigate to Azure portal
Select the corresponding Web App or Function App
Navigate to "Diagnose and solve problems" and search for "VNet Integration Information"
This will load a blade, which will have details of the Web App in that App Service Plan
This is what the UI looks like

How to get the NIC details for Application Security Group / Resource Group

I'm looking a PowerShell command which is used to list out the relationship between the network interface card and its associated application security group / resources group. I use the following commands and it only displays the VMName, IPAddress. The Application Security Group cannot be shown up.
I already use -ExpandProperty ApplicationSecurityGroups but still doesn't work.
$nics =Get-AzureRmNetworkInterface -ResourceGroupName "My-RG"
foreach($nic in $nics)
{
$vm = $vms | where-object -Property Id -EQ $nic.VirtualMachine.id
$Name = $nic.Name
$prv = $nic.IpConfigurations | select-object -ExpandProperty PrivateIpAddress
$alloc = $nic.IpConfigurations | select-object -ExpandProperty PrivateIpAllocationMethod
$asc = $nic.IpConfigurations | select-object -ExpandProperty ApplicationSecurityGroups
Write-Output "$Name, $prv , $asc"
}
It is quite hard to retrospectively query members of an ASG, the property is contained in arrays within arrays in the NIC configuration. I found an AZ cli command to retrieve this, hope it saves some time.
az network nic list --query '[].{Name:name,ASG:ipConfigurations[0].applicationSecurityGroups[].id}'
I've just tested your commands and I can get the application security group successfully, from a machine that is configured with an ASG. However, that will only work if you have put the VM in an ASG, ASG's are there to provide micro-segmentation inside a subnet, so you can group your app servers, DBs etc. together and apply NSG rules to groups rather than single servers.
If instead, you want to know what NSG the VM is in, you need a different command. NSG's are the resource that attaches to a VM or NIC and acts like a firewall. If you want that then you need to run:
$nsg = $nic | select-object -ExpandProperty NetworkSecurityGroup
However, this is only going to get you the NSG applied to the VM, you can also apply these at the VM level, so you are better running this command:
$effectiveRules=Get-AzureRmEffectiveNetworkSecurityGroup -NetworkInterfaceName <nicName> -ResourceGroupName <resourceGroup>
$effectiveRules.NetworSecurityGroup
This will list all NSGs applied either at NIC or Subnet level.
The thing is that you can only get the ASG information from property IpConfigurationsText as a string, so you'll need to update your query to this:
$nics = Get-AzureRmNetworkInterface -ResourceGroupName "My-RG"
foreach($nic in $nics)
{
$GetAzureNIC = Get-AzureRmNetworkInterface -ResourceGroupName "My-RG" -Name $nic.Name
$Name = $nic.Name
$prv = $nic.IpConfigurations.PrivateIpAddress
$alloc = $nic.IpConfigurations.PrivateIpAllocationMethod
$asgResourceID = ($GetAzureNIC.IpConfigurationsText | ConvertFrom-Json).ApplicationSecurityGroups.Id
$asgName = (Get-AzureRmResource -ResourceId $asgResourceID).Name
Write-Output "$Name, $prv, $alloc, $asgName, $asgResourceID"
}
EDIT: I've noticed that you also want to get the allocation method but don't use it in the Write-Output and updated the query to include both ASG name and ASG resource ID, pick whichever you need.

AzureRmVM - Obtaining VMs Public IP addresses

I am trying to obtain IP addresses for all my virtual machines within my azure subscription. While I get the IP addresses of all my NICs, I can't seem to get them for my VMs. I am using AzureRm and powershell to obtain this information.
How do I obtain IP addresses of all my VMs within Azure using AzureRm?
You can use Azure PowerShell to get all the VM Public IPs, but there is something you should pay attention to.
The VM can be associated with more than one network interface and each network interface can also associate with a public Ip.
I assume that your VMs in the same resource group and each VM just have one network interface. Then the PowerShell script will like this:
$vms = Get-AzureRmVM -ResourceGroupName yourRGName
foreach ($vm in $vms)
{
$vmName = $vm.Name
$nic = $vm.NetworkProfile.NetworkInterfaces[0].Id.Split('/') | select -Last 1
if ( (Get-AzureRmNetworkInterface -ResourceGroupName yourRGName -Name $nic).IpConfigurations.PublicIpAddress -eq $null )
{
continue
}
$publicIpName = (Get-AzureRmNetworkInterface -ResourceGroupName yourRGName -Name $nic).IpConfigurations.PublicIpAddress.Id.Split('/') | select -Last 1
$publicIpAddress = (Get-AzureRmPublicIpAddress -ResourceGroupName yourRGName -Name $publicIpName).IpAddress
Write-Output $vmName $publicIpAddress
}
The result will like this:
If your VMs in the different resource groups, you can first get the VMs information and then everything is on the way. If there just exist your VMs in subscription, you can get all the VMs with the PowerShell command Get-azureRMVM when you log in the subscription. But if they're not just your VMs in the subscription, I think you'd better get all your VMs through resource groups. Hope this will help you.
Because IP addresses in ARM are assigned to NICs not VM. You will have write a script to look at NICs assigned to VMs and look for IPs on those NICs.
You may refer the following steps to get all the public IP addresses in a Azure Subscription.
Gets all the public IP addresses in a subscription.
GET https://management.azure.com/subscriptions/{subscriptionId}/providers/Microsoft.Network/publicIPAddresses?api-version=2018-08-01
Click on Try it
=> Sign in => Pick an Azure account => Select subscription Id => Run
Check out the Public IP addresses in the subscription:
Note: Only running VMs will have public IP address.
For more details, refer "Public IP Address - List All".
Hope this helps.
Riffing on Charles Xu's excellent answer....
Converted to use the new 'Az' powershell module
foreach ($vm in $vms)
{
$vmName = $vm.Name
$resgrpName = $vm.ResourceGroupName
$nic = $vm.NetworkProfile.NetworkInterfaces[0].Id.Split('/') | select -Last 1
if ( (Get-AzNetworkInterface -ResourceGroupName $resgrpName -Name $nic).IpConfigurations.PublicIpAddress -eq $null )
{
continue
}
$publicIpName = (Get-AzNetworkInterface -ResourceGroupName $resgrpName -Name $nic).IpConfigurations.PublicIpAddress.Id.Split('/') | select -Last 1
$publicIpAddress = (Get-AzPublicIpAddress -ResourceGroupName $resgrpName -Name $publicIpName).IpAddress
Write-Output $vmName $publicIpAddress
}
It's wicked-slow, but does the job!

Get private IP of VM in Azure Dev Test Lab using Powershell

Just now I started with Azure DevTest Lab. I created a VM in lab using a json template. I want to use the public IP of the VM using powershell or may be I would like to return the same using template, if I can.
The challenge here is as per DTL concept the VM is created in a new resource group other than the one where your lab exists. I can definitely see the name of resource group of lab VM on portal but I am not able to figure out how this can be done using powershell. I am working on an automation so I need to do it by powershell.
Refer to the picture. The lab seems to be in a resource group in the same where the lab exist shown in green box. But, technically the lab VM resides in dynamically created resource gruop (RG name pattern = labname + VM name + Some Random digits) shown in light yellow in screenshot.
Other solutions are helpful but not complete. I am doing in this way - I am returning the default output of template that is vmId. Refer from template link
Now we need to manipulate this vmId to get the name of resource group where the lab VM has been created.
$result = New-AzureRmResourceGroupDeployment -ResourceGroupName "aatifdtlrg207912" -TemplateFile "D:\AzureDeploy.json" -TemplateParameterObject $paramValues
$VMId = $result.outputs.Values.value
$VMComputeId = (Get-AzureRmResource -Id $VMId).Properties.ComputeId
$RGNameofVM = $VMComputeId.split("/")
$RGNameofVM = $RGNameofVM[4]
$IP = (Get-AzureRmNetworkInterface -Name $VMName -ResourceGroupName $RGNameofVM ).IpConfigurations.PrivateIpAddress
Well, generally a more elegant solution, oposed to bruteforce would be to use Get-AzureRmResource
$Resource = Get-AzureRmResource -ResourceId "/subscriptions/$sub_GUID/resourcegroups/$RG_devlab_Name/providers/microsoft.devtestlab/labs/$LabName/virtualmachines/$VMName"
$Resource.Properties.computeId -match 'resourceGroups/(.+)/providers'
$RGName = $Matches[1]
$IP = (Get-AzureRmNetworkInterface -Name $VMName-ResourceGroupName $RGName).IpConfigurations.PrivateIpAddress
Well, as we know for DevTest Labs there is no direct way for powershell. You can use the below powershell script to get the Private IP Address of the VM by just passing the Virtual machine name. We can use Find-AzureRmResource and Get-AzureRmResource by passing the ResourceId:
$vmNicdetails = Find-AzureRmResource -ResourceNameContains mytestVM | Where {$_.ResourceType -eq 'Microsoft.Network/networkInterfaces'}
$nicdetails = Get-AzureRmResource -ResourceId $vmNicdetails.ResourceId
$ipconfig = Get-AzureRmResource -ResourceId
$nicdetails.Properties.ipConfigurations.id -ApiVersion '2017-03-01'
$ipconfig.Properties.privateIPAddress

Resources