/** * Azure Network sample for enabling and updating network peering between two virtual networks * * Summary ... * * - This sample uses Azure Network Watcher's connectivity check to verify connectivity between * two peered virtual networks. * * Details ... * * 1. Define two virtual networks network "A" and network "B" with one subnet each * * 2. Create two virtual machines, each within a separate network * - The virtual machines currently must use a special extension to support Network Watcher * * 3. Peer the networks... * - the peering will initially have default settings: * - each network's IP address spaces will be accessible from the other network * - no traffic forwarding will be enabled between the networks * - no gateway transit between one network and the other will be enabled * * 4. Use Network Watcher to check connectivity between the virtual machines in different peering scenarios: * - both virtual machines accessible to each other (bi-directional) * - virtual machine A accessible to virtual machine B, but not the other way */ public static void RunSample(IAzure azure) { Region region = Region.USEast; string resourceGroupName = SdkContext.RandomResourceName("rg", 15); string vnetAName = SdkContext.RandomResourceName("net", 15); string vnetBName = SdkContext.RandomResourceName("net", 15); string[] vmNames = SdkContext.RandomResourceNames("vm", 15, 2); string[] vmIPAddresses = new String[] { /* within subnetA */ "10.0.0.8", /* within subnetB */ "10.1.0.8" }; string peeringABName = SdkContext.RandomResourceName("peer", 15); string rootname = "tirekicker"; string password = SdkContext.RandomResourceName("pWd!", 15); string networkWatcherName = SdkContext.RandomResourceName("netwch", 20); try { //============================================================= // Define two virtual networks to peer and put the virtual machines in, at specific IP addresses List <ICreatable <INetwork> > networkDefinitions = new List <ICreatable <INetwork> >(); networkDefinitions.Add(azure.Networks.Define(vnetAName) .WithRegion(region) .WithNewResourceGroup(resourceGroupName) .WithAddressSpace("10.0.0.0/27") .WithSubnet("subnetA", "10.0.0.0/27")); networkDefinitions.Add(azure.Networks.Define(vnetBName) .WithRegion(region) .WithNewResourceGroup(resourceGroupName) .WithAddressSpace("10.1.0.0/27") .WithSubnet("subnetB", "10.1.0.0/27")); //============================================================= // Define a couple of Windows VMs and place them in each of the networks List <ICreatable <IVirtualMachine> > vmDefinitions = new List <ICreatable <IVirtualMachine> >(); for (int i = 0; i < networkDefinitions.Count; i++) { vmDefinitions.Add(azure.VirtualMachines.Define(vmNames[i]) .WithRegion(region) .WithExistingResourceGroup(resourceGroupName) .WithNewPrimaryNetwork(networkDefinitions[i]) .WithPrimaryPrivateIPAddressStatic(vmIPAddresses[i]) .WithoutPrimaryPublicIPAddress() .WithPopularWindowsImage(KnownWindowsVirtualMachineImage.WindowsServer2012R2Datacenter) .WithAdminUsername(rootname) .WithAdminPassword(password) // Extension currently needed for network watcher support .DefineNewExtension("packetCapture") .WithPublisher("Microsoft.Azure.NetworkWatcher") .WithType("NetworkWatcherAgentWindows") .WithVersion("1.4") .Attach()); } // Create the VMs in parallel for better performance Utilities.Log("Creating virtual machines and virtual networks..."); var createdVMs = azure.VirtualMachines.Create(vmDefinitions); IVirtualMachine vmA = createdVMs.FirstOrDefault(vm => vm.Key == vmDefinitions[0].Key); IVirtualMachine vmB = createdVMs.FirstOrDefault(vm => vm.Key == vmDefinitions[1].Key); Utilities.Log("Created the virtual machines and networks."); //============================================================= // Peer the two networks using default settings INetwork networkA = vmA.GetPrimaryNetworkInterface().PrimaryIPConfiguration.GetNetwork(); INetwork networkB = vmB.GetPrimaryNetworkInterface().PrimaryIPConfiguration.GetNetwork(); Utilities.PrintVirtualNetwork(networkA); Utilities.PrintVirtualNetwork(networkB); Utilities.Log( "Peering the networks using default settings...\n" + "- Network access enabled\n" + "- Traffic forwarding disabled\n" + "- Gateway use (transit) by the remote network disabled"); INetworkPeering peeringAB = networkA.Peerings.Define(peeringABName) .WithRemoteNetwork(networkB) .Create(); Utilities.PrintVirtualNetwork(networkA); Utilities.PrintVirtualNetwork(networkB); //============================================================= // Check connectivity between the two VMs/networks using Network Watcher INetworkWatcher networkWatcher = azure.NetworkWatchers.Define(networkWatcherName) .WithRegion(region) .WithExistingResourceGroup(resourceGroupName) .Create(); // Verify bi-directional connectivity between the VMs on port 22 (SSH enabled by default on Linux VMs) IExecutable <IConnectivityCheck> connectivityAtoB = networkWatcher.CheckConnectivity() .ToDestinationAddress(vmIPAddresses[1]) .ToDestinationPort(22) .FromSourceVirtualMachine(vmA); Utilities.Log("Connectivity from A to B: " + connectivityAtoB.Execute().ConnectionStatus); IExecutable <IConnectivityCheck> connectivityBtoA = networkWatcher.CheckConnectivity() .ToDestinationAddress(vmIPAddresses[0]) .ToDestinationPort(22) .FromSourceVirtualMachine(vmB); Utilities.Log("Connectivity from B to A: " + connectivityBtoA.Execute().ConnectionStatus); // Change the peering to allow access between A and B Utilities.Log("Changing the peering to disable access between A and B..."); peeringAB.Update() .WithoutAccessFromEitherNetwork() .Apply(); Utilities.PrintVirtualNetwork(networkA); Utilities.PrintVirtualNetwork(networkB); // Verify connectivity no longer possible between A and B Utilities.Log("Peering configuration changed.\nNow, A should be unreachable from B, and B should be unreachable from A..."); Utilities.Log("Connectivity from A to B: " + connectivityAtoB.Execute().ConnectionStatus); Utilities.Log("Connectivity from B to A: " + connectivityBtoA.Execute().ConnectionStatus); } finally { try { Utilities.Log("Deleting Resource Group: " + resourceGroupName); azure.ResourceGroups.BeginDeleteByName(resourceGroupName); } catch (NullReferenceException) { Utilities.Log("Did not create any resources in Azure. No clean up is necessary"); } catch (Exception ex) { Utilities.Log(ex); } } }
public void CreateUpdatePeering() { using (var context = FluentMockContext.Start(GetType().FullName)) { var testId = TestUtilities.GenerateName(""); Region region = Region.USEast; string groupName = "rg" + testId; string networkName = "netA" + testId; string networkName2 = "netB" + testId; var networks = TestHelper.CreateNetworkManager().Networks; try { // Create networks ICreatable <INetwork> remoteNetworkDefinition = networks.Define(networkName2) .WithRegion(region) .WithNewResourceGroup(groupName) .WithAddressSpace("10.1.0.0/27") .WithSubnet("subnet3", "10.1.0.0/27"); ICreatable <INetwork> localNetworkDefinition = networks.Define(networkName) .WithRegion(region) .WithNewResourceGroup(groupName) .WithAddressSpace("10.0.0.0/27") .WithSubnet("subnet1", "10.0.0.0/28") .WithSubnet("subnet2", "10.0.0.16/28"); var createdNetworks = networks.Create(remoteNetworkDefinition, localNetworkDefinition); INetwork localNetwork = createdNetworks.FirstOrDefault(o => o.Key == localNetworkDefinition.Key); Assert.NotNull(localNetwork); INetwork remoteNetwork = createdNetworks.FirstOrDefault(o => o.Key == remoteNetworkDefinition.Key); Assert.NotNull(remoteNetwork); // Create peering INetworkPeering localPeering = localNetwork.Peerings.Define("peer0") .WithRemoteNetwork(remoteNetwork) // Optionals .WithTrafficForwardingBetweenBothNetworks() .WithoutAccessFromEitherNetwork() .WithGatewayUseByRemoteNetworkAllowed() .Create(); // Verify local peering Assert.NotNull(localNetwork.Peerings); var localPeerings = localNetwork.Peerings.List(); Assert.Single(localPeerings); localPeering = localPeerings.FirstOrDefault(); Assert.NotNull(localPeering); Assert.Equal("peer0", localPeering.Name, true); Assert.Equal(VirtualNetworkPeeringState.Connected, localPeering.State); Assert.True(localPeering.IsTrafficForwardingFromRemoteNetworkAllowed); Assert.False(localPeering.CheckAccessBetweenNetworks()); Assert.Equal(NetworkPeeringGatewayUse.ByRemoteNetwork, localPeering.GatewayUse); // Verify remote peering Assert.NotNull(remoteNetwork.Peerings); Assert.Single(remoteNetwork.Peerings.List()); INetworkPeering remotePeering = localPeering.GetRemotePeering(); Assert.NotNull(remotePeering); Assert.Equal(localNetwork.Id, remotePeering.RemoteNetworkId, true); Assert.Equal(VirtualNetworkPeeringState.Connected, remotePeering.State); Assert.True(remotePeering.IsTrafficForwardingFromRemoteNetworkAllowed); Assert.False(remotePeering.CheckAccessBetweenNetworks()); Assert.Equal(NetworkPeeringGatewayUse.None, remotePeering.GatewayUse); // Update peering localPeering = localNetwork.Peerings.List().FirstOrDefault(); Assert.NotNull(localPeering); // Verify remote IP invisibility to local network before peering remoteNetwork = localPeering.GetRemoteNetwork(); Assert.NotNull(remoteNetwork); ISubnet remoteSubnet = remoteNetwork.Subnets["subnet3"]; Assert.NotNull(remoteSubnet); var remoteAvailableIPs = remoteSubnet.ListAvailablePrivateIPAddresses(); Assert.NotNull(remoteAvailableIPs); Assert.NotEmpty(remoteAvailableIPs); string remoteTestIP = remoteAvailableIPs.FirstOrDefault(); Assert.False(localNetwork.IsPrivateIPAddressAvailable(remoteTestIP)); localPeering.Update() .WithoutTrafficForwardingFromEitherNetwork() .WithAccessBetweenBothNetworks() .WithoutAnyGatewayUse() .Apply(); // Verify local peering changes Assert.False(localPeering.IsTrafficForwardingFromRemoteNetworkAllowed); Assert.True(localPeering.CheckAccessBetweenNetworks()); Assert.Equal(NetworkPeeringGatewayUse.None, localPeering.GatewayUse); // Verify remote peering changes remotePeering = localPeering.GetRemotePeering(); Assert.NotNull(remotePeering); Assert.False(remotePeering.IsTrafficForwardingFromRemoteNetworkAllowed); Assert.True(remotePeering.CheckAccessBetweenNetworks()); Assert.Equal(NetworkPeeringGatewayUse.None, remotePeering.GatewayUse); // Delete the peering localNetwork.Peerings.DeleteById(remotePeering.Id); // Verify deletion Assert.Empty(localNetwork.Peerings.List()); Assert.Empty(remoteNetwork.Peerings.List()); // Cleanup networks.Manager.ResourceManager.ResourceGroups.BeginDeleteByName(groupName); } finally { try { TestHelper.CreateResourceManager().ResourceGroups.DeleteByName(groupName); } catch { } } } }
/** * Azure Network sample for enabling and updating network peering between two virtual networks * * Summary ... * * - This sample creates two virtual networks in the same subscription and then peers them, modifying various options on the peering. * * Details ... * * 1. Create two virtual networks, network "A" and network "B"... * - network A with two subnets * - network B with one subnet * - the networks' address spaces must not overlap * - the networks must be in the same region * * 2. Peer the networks... * - the peering will initially have default settings: * - each network's IP address spaces will be accessible from the other network * - no traffic forwarding will be enabled between the networks * - no gateway transit between one network and the other will be enabled * * 3. Update the peering... * - disable IP address space between the networks * - enable traffic forwarding from network A to network B * * 4. Delete the peering * - the removal of the peering takes place on both networks, as long as they are in the same subscription * * Notes: * - Once a peering is created, it cannot be pointed at another remote network later. * - The address spaces of the peered networks cannot be changed as long as the networks are peered. * - Gateway transit scenarios as well as peering networks in different subscriptions are possible but beyond the scope of this sample. * - Network peering in reality results in pairs of peering objects: one pointing from one network to the other, * and the other peering object pointing the other way. For simplicity though, the SDK provides a unified way to * manage the peering as a whole, in a single command flow, without the need to duplicate commands for both sides of the peering, * while enforcing the required restrictions between the two peerings automatically, as this sample shows. But it is also possible * to modify each peering separately, which becomes required when working with networks in different subscriptions. */ public static void RunSample(IAzure azure) { Region region = Region.USEast; string resourceGroupName = SdkContext.RandomResourceName("rg", 15); string vnetAName = SdkContext.RandomResourceName("net", 15); string vnetBName = SdkContext.RandomResourceName("net", 15); string peeringABName = SdkContext.RandomResourceName("peer", 15); try { //============================================================= // Define two virtual networks to peer Utilities.Log("Creating two virtual networks in the same region and subscription..."); ICreatable <INetwork> networkADefinition = azure.Networks.Define(vnetAName) .WithRegion(region) .WithNewResourceGroup(resourceGroupName) .WithAddressSpace("10.0.0.0/27") .WithSubnet("subnet1", "10.0.0.0/28") .WithSubnet("subnet2", "10.0.0.16/28"); ICreatable <INetwork> networkBDefinition = azure.Networks.Define(vnetBName) .WithRegion(region) .WithNewResourceGroup(resourceGroupName) .WithAddressSpace("10.1.0.0/27") .WithSubnet("subnet3", "10.1.0.0/27"); // Create the networks in parallel for better performance var created = azure.Networks.Create(networkADefinition, networkBDefinition); // Print virtual network details foreach (INetwork network in created) { Utilities.PrintVirtualNetwork(network); Utilities.Log(); } // Retrieve the created networks using their definition keys INetwork networkA = created.FirstOrDefault(n => n.Key == networkADefinition.Key); INetwork networkB = created.FirstOrDefault(n => n.Key == networkBDefinition.Key); //============================================================= // Peer the two networks using default settings Utilities.Log( "Peering the networks using default settings...\n" + "- Network access enabled\n" + "- Traffic forwarding disabled\n" + "- Gateway use (transit) by the peered network disabled"); INetworkPeering peeringAB = networkA.Peerings.Define(peeringABName) .WithRemoteNetwork(networkB) .Create(); // This implicitly creates a matching peering object on network B as well, if both networks are in the same subscription // Print network details showing new peering Utilities.Log("Created a peering"); Utilities.PrintVirtualNetwork(networkA); Utilities.PrintVirtualNetwork(networkB); //============================================================= // Update a the peering disallowing access from B to A but allowing traffic forwarding from B to A Utilities.Log("Updating the peering ..."); peeringAB.Update() .WithoutAccessFromEitherNetwork() .WithTrafficForwardingFromRemoteNetwork() .Apply(); Utilities.Log("Updated the peering to disallow network access between B and A but allow traffic forwarding from B to A."); //============================================================= // Show the new network information Utilities.PrintVirtualNetwork(networkA); Utilities.PrintVirtualNetwork(networkB); //============================================================= // Remove the peering Utilities.Log("Deleting the peering from the networks..."); networkA.Peerings.DeleteById(peeringAB.Id); // This deletes the peering from both networks, if they're in the same subscription Utilities.Log("Deleted the peering from both sides."); Utilities.PrintVirtualNetwork(networkA); Utilities.PrintVirtualNetwork(networkB); } finally { try { Utilities.Log("Deleting Resource Group: " + resourceGroupName); azure.ResourceGroups.BeginDeleteByName(resourceGroupName); } catch (NullReferenceException) { Utilities.Log("Did not create any resources in Azure. No clean up is necessary"); } catch (Exception ex) { Utilities.Log(ex); } } }