The task is to modify an Azure Network Security Group Rule.
I am all OK there (using az network nsg rule update ), provided the name of the NSG and the actual Rule.
But what I want to do is edit that rule with the VM Name (subscription ID, RG name and Rule name are already known and will be explicit) as the input parameter.
I am using az (not Az) commands.
What I see is az vm show, but it doesn't show which NSG the VM is connected to.
I would like to ask how to get the NSG name where a VM is associated, using CLI. Straight answers, guides or links to resources will all be appreciated.
Thank you and thanks in advance!
CodePudding user response:
Follow the Microsoft documentation below
Get-AzNetworkSecurityGroup [-Name <String>][-ResourceGroupName<String> [-DefaultProfile <IAzureContextContainer>][<CommonParameters>]
CodePudding user response:
You would also need to provide the Resource Group in which the VM is located - this is how it will be able to differentiate between two VM with same name in different Resource Groups. Here, {id:id}
creates a map that can be used with the subsequent commands. There are other ways to do this but I prefer this approach since I'm more familiar with the format.
Here's what you could do:
- Using the VM name and RG, get the VM's NIC's ID and save it to
nic_id
:
vm_name="myvm"
vm_rg="myrg"
nic_id=`az vm nic list -g $vm_rg --vm-name $vm_name --query "[].{id:id}"`
# echo to make sure we're getting the right value.
echo $nic_id
- Using the NIC ID, get the Subnet ID
snet_id=`az network nic show --ids $nic_id --query "ipConfigurations[0].subnet.{id:id}"`
# echo to make sure we're getting the right value.
echo $snet_id
- Finally, using the Subnet ID, get the NSG's name
nsg_name=`az network vnet subnet show --ids $snet_id --query networkSecurityGroup.{id:id} -o tsv | sed 's/^.*networkSecurityGroups\///'`
# echo to make sure we're getting the right value.
echo $nsg_name