0
votes

When I try to use Powershell to make a peering link in Azure, between vnets in different subscriptions but in the same tenant, I get the following error messages.

Without specifying tenant:

Set-AzureRmContext : Please provide a valid tenant or a valid subscription.

So I tried specifying the tenant:

Get-AzureRmSubscription : Subscription was not found in tenant ****. Please verify that the subscription exists in this tenant.

I'm using Jenkins with a root account that has access to the dev subscription. I'm setting those credentials using the Microsoft Azure Service Principal bindings, before the job is run.

Does anyone know how I can code my Powershell script so that the Azure end recognises the 2nd subscription ID that I'm trying to peer to?

Current code below.

Write-Host "Create Vnet Peering from dev-vnet to test-centralhub-vnet"

$Subscription1 = Get-AzureRmSubscription -TenantId '(sanitised for Stackoverflow)' -SubscriptionId '(sanitised for Stackoverflow)'
Set-AzureRmContext -Subscription $subscription1
$Vnet1 = Get-AzureRmVirtualNetwork -name 'test-centralhub-vnet' -ResourceGroupName 'test-networks-hub-rg'

$Subscription2 = Get-AzureRmSubscription -TenantId '(sanitised for Stackoverflow)' -SubscriptionId '(sanitised for Stackoverflow)'
Set-AzureRmContext -Subscription $Subscription2
$Vnet2 = Get-AzureRmVirtualNetwork -name 'dev-vnet' -ResourceGroupName 'networks-dev-rg'

Set-AzureRmContext -Subscription '(sanitised for Stackoverflow)'
Add-AzureRmVirtualNetworkPeering -Name 'dev-vnet_to_test-centralhub-vnet' -VirtualNetwork $Vnet2 -RemoteVirtualNetworkId $Vnet1.ID -UseRemoteGateways
1
Usually, that error indicates you don't have rights to that subscription. Are you sure you have access to both subs?Sam Cogan

1 Answers

1
votes

As the comment points out, the account you log in with must have the necessary permissions to create a virtual network peering. You can peer virtual networks that exist in two different subscriptions as long as a privileged user of both subscriptions authorizes the peering and the subscriptions are associated with the same Active Directory tenant.

For a list of permissions, see Virtual network peering permissions.

I just test this on my local Powershell. My account was assigned a contributor role in another subscription level, then run your Powershell scripts with the same account successfully.

If you create peering with a different account in the different subscription. You may log in to Azure by entering the Connect-AzureRmAccount command for each subscription. More details from Create peering - PowerShell. Note, the linking scripts are using new Az module. You can refer it to replace Az with AzureRm for AzureRm module.

enter image description here