Exemplo n.º 1
0
        public static void RunSample(IAzure azure)
        {
            string rgName             = SdkContext.RandomResourceName("rgSTMS", 20);
            string networkName        = SdkContext.RandomResourceName("nw", 20);
            string subnetName         = "subnetA";
            string storageAccountName = SdkContext.RandomResourceName("sa", 15);
            string publicIpName       = SdkContext.RandomResourceName("pip", 20);
            string vmName             = SdkContext.RandomResourceName("vm", 10);

            try
            {
                // ============================================================
                // Create a virtual network and a subnet with storage service subnet access enabled

                Utilities.Log("Creating a Virtual network and subnet with storage service subnet access enabled:");

                INetwork network = azure.Networks.Define(networkName)
                                   .WithRegion(Region.USEast)
                                   .WithNewResourceGroup(rgName)
                                   .WithAddressSpace("10.0.0.0/28")
                                   .DefineSubnet(subnetName)
                                   .WithAddressPrefix("10.0.0.8/29")
                                   .WithAccessFromService(ServiceEndpointType.MicrosoftStorage)
                                   .Attach()
                                   .Create();

                Utilities.Log("Created a Virtual network with subnet:");
                Utilities.PrintVirtualNetwork(network);

                // ============================================================
                // Create a storage account with access to it allowed only from a specific subnet

                var subnetId = $"{network.Id}/subnets/{subnetName}";

                Utilities.Log($"Creating a storage account with access allowed only from the subnet{subnetId}");

                IStorageAccount storageAccount = azure.StorageAccounts.Define(storageAccountName)
                                                 .WithRegion(Region.USEast)
                                                 .WithExistingResourceGroup(rgName)
                                                 .WithAccessFromSelectedNetworks()
                                                 .WithAccessFromNetworkSubnet(subnetId)
                                                 .Create();

                Utilities.Log("Created storage account:");
                Utilities.PrintStorageAccount(storageAccount);


                // ============================================================
                // Create a public IP address

                Utilities.Log("Creating a Public IP address");

                IPublicIPAddress publicIPAddress = azure.PublicIPAddresses
                                                   .Define(publicIpName)
                                                   .WithRegion(Region.USEast)
                                                   .WithExistingResourceGroup(rgName)
                                                   .WithLeafDomainLabel(publicIpName)
                                                   .Create();

                Utilities.Log("Created Public IP address:");
                Utilities.PrintIPAddress(publicIPAddress);

                // ============================================================
                // Create a virtual machine and associate the public IP address

                Utilities.Log("Creating a VM with the Public IP address");

                IVirtualMachine linuxVM = azure.VirtualMachines
                                          .Define(vmName)
                                          .WithRegion(Region.USEast)
                                          .WithExistingResourceGroup(rgName)
                                          .WithNewPrimaryNetwork("10.1.0.0/28")
                                          .WithPrimaryPrivateIPAddressDynamic()
                                          .WithExistingPrimaryPublicIPAddress(publicIPAddress)
                                          .WithPopularLinuxImage(KnownLinuxVirtualMachineImage.UbuntuServer16_04_Lts)
                                          .WithRootUsername(Utilities.CreateUsername())
                                          .WithRootPassword(Utilities.CreatePassword())
                                          .WithSize(VirtualMachineSizeTypes.Parse("Standard_D2a_v4"))
                                          .Create();

                Utilities.Log($"Created the VM: {linuxVM.Id}");
                Utilities.PrintVirtualMachine(linuxVM);

                publicIPAddress.Refresh();  // Refresh public IP resource to populate the assigned IPv4 address

                // ============================================================
                // Update the storage account so that it can also be accessed from the PublicIP address

                Utilities.Log($"Updating storage account with access also allowed from publicIP{publicIPAddress.IPAddress}");

                storageAccount.Update()
                .WithAccessFromIpAddress(publicIPAddress.IPAddress)
                .Apply();

                Utilities.Log("Updated storage account:");
                Utilities.PrintStorageAccount(storageAccount);

                // ============================================================
                //  Update the storage account to restrict incoming traffic to HTTPS

                Utilities.Log("Restricting access to storage account only via HTTPS");

                storageAccount.Update()
                .WithOnlyHttpsTraffic()
                .Apply();

                Utilities.Log("Updated the storage account:");
                Utilities.PrintStorageAccount(storageAccount);
            }
            finally
            {
                if (azure.ResourceGroups.GetByName(rgName) != null)
                {
                    Utilities.Log("Deleting Resource Group: " + rgName);
                    azure.ResourceGroups.DeleteByName(rgName);
                    Utilities.Log("Deleted Resource Group: " + rgName);
                }
                else
                {
                    Utilities.Log("Did not create any resources in Azure. No clean up is necessary");
                }
            }
        }
        public override ILoadBalancer CreateResource(ILoadBalancers resources)
        {
            pips             = resources.Manager.PublicIPAddresses;
            networks         = resources.Manager.Networks;
            availabilitySets = computeManager.AvailabilitySets;
            var existingVMs = loadBalancerHelper.EnsureVMs(networks, computeManager, 2);

            Assert.Equal(2, existingVMs.Count());
            var existingPips     = loadBalancerHelper.EnsurePIPs(pips);
            var nic1             = existingVMs.ElementAt(0).GetPrimaryNetworkInterface();
            var nic2             = existingVMs.ElementAt(1).GetPrimaryNetworkInterface();
            IPublicIPAddress pip = resources.Manager.PublicIPAddresses.GetByResourceGroup(
                loadBalancerHelper.GroupName,
                loadBalancerHelper.PipNames[0]);

            // Create a load balancer
            var lb = resources.Define(loadBalancerHelper.LoadBalancerName)
                     .WithRegion(loadBalancerHelper.Region)
                     .WithExistingResourceGroup(loadBalancerHelper.GroupName)

                                                          // Load balancing rules
                     .DefineLoadBalancingRule("rule1")
                     .WithProtocol(TransportProtocol.Tcp) // Required
                     .FromExistingPublicIPAddress(pip)
                     .FromFrontendPort(81)
                     .ToBackend("backend1")
                     .ToBackendPort(82)                           // Optionals
                     .WithProbe("tcpProbe1")
                     .WithIdleTimeoutInMinutes(10)
                     .WithLoadDistribution(LoadDistribution.SourceIP)
                     .Attach()

                     // Inbound NAT rules
                     .DefineInboundNatRule("natrule1")
                     .WithProtocol(TransportProtocol.Tcp)
                     .FromExistingPublicIPAddress(pip)        // Implicitly uses the same frontend because the PIP is the same
                     .FromFrontendPort(88)
                     .Attach()

                     // Probes
                     .DefineTcpProbe("tcpProbe1")
                     .WithPort(25)                      // Required
                     .WithIntervalInSeconds(15)         // Optionals
                     .WithNumberOfProbes(5)
                     .Attach()
                     .DefineHttpProbe("httpProbe1")
                     .WithRequestPath("/")              // Required
                     .WithIntervalInSeconds(13)         // Optionals
                     .WithNumberOfProbes(4)
                     .Attach()

                     .Create();

            string backendName  = lb.Backends.Values.First().Name;
            string frontendName = lb.Frontends.Values.First().Name;

            // Connect NICs explicitly
            nic1.Update()
            .WithExistingLoadBalancerBackend(lb, backendName)
            .WithExistingLoadBalancerInboundNatRule(lb, "natrule1")
            .Apply();
            NetworkInterfaceHelper.PrintNic(nic1);
            Assert.Equal(nic1.PrimaryIPConfiguration.ListAssociatedLoadBalancerBackends().ElementAt(0)
                         .Name, backendName, ignoreCase: true);
            Assert.Equal("natrule1", nic1.PrimaryIPConfiguration.ListAssociatedLoadBalancerInboundNatRules().ElementAt(0)
                         .Name, ignoreCase: true);

            nic2.Update()
            .WithExistingLoadBalancerBackend(lb, backendName)
            .Apply();
            NetworkInterfaceHelper.PrintNic(nic2);
            Assert.Equal(nic2.PrimaryIPConfiguration.ListAssociatedLoadBalancerBackends().ElementAt(0)
                         .Name, backendName, ignoreCase: true);

            // Verify frontends
            Assert.Single(lb.Frontends.Values);
            Assert.Single(lb.PublicFrontends.Values);
            Assert.Empty(lb.PrivateFrontends.Values);
            Assert.True(lb.Frontends.ContainsKey(frontendName));
            var frontend = lb.Frontends[frontendName];

            Assert.True(frontend.IsPublic);
            var publicFrontend = (ILoadBalancerPublicFrontend)frontend;

            Assert.Equal(pip.Id, publicFrontend.PublicIPAddressId, ignoreCase: true);

            pip.Refresh();
            Assert.Equal(pip.GetAssignedLoadBalancerFrontend().Name, frontendName, ignoreCase: true);

            // Verify backends
            Assert.True(lb.Backends.ContainsKey(backendName));
            Assert.Single(lb.Backends.Values);

            // Verify probes
            Assert.True(lb.HttpProbes.ContainsKey("httpProbe1"));
            Assert.Single(lb.HttpProbes.Values);
            Assert.True(lb.TcpProbes.ContainsKey("tcpProbe1"));
            Assert.Single(lb.TcpProbes.Values);

            // Verify rules
            Assert.Single(lb.LoadBalancingRules.Values);
            Assert.True(lb.LoadBalancingRules.ContainsKey("rule1"));
            var rule = lb.LoadBalancingRules["rule1"];

            Assert.Equal(rule.Backend.Name, backendName, ignoreCase: true);
            Assert.Equal(rule.Frontend.Name, frontendName, ignoreCase: true);
            Assert.Equal("tcpProbe1", rule.Probe.Name, ignoreCase: true);

            // Verify inbound NAT rules
            Assert.Single(lb.InboundNatRules.Values);
            Assert.True(lb.InboundNatRules.ContainsKey("natrule1"));
            var inboundNatRule = lb.InboundNatRules["natrule1"];

            Assert.Equal(inboundNatRule.Frontend.Name, frontendName, ignoreCase: true);
            Assert.Equal(88, inboundNatRule.FrontendPort);
            Assert.Equal(88, inboundNatRule.BackendPort);

            return(lb);
        }