I have got the code below which works fine, however the way in which I am checking if a vnet pairing is found is somewhat wrong.
This is what the code looks like.
$existing_peering = az network vnet peering show -g 'xx' -n 'ccc' --vnet-name 'ccc'
if ($existing_peering) {
write-output 'Peering exists'
}
The output of $existing_peering
is as follows.
{
"allowForwardedTraffic": true,
"allowGatewayTransit": true,
"allowVirtualNetworkAccess": true,
"doNotVerifyRemoteGateways": false,
"etag": "W/\"xxxxxx\"",
"id": "/subscriptions/fdfd",
"name": "xxxx",
"peeringState": "Disconnected",
"peeringSyncLevel": "FullyInSync",
"provisioningState": "Succeeded",
"remoteAddressSpace": {
"addressPrefixes": [
"10.77.0.0/16"
]
},
"remoteBgpCommunities": null,
"remoteVirtualNetwork": {
"id": "/subscriptions/",
"resourceGroup": "my-rg"
},
"remoteVirtualNetworkAddressSpace": {
"addressPrefixes": [
"10.77.0.0/16"
]
},
"remoteVirtualNetworkEncryption": null,
"resourceGroup": "cccc",
"resourceGuid": "ggggggggggg",
"type": "Microsoft.Network/virtualNetworks/virtualNetworkPeerings",
"useRemoteGateways": false
}
I would like to get the value of name
and the way the if statement has been evaluated, i am not sure if this is the correct way, sometimes I find that if AZ cli cannot find an object, the value if $existing_peering
could be an error message rather than the expected returned object, and when the IF
statement is valuated, it could be doing the wrong thing.
I have created virtual network and peered vnet with the name of vnet1-vnet2
like below:
To get the value of only name
you can make use of below command:
$existing_peering = az network vnet peering show -g "<RGName>" -n "<PeeredvnetName>" --vnet-name "<VnetName>" --query "name" --output tsv
if ($existing_peering) {
Write-Output "Peering exists: $existing_peering"
} else {
Write-Output "Peering does not exist"
}
Output:
Or as suggested by Abraham Zinala, you can use ConvertFrom-Json
to turn it into an object by modifying script like below:
$existing_peerings = az network vnet peering show -g "xxxx" -n "xxxx" --vnet-name "xxx" | ConvertFrom-Json
foreach ($peering_info in $existing_peerings) {
if ($peering_info.name) {
Write-Output 'Peering exists'
# You can access other properties like $peering_info.name here
}
}
Output: