/** * Azure Network sample for managing virtual network gateway. * - Create 2 virtual networks with subnets and 2 virtual network gateways corresponding to each network * - Create VPN VNet-to-VNet connection * - Troubleshoot the connection * - Create network watcher in the same region as virtual network gateway * - Create storage account to store troubleshooting information * - Run troubleshooting for the connection - result will be 'UnHealthy' as need to create symmetrical connection from second gateway to the first * - Create virtual network connection from second gateway to the first and run troubleshooting. Result will be 'Healthy'. * - List VPN Gateway connections for the first gateway * - Create 2 virtual machines, each one in its network and verify connectivity between them */ public static void RunSample(IAzure azure) { string rgName = SdkContext.RandomResourceName("rg", 24); string vnetName = SdkContext.RandomResourceName("vnet", 20); string vnet2Name = SdkContext.RandomResourceName("vnet", 20); string vpnGatewayName = SdkContext.RandomResourceName("vngw", 20); string vpnGateway2Name = SdkContext.RandomResourceName("vngw2", 20); string connectionName = SdkContext.RandomResourceName("con", 20); string connection2Name = SdkContext.RandomResourceName("con2", 20); string nwName = SdkContext.RandomResourceName("nw", 20); string vm1Name = SdkContext.RandomResourceName("vm1", 20); string vm2Name = SdkContext.RandomResourceName("vm2", 20); string rootname = Utilities.CreateUsername(); string password = SdkContext.RandomResourceName("pWd!", 15); string containerName = "results"; try { //============================================================ // Create virtual network Utilities.Log("Creating virtual network..."); INetwork network1 = azure.Networks.Define(vnetName) .WithRegion(region) .WithNewResourceGroup(rgName) .WithAddressSpace("10.11.0.0/16") .WithSubnet("GatewaySubnet", "10.11.255.0/27") .WithSubnet("Subnet1", "10.11.0.0/24") .Create(); Utilities.Log("Created network"); // Print the virtual network Utilities.PrintVirtualNetwork(network1); //============================================================ // Create virtual network gateway Utilities.Log("Creating virtual network gateway..."); IVirtualNetworkGateway vngw1 = azure.VirtualNetworkGateways.Define(vpnGatewayName) .WithRegion(region) .WithNewResourceGroup(rgName) .WithExistingNetwork(network1) .WithRouteBasedVpn() .WithSku(VirtualNetworkGatewaySkuName.VpnGw1) .Create(); Utilities.Log("Created virtual network gateway"); //============================================================ // Create second virtual network Utilities.Log("Creating virtual network..."); INetwork network2 = azure.Networks.Define(vnet2Name) .WithRegion(region) .WithNewResourceGroup(rgName) .WithAddressSpace("10.41.0.0/16") .WithSubnet("GatewaySubnet", "10.41.255.0/27") .WithSubnet("Subnet2", "10.41.0.0/24") .Create(); Utilities.Log("Created virtual network"); //============================================================ // Create second virtual network gateway Utilities.Log("Creating second virtual network gateway..."); IVirtualNetworkGateway vngw2 = azure.VirtualNetworkGateways.Define(vpnGateway2Name) .WithRegion(region) .WithNewResourceGroup(rgName) .WithExistingNetwork(network2) .WithRouteBasedVpn() .WithSku(VirtualNetworkGatewaySkuName.VpnGw1) .Create(); Utilities.Log("Created second virtual network gateway"); //============================================================ // Create virtual network gateway connection Utilities.Log("Creating virtual network gateway connection..."); IVirtualNetworkGatewayConnection connection = vngw1.Connections .Define(connectionName) .WithVNetToVNet() .WithSecondVirtualNetworkGateway(vngw2) .WithSharedKey("MySecretKey") .Create(); Utilities.Log("Created virtual network gateway connection"); //============================================================ // Troubleshoot the connection // create Network Watcher INetworkWatcher nw = azure.NetworkWatchers.Define(nwName) .WithRegion(region) .WithExistingResourceGroup(rgName) .Create(); // Create storage account to store troubleshooting information IStorageAccount storageAccount = azure.StorageAccounts.Define("sa" + SdkContext.RandomResourceName("", 8)) .WithRegion(region) .WithExistingResourceGroup(rgName) .Create(); // Create storage container to store troubleshooting results string accountKey = storageAccount.GetKeys()[0].Value; string connectionString = string.Format("DefaultEndpointsProtocol=https;AccountName={0};AccountKey={1}", storageAccount.Name, accountKey); Utilities.CreateContainer(connectionString, containerName); // Run troubleshooting for the connection - result will be 'UnHealthy' as need to create symmetrical connection from second gateway to the first ITroubleshooting troubleshooting = nw.Troubleshoot() .WithTargetResourceId(connection.Id) .WithStorageAccount(storageAccount.Id) .WithStoragePath(storageAccount.EndPoints.Primary.Blob + containerName) .Execute(); Utilities.Log("Troubleshooting status is: " + troubleshooting.Code); //============================================================ // Create virtual network connection from second gateway to the first and run troubleshooting. Result will be 'Healthy'. vngw2.Connections .Define(connection2Name) .WithVNetToVNet() .WithSecondVirtualNetworkGateway(vngw1) .WithSharedKey("MySecretKey") .Create(); // Delay before running troubleshooting to wait for connection settings to propagate SdkContext.DelayProvider.Delay(250000); troubleshooting = nw.Troubleshoot() .WithTargetResourceId(connection.Id) .WithStorageAccount(storageAccount.Id) .WithStoragePath(storageAccount.EndPoints.Primary.Blob + containerName) .Execute(); Utilities.Log("Troubleshooting status is: " + troubleshooting.Code); //============================================================ // List VPN Gateway connections for particular gateway var connections = vngw1.ListConnections(); foreach (var conn in connections) { Utilities.Print(conn); } //============================================================ // Create 2 virtual machines, each one in its network and verify connectivity between them List <ICreatable <IVirtualMachine> > vmDefinitions = new List <ICreatable <IVirtualMachine> >(); vmDefinitions.Add(azure.VirtualMachines.Define(vm1Name) .WithRegion(region) .WithExistingResourceGroup(rgName) .WithExistingPrimaryNetwork(network1) .WithSubnet("Subnet1") .WithPrimaryPrivateIPAddressDynamic() .WithoutPrimaryPublicIPAddress() .WithPopularLinuxImage(KnownLinuxVirtualMachineImage.UbuntuServer16_04_Lts) .WithRootUsername(rootname) .WithRootPassword(password) // Extension currently needed for network watcher support .DefineNewExtension("networkWatcher") .WithPublisher("Microsoft.Azure.NetworkWatcher") .WithType("NetworkWatcherAgentLinux") .WithVersion("1.4") .Attach()); vmDefinitions.Add(azure.VirtualMachines.Define(vm2Name) .WithRegion(region) .WithExistingResourceGroup(rgName) .WithExistingPrimaryNetwork(network2) .WithSubnet("Subnet2") .WithPrimaryPrivateIPAddressDynamic() .WithoutPrimaryPublicIPAddress() .WithPopularLinuxImage(KnownLinuxVirtualMachineImage.UbuntuServer16_04_Lts) .WithRootUsername(rootname) .WithRootPassword(password) // Extension currently needed for network watcher support .DefineNewExtension("networkWatcher") .WithPublisher("Microsoft.Azure.NetworkWatcher") .WithType("NetworkWatcherAgentLinux") .WithVersion("1.4") .Attach()); ICreatedResources <IVirtualMachine> createdVMs = azure.VirtualMachines.Create(vmDefinitions); IVirtualMachine vm1 = createdVMs.FirstOrDefault(vm => vm.Key == vmDefinitions[0].Key); IVirtualMachine vm2 = createdVMs.FirstOrDefault(vm => vm.Key == vmDefinitions[1].Key); IConnectivityCheck connectivity = nw.CheckConnectivity() .ToDestinationResourceId(vm2.Id) .ToDestinationPort(22) .FromSourceVirtualMachine(vm1.Id) .Execute(); Utilities.Log("Connectivity status: " + connectivity.ConnectionStatus); } finally { try { Utilities.Log("Deleting Resource Group: " + rgName); azure.ResourceGroups.BeginDeleteByName(rgName); } catch (NullReferenceException) { Utilities.Log("Did not create any resources in Azure. No clean up is necessary"); } catch (Exception ex) { Utilities.Log(ex); } } }
public void CanWatchNetwork() { using (var context = FluentMockContext.Start(GetType().FullName)) { string newName = SdkContext.RandomResourceName("nw", 6); var groupName = SdkContext.RandomResourceName("rg", 6); var resourcesGroupName = SdkContext.RandomResourceName("rg", 8); // Create network watcher var manager = TestHelper.CreateNetworkManager(); var computeManager = TestHelper.CreateComputeManager(); // make sure Network Watcher is disabled in current subscription and region as only one can exist EnsureNetworkWatcherNotExists(manager.NetworkWatchers); var nw = manager.NetworkWatchers.Define(newName) .WithRegion(REGION) .WithNewResourceGroup(groupName) .Create(); // pre-create VMs to show topology on ICreatedResources <IVirtualMachine> virtualMachines = EnsureNetwork(manager, computeManager, resourcesGroupName); var vm0 = virtualMachines.ElementAt(0); ITopology topology = nw.GetTopology(vm0.ResourceGroupName); Assert.Equal(11, topology.Resources.Count); Assert.True(topology.Resources.ContainsKey(vm0.PrimaryNetworkInterfaceId)); Assert.Equal(4, topology.Resources[vm0.PrimaryNetworkInterfaceId].Associations.Count); ISecurityGroupView sgViewResult = nw.GetSecurityGroupView(virtualMachines.ElementAt(0).Id); Assert.Equal(1, sgViewResult.NetworkInterfaces.Count); Assert.Equal(virtualMachines.ElementAt(0).PrimaryNetworkInterfaceId, sgViewResult.NetworkInterfaces.Keys.First()); IFlowLogSettings flowLogSettings = nw.GetFlowLogSettings(vm0.GetPrimaryNetworkInterface().NetworkSecurityGroupId); IStorageAccount storageAccount = EnsureStorageAccount(resourcesGroupName); flowLogSettings.Update() .WithLogging() .WithStorageAccount(storageAccount.Id) .WithRetentionPolicyDays(5) .WithRetentionPolicyEnabled() .Apply(); Assert.True(flowLogSettings.Enabled); Assert.Equal(5, flowLogSettings.RetentionDays); Assert.Equal(storageAccount.Id, flowLogSettings.StorageId); INextHop nextHop = nw.NextHop().WithTargetResourceId(vm0.Id) .WithSourceIPAddress("10.0.0.4") .WithDestinationIPAddress("8.8.8.8") .Execute(); Assert.Equal("System Route", nextHop.RouteTableId); Assert.Equal(NextHopType.Internet, nextHop.NextHopType); Assert.Null(nextHop.NextHopIpAddress); IVerificationIPFlow verificationIPFlow = nw.VerifyIPFlow() .WithTargetResourceId(vm0.Id) .WithDirection(Direction.Outbound) .WithProtocol(Protocol.TCP) .WithLocalIPAddress("10.0.0.4") .WithRemoteIPAddress("8.8.8.8") .WithLocalPort("443") .WithRemotePort("443") .Execute(); Assert.Equal(Access.Allow, verificationIPFlow.Access); Assert.Equal("defaultSecurityRules/AllowInternetOutBound", verificationIPFlow.RuleName); // test packet capture IEnumerable <IPacketCapture> packetCaptures = nw.PacketCaptures.List(); Assert.Empty(packetCaptures); IPacketCapture packetCapture = nw.PacketCaptures .Define("NewPacketCapture") .WithTarget(vm0.Id) .WithStorageAccountId(storageAccount.Id) .WithTimeLimitInSeconds(1500) .DefinePacketCaptureFilter() .WithProtocol(PcProtocol.TCP) .WithLocalIPAddresses(new List <string>() { "127.0.0.1", "127.0.0.5" }) .Attach() .Create(); packetCaptures = nw.PacketCaptures.List(); Assert.Single(packetCaptures); Assert.Equal("NewPacketCapture", packetCapture.Name); Assert.Equal(1500, packetCapture.TimeLimitInSeconds); Assert.Equal(PcProtocol.TCP.Value, packetCapture.Filters[0].Protocol); Assert.Equal("127.0.0.1;127.0.0.5", packetCapture.Filters[0].LocalIPAddress); // Assert.assertEquals("Running", packetCapture.getStatus().packetCaptureStatus().toString()); packetCapture.Stop(); Assert.Equal("Stopped", packetCapture.GetStatus().PacketCaptureStatus.Value); nw.PacketCaptures.DeleteByName(packetCapture.Name); IConnectivityCheck connectivityCheck = nw.CheckConnectivity() .ToDestinationResourceId(vm0.Id) .ToDestinationPort(80) .FromSourceVirtualMachine(virtualMachines.ElementAt(0).Id) .Execute(); Assert.Equal("Reachable", connectivityCheck.ConnectionStatus.ToString()); computeManager.VirtualMachines.DeleteById(virtualMachines.ElementAt(1).Id); topology.Refresh(); Assert.Equal(10, topology.Resources.Count); manager.ResourceManager.ResourceGroups.DeleteByName(nw.ResourceGroupName); manager.ResourceManager.ResourceGroups.DeleteByName(resourcesGroupName); } }