Search in sources :

Example 6 with PublicIPAddress

use of com.microsoft.azure.management.network.PublicIPAddress in project azure-sdk-for-java by Azure.

the class ManageVirtualMachineScaleSetWithUnmanagedDisks method runSample.

/**
     * Main function which runs the actual sample.
     * @param azure instance of the azure client
     * @return true if sample runs successfully
     */
public static boolean runSample(Azure azure) {
    final Region region = Region.US_WEST_CENTRAL;
    final String rgName = SdkContext.randomResourceName("rgCOVS", 15);
    final String vnetName = SdkContext.randomResourceName("vnet", 24);
    final String loadBalancerName1 = SdkContext.randomResourceName("intlb" + "-", 18);
    final String publicIpName = "pip-" + loadBalancerName1;
    final String frontendName = loadBalancerName1 + "-FE1";
    final String backendPoolName1 = loadBalancerName1 + "-BAP1";
    final String backendPoolName2 = loadBalancerName1 + "-BAP2";
    final String httpProbe = "httpProbe";
    final String httpsProbe = "httpsProbe";
    final String httpLoadBalancingRule = "httpRule";
    final String httpsLoadBalancingRule = "httpsRule";
    final String natPool50XXto22 = "natPool50XXto22";
    final String natPool60XXto23 = "natPool60XXto23";
    final String vmssName = SdkContext.randomResourceName("vmss", 24);
    final String storageAccountName1 = SdkContext.randomResourceName("stg1", 24);
    final String storageAccountName2 = SdkContext.randomResourceName("stg2", 24);
    final String storageAccountName3 = SdkContext.randomResourceName("stg3", 24);
    final String userName = "tirekicker";
    final String sshKey = "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCfSPC2K7LZcFKEO+/t3dzmQYtrJFZNxOsbVgOVKietqHyvmYGHEC0J2wPdAqQ/63g/hhAEFRoyehM+rbeDri4txB3YFfnOK58jqdkyXzupWqXzOrlKY4Wz9SKjjN765+dqUITjKRIaAip1Ri137szRg71WnrmdP3SphTRlCx1Bk2nXqWPsclbRDCiZeF8QOTi4JqbmJyK5+0UqhqYRduun8ylAwKKQJ1NJt85sYIHn9f1Rfr6Tq2zS0wZ7DHbZL+zB5rSlAr8QyUdg/GQD+cmSs6LvPJKL78d6hMGk84ARtFo4A79ovwX/Fj01znDQkU6nJildfkaolH2rWFG/qttD azjava@javalib.com";
    final String apacheInstallScript = "https://raw.githubusercontent.com/Azure/azure-sdk-for-java/master/azure-samples/src/main/resources/install_apache.sh";
    final String installCommand = "bash install_apache.sh";
    List<String> fileUris = new ArrayList<>();
    fileUris.add(apacheInstallScript);
    try {
        //=============================================================
        // Create a virtual network with a frontend subnet
        System.out.println("Creating virtual network with a frontend subnet ...");
        Network network = azure.networks().define(vnetName).withRegion(region).withNewResourceGroup(rgName).withAddressSpace("172.16.0.0/16").defineSubnet("Front-end").withAddressPrefix("172.16.1.0/24").attach().create();
        System.out.println("Created a virtual network");
        // Print the virtual network details
        Utils.print(network);
        //=============================================================
        // Create a public IP address
        System.out.println("Creating a public IP address...");
        PublicIPAddress publicIPAddress = azure.publicIPAddresses().define(publicIpName).withRegion(region).withExistingResourceGroup(rgName).withLeafDomainLabel(publicIpName).create();
        System.out.println("Created a public IP address");
        // Print the virtual network details
        Utils.print(publicIPAddress);
        //=============================================================
        // Create an Internet facing load balancer with
        // One frontend IP address
        // Two backend address pools which contain network interfaces for the virtual
        //  machines to receive HTTP and HTTPS network traffic from the load balancer
        // Two load balancing rules for HTTP and HTTPS to map public ports on the load
        //  balancer to ports in the backend address pool
        // Two probes which contain HTTP and HTTPS health probes used to check availability
        //  of virtual machines in the backend address pool
        // Three inbound NAT rules which contain rules that map a public port on the load
        //  balancer to a port for a specific virtual machine in the backend address pool
        //  - this provides direct VM connectivity for SSH to port 22 and TELNET to port 23
        System.out.println("Creating a Internet facing load balancer with ...");
        System.out.println("- A frontend IP address");
        System.out.println("- Two backend address pools which contain network interfaces for the virtual\n" + "  machines to receive HTTP and HTTPS network traffic from the load balancer");
        System.out.println("- Two load balancing rules for HTTP and HTTPS to map public ports on the load\n" + "  balancer to ports in the backend address pool");
        System.out.println("- Two probes which contain HTTP and HTTPS health probes used to check availability\n" + "  of virtual machines in the backend address pool");
        System.out.println("- Two inbound NAT rules which contain rules that map a public port on the load\n" + "  balancer to a port for a specific virtual machine in the backend address pool\n" + "  - this provides direct VM connectivity for SSH to port 22 and TELNET to port 23");
        LoadBalancer loadBalancer1 = azure.loadBalancers().define(loadBalancerName1).withRegion(region).withExistingResourceGroup(rgName).definePublicFrontend(frontendName).withExistingPublicIPAddress(publicIPAddress).attach().defineBackend(backendPoolName1).attach().defineBackend(backendPoolName2).attach().defineHttpProbe(httpProbe).withRequestPath("/").withPort(80).attach().defineHttpProbe(httpsProbe).withRequestPath("/").withPort(443).attach().defineLoadBalancingRule(httpLoadBalancingRule).withProtocol(TransportProtocol.TCP).withFrontend(frontendName).withFrontendPort(80).withProbe(httpProbe).withBackend(backendPoolName1).attach().defineLoadBalancingRule(httpsLoadBalancingRule).withProtocol(TransportProtocol.TCP).withFrontend(frontendName).withFrontendPort(443).withProbe(httpsProbe).withBackend(backendPoolName2).attach().defineInboundNatPool(natPool50XXto22).withProtocol(TransportProtocol.TCP).withFrontend(frontendName).withFrontendPortRange(5000, 5099).withBackendPort(22).attach().defineInboundNatPool(natPool60XXto23).withProtocol(TransportProtocol.TCP).withFrontend(frontendName).withFrontendPortRange(6000, 6099).withBackendPort(23).attach().create();
        // Print load balancer details
        System.out.println("Created a load balancer");
        Utils.print(loadBalancer1);
        //=============================================================
        // Create a virtual machine scale set with three virtual machines
        // And, install Apache Web servers on them
        System.out.println("Creating virtual machine scale set with three virtual machines" + " in the frontend subnet ...");
        Date t1 = new Date();
        VirtualMachineScaleSet virtualMachineScaleSet = azure.virtualMachineScaleSets().define(vmssName).withRegion(region).withExistingResourceGroup(rgName).withSku(VirtualMachineScaleSetSkuTypes.STANDARD_D3_V2).withExistingPrimaryNetworkSubnet(network, "Front-end").withExistingPrimaryInternetFacingLoadBalancer(loadBalancer1).withPrimaryInternetFacingLoadBalancerBackends(backendPoolName1, backendPoolName2).withPrimaryInternetFacingLoadBalancerInboundNatPools(natPool50XXto22, natPool60XXto23).withoutPrimaryInternalLoadBalancer().withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS).withRootUsername(userName).withSsh(sshKey).withUnmanagedDisks().withNewStorageAccount(storageAccountName1).withNewStorageAccount(storageAccountName2).withNewStorageAccount(storageAccountName3).withCapacity(3).defineNewExtension("CustomScriptForLinux").withPublisher("Microsoft.OSTCExtensions").withType("CustomScriptForLinux").withVersion("1.4").withMinorVersionAutoUpgrade().withPublicSetting("fileUris", fileUris).withPublicSetting("commandToExecute", installCommand).attach().create();
        Date t2 = new Date();
        System.out.println("Created a virtual machine scale set with " + "3 Linux VMs & Apache Web servers on them: (took " + ((t2.getTime() - t1.getTime()) / 1000) + " seconds) ");
        System.out.println();
        // Print virtual machine scale set details
        // Utils.print(virtualMachineScaleSet);
        //=============================================================
        // List virtual machine scale set network interfaces
        System.out.println("Listing scale set network interfaces ...");
        PagedList<VirtualMachineScaleSetNetworkInterface> vmssNics = virtualMachineScaleSet.listNetworkInterfaces();
        for (VirtualMachineScaleSetNetworkInterface vmssNic : vmssNics) {
            System.out.println(vmssNic.id());
        }
        //=============================================================
        // List virtual machine scale set instance network interfaces and SSH connection string
        System.out.println("Listing scale set virtual machine instance network interfaces and SSH connection string...");
        for (VirtualMachineScaleSetVM instance : virtualMachineScaleSet.virtualMachines().list()) {
            System.out.println("Scale set virtual machine instance #" + instance.instanceId());
            System.out.println(instance.id());
            PagedList<VirtualMachineScaleSetNetworkInterface> networkInterfaces = instance.listNetworkInterfaces();
            // Pick the first NIC
            VirtualMachineScaleSetNetworkInterface networkInterface = networkInterfaces.get(0);
            for (VirtualMachineScaleSetNicIPConfiguration ipConfig : networkInterface.ipConfigurations().values()) {
                if (ipConfig.isPrimary()) {
                    List<LoadBalancerInboundNatRule> natRules = ipConfig.listAssociatedLoadBalancerInboundNatRules();
                    for (LoadBalancerInboundNatRule natRule : natRules) {
                        if (natRule.backendPort() == 22) {
                            System.out.println("SSH connection string: " + userName + "@" + publicIPAddress.fqdn() + ":" + natRule.frontendPort());
                            break;
                        }
                    }
                    break;
                }
            }
        }
        //=============================================================
        // Stop the virtual machine scale set
        System.out.println("Stopping virtual machine scale set ...");
        virtualMachineScaleSet.powerOff();
        System.out.println("Stopped virtual machine scale set");
        //=============================================================
        // Start the virtual machine scale set
        System.out.println("Starting virtual machine scale set ...");
        virtualMachineScaleSet.start();
        System.out.println("Started virtual machine scale set");
        //=============================================================
        // Update the virtual machine scale set
        // - double the no. of virtual machines
        System.out.println("Updating virtual machine scale set " + "- double the no. of virtual machines ...");
        virtualMachineScaleSet.update().withCapacity(6).apply();
        System.out.println("Doubled the no. of virtual machines in " + "the virtual machine scale set");
        //=============================================================
        // re-start virtual machine scale set
        System.out.println("re-starting virtual machine scale set ...");
        virtualMachineScaleSet.restart();
        System.out.println("re-started virtual machine scale set");
        return true;
    } catch (Exception f) {
        System.out.println(f.getMessage());
        f.printStackTrace();
    } finally {
        try {
            System.out.println("Deleting Resource Group: " + rgName);
            azure.resourceGroups().deleteByName(rgName);
            System.out.println("Deleted Resource Group: " + rgName);
        } catch (NullPointerException npe) {
            System.out.println("Did not create any resources in Azure. No clean up is necessary");
        } catch (Exception g) {
            g.printStackTrace();
        }
    }
    return false;
}
Also used : ArrayList(java.util.ArrayList) LoadBalancer(com.microsoft.azure.management.network.LoadBalancer) PublicIPAddress(com.microsoft.azure.management.network.PublicIPAddress) LoadBalancerInboundNatRule(com.microsoft.azure.management.network.LoadBalancerInboundNatRule) Date(java.util.Date) VirtualMachineScaleSetNicIPConfiguration(com.microsoft.azure.management.network.VirtualMachineScaleSetNicIPConfiguration) VirtualMachineScaleSetVM(com.microsoft.azure.management.compute.VirtualMachineScaleSetVM) Network(com.microsoft.azure.management.network.Network) Region(com.microsoft.azure.management.resources.fluentcore.arm.Region) VirtualMachineScaleSetNetworkInterface(com.microsoft.azure.management.network.VirtualMachineScaleSetNetworkInterface) VirtualMachineScaleSet(com.microsoft.azure.management.compute.VirtualMachineScaleSet)

Example 7 with PublicIPAddress

use of com.microsoft.azure.management.network.PublicIPAddress in project azure-sdk-for-java by Azure.

the class TestPublicIPAddress method createResource.

@Override
public PublicIPAddress createResource(PublicIPAddresses pips) throws Exception {
    final String newPipName = "pip" + this.testId;
    PublicIPAddress pip = pips.define(newPipName).withRegion(Region.US_WEST).withNewResourceGroup().withDynamicIP().withLeafDomainLabel(newPipName).withIdleTimeoutInMinutes(10).create();
    return pip;
}
Also used : PublicIPAddress(com.microsoft.azure.management.network.PublicIPAddress)

Example 8 with PublicIPAddress

use of com.microsoft.azure.management.network.PublicIPAddress in project azure-sdk-for-java by Azure.

the class TestTrafficManager method createResource.

@Override
public TrafficManagerProfile createResource(TrafficManagerProfiles profiles) throws Exception {
    final Region region = Region.US_EAST;
    final String groupName = "rg" + this.testId;
    final String pipName = "pip" + this.testId;
    final String pipDnsLabel = SdkContext.randomResourceName("contoso", 15);
    final String tmProfileName = "tm" + this.testId;
    final String nestedTmProfileName = "nested" + tmProfileName;
    final String tmProfileDnsLabel = SdkContext.randomResourceName("tmdns", 15);
    final String nestedTmProfileDnsLabel = "nested" + tmProfileDnsLabel;
    ResourceGroup.DefinitionStages.WithCreate rgCreatable = profiles.manager().resourceManager().resourceGroups().define(groupName).withRegion(region);
    // Creates a TM profile that will be used as a nested profile endpoint in parent TM profile
    //
    TrafficManagerProfile nestedProfile = profiles.define(nestedTmProfileName).withNewResourceGroup(rgCreatable).withLeafDomainLabel(nestedTmProfileDnsLabel).withPriorityBasedRouting().defineExternalTargetEndpoint("external-ep-1").toFqdn("www.gitbook.com").fromRegion(Region.INDIA_CENTRAL).attach().withHttpsMonitoring().withTimeToLive(500).create();
    Assert.assertTrue(nestedProfile.isEnabled());
    Assert.assertNotNull(nestedProfile.monitorStatus());
    Assert.assertEquals(nestedProfile.monitoringPort(), 443);
    Assert.assertEquals(nestedProfile.monitoringPath(), "/");
    Assert.assertEquals(nestedProfile.azureEndpoints().size(), 0);
    Assert.assertEquals(nestedProfile.nestedProfileEndpoints().size(), 0);
    Assert.assertEquals(nestedProfile.externalEndpoints().size(), 1);
    Assert.assertEquals(nestedProfile.fqdn(), nestedTmProfileDnsLabel + ".trafficmanager.net");
    Assert.assertEquals(nestedProfile.timeToLive(), 500);
    // Creates a public ip to be used as an Azure endpoint
    //
    PublicIPAddress publicIPAddress = this.publicIPAddresses.define(pipName).withRegion(region).withNewResourceGroup(rgCreatable).withLeafDomainLabel(pipDnsLabel).create();
    Assert.assertNotNull(publicIPAddress.fqdn());
    // Creates a TM profile
    //
    TrafficManagerProfile profile = profiles.define(tmProfileName).withNewResourceGroup(rgCreatable).withLeafDomainLabel(tmProfileDnsLabel).withWeightBasedRouting().defineExternalTargetEndpoint(externalEndpointName21).toFqdn(externalFqdn21).fromRegion(Region.US_EAST).withRoutingPriority(1).withRoutingWeight(1).attach().defineExternalTargetEndpoint(externalEndpointName22).toFqdn(externalFqdn22).fromRegion(Region.US_EAST2).withRoutingPriority(2).withRoutingWeight(1).withTrafficDisabled().attach().defineAzureTargetEndpoint(azureEndpointName).toResourceId(publicIPAddress.id()).withRoutingPriority(3).attach().defineNestedTargetEndpoint(nestedProfileEndpointName).toProfile(nestedProfile).fromRegion(Region.INDIA_CENTRAL).withMinimumEndpointsToEnableTraffic(1).withRoutingPriority(4).attach().withHttpMonitoring().create();
    Assert.assertTrue(profile.isEnabled());
    Assert.assertNotNull(profile.monitorStatus());
    Assert.assertEquals(profile.monitoringPort(), 80);
    Assert.assertEquals(profile.monitoringPath(), "/");
    Assert.assertEquals(profile.azureEndpoints().size(), 1);
    Assert.assertEquals(profile.nestedProfileEndpoints().size(), 1);
    Assert.assertEquals(profile.externalEndpoints().size(), 2);
    Assert.assertEquals(profile.fqdn(), tmProfileDnsLabel + ".trafficmanager.net");
    // Default
    Assert.assertEquals(profile.timeToLive(), 300);
    profile = profile.refresh();
    Assert.assertEquals(profile.azureEndpoints().size(), 1);
    Assert.assertEquals(profile.nestedProfileEndpoints().size(), 1);
    Assert.assertEquals(profile.externalEndpoints().size(), 2);
    int c = 0;
    for (TrafficManagerExternalEndpoint endpoint : profile.externalEndpoints().values()) {
        Assert.assertEquals(endpoint.endpointType(), EndpointType.EXTERNAL);
        if (endpoint.name().equalsIgnoreCase(externalEndpointName21)) {
            Assert.assertEquals(endpoint.routingPriority(), 1);
            Assert.assertEquals(endpoint.fqdn(), externalFqdn21);
            Assert.assertNotNull(endpoint.monitorStatus());
            Assert.assertEquals(endpoint.sourceTrafficLocation(), Region.US_EAST);
            c++;
        } else if (endpoint.name().equalsIgnoreCase(externalEndpointName22)) {
            Assert.assertEquals(endpoint.routingPriority(), 2);
            Assert.assertEquals(endpoint.fqdn(), externalFqdn22);
            Assert.assertNotNull(endpoint.monitorStatus());
            Assert.assertEquals(endpoint.sourceTrafficLocation(), Region.US_EAST2);
            c++;
        }
    }
    Assert.assertEquals(c, 2);
    c = 0;
    for (TrafficManagerAzureEndpoint endpoint : profile.azureEndpoints().values()) {
        Assert.assertEquals(endpoint.endpointType(), EndpointType.AZURE);
        if (endpoint.name().equalsIgnoreCase(azureEndpointName)) {
            Assert.assertEquals(endpoint.routingPriority(), 3);
            Assert.assertNotNull(endpoint.monitorStatus());
            Assert.assertEquals(endpoint.targetAzureResourceId(), publicIPAddress.id());
            Assert.assertEquals(endpoint.targetResourceType(), TargetAzureResourceType.PUBLICIP);
            c++;
        }
    }
    Assert.assertEquals(c, 1);
    c = 0;
    for (TrafficManagerNestedProfileEndpoint endpoint : profile.nestedProfileEndpoints().values()) {
        Assert.assertEquals(endpoint.endpointType(), EndpointType.NESTED_PROFILE);
        if (endpoint.name().equalsIgnoreCase(nestedProfileEndpointName)) {
            Assert.assertEquals(endpoint.routingPriority(), 4);
            Assert.assertNotNull(endpoint.monitorStatus());
            Assert.assertEquals(endpoint.minimumChildEndpointCount(), 1);
            Assert.assertEquals(endpoint.nestedProfileId(), nestedProfile.id());
            Assert.assertEquals(endpoint.sourceTrafficLocation(), Region.INDIA_CENTRAL);
            c++;
        }
    }
    Assert.assertEquals(c, 1);
    return profile;
}
Also used : TrafficManagerExternalEndpoint(com.microsoft.azure.management.trafficmanager.TrafficManagerExternalEndpoint) TrafficManagerNestedProfileEndpoint(com.microsoft.azure.management.trafficmanager.TrafficManagerNestedProfileEndpoint) TrafficManagerAzureEndpoint(com.microsoft.azure.management.trafficmanager.TrafficManagerAzureEndpoint) TrafficManagerProfile(com.microsoft.azure.management.trafficmanager.TrafficManagerProfile) Region(com.microsoft.azure.management.resources.fluentcore.arm.Region) PublicIPAddress(com.microsoft.azure.management.network.PublicIPAddress) TrafficManagerExternalEndpoint(com.microsoft.azure.management.trafficmanager.TrafficManagerExternalEndpoint) TrafficManagerAzureEndpoint(com.microsoft.azure.management.trafficmanager.TrafficManagerAzureEndpoint) TrafficManagerNestedProfileEndpoint(com.microsoft.azure.management.trafficmanager.TrafficManagerNestedProfileEndpoint)

Example 9 with PublicIPAddress

use of com.microsoft.azure.management.network.PublicIPAddress in project azure-sdk-for-java by Azure.

the class ManageIPAddress method runSample.

/**
     * Main function which runs the actual sample.
     * @param azure instance of the azure client
     * @return true if sample runs successfully
     */
public static boolean runSample(Azure azure) {
    final String publicIPAddressName1 = SdkContext.randomResourceName("pip1", 20);
    final String publicIPAddressName2 = SdkContext.randomResourceName("pip2", 20);
    final String publicIPAddressLeafDNS1 = SdkContext.randomResourceName("pip1", 20);
    final String publicIPAddressLeafDNS2 = SdkContext.randomResourceName("pip2", 20);
    final String vmName = SdkContext.randomResourceName("vm", 8);
    final String rgName = SdkContext.randomResourceName("rgNEMP", 24);
    final String userName = "tirekicker";
    final String password = "12NewPA$$w0rd!";
    try {
        //============================================================
        // Assign a public IP address for a VM during its creation
        // Define a public IP address to be used during VM creation time
        System.out.println("Creating a public IP address...");
        PublicIPAddress publicIPAddress = azure.publicIPAddresses().define(publicIPAddressName1).withRegion(Region.US_EAST).withNewResourceGroup(rgName).withLeafDomainLabel(publicIPAddressLeafDNS1).create();
        System.out.println("Created a public IP address");
        // Print public IP address details
        Utils.print(publicIPAddress);
        // Use the pre-created public IP for the new VM
        System.out.println("Creating a Windows VM");
        Date t1 = new Date();
        VirtualMachine vm = azure.virtualMachines().define(vmName).withRegion(Region.US_EAST).withExistingResourceGroup(rgName).withNewPrimaryNetwork("10.0.0.0/28").withPrimaryPrivateIPAddressDynamic().withExistingPrimaryPublicIPAddress(publicIPAddress).withPopularWindowsImage(KnownWindowsVirtualMachineImage.WINDOWS_SERVER_2012_R2_DATACENTER).withAdminUsername(userName).withAdminPassword(password).withSize(VirtualMachineSizeTypes.STANDARD_D3_V2).create();
        Date t2 = new Date();
        System.out.println("Created VM: (took " + ((t2.getTime() - t1.getTime()) / 1000) + " seconds) " + vm.id());
        // Print virtual machine details
        Utils.print(vm);
        //============================================================
        // Gets the public IP address associated with the VM's primary NIC
        System.out.println("Public IP address associated with the VM's primary NIC [After create]");
        // Print the public IP address details
        Utils.print(vm.getPrimaryPublicIPAddress());
        //============================================================
        // Assign a new public IP address for the VM
        // Define a new public IP address
        PublicIPAddress publicIPAddress2 = azure.publicIPAddresses().define(publicIPAddressName2).withRegion(Region.US_EAST).withNewResourceGroup(rgName).withLeafDomainLabel(publicIPAddressLeafDNS2).create();
        // Update VM's primary NIC to use the new public IP address
        System.out.println("Updating the VM's primary NIC with new public IP address");
        NetworkInterface primaryNetworkInterface = vm.getPrimaryNetworkInterface();
        primaryNetworkInterface.update().withExistingPrimaryPublicIPAddress(publicIPAddress2).apply();
        //============================================================
        // Gets the updated public IP address associated with the VM
        // Get the associated public IP address for a virtual machine
        System.out.println("Public IP address associated with the VM's primary NIC [After Update]");
        vm.refresh();
        Utils.print(vm.getPrimaryPublicIPAddress());
        //============================================================
        // Remove public IP associated with the VM
        System.out.println("Removing public IP address associated with the VM");
        vm.refresh();
        primaryNetworkInterface = vm.getPrimaryNetworkInterface();
        publicIPAddress = primaryNetworkInterface.primaryIPConfiguration().getPublicIPAddress();
        primaryNetworkInterface.update().withoutPrimaryPublicIPAddress().apply();
        System.out.println("Removed public IP address associated with the VM");
        //============================================================
        // Delete the public ip
        System.out.println("Deleting the public IP address");
        azure.publicIPAddresses().deleteById(publicIPAddress.id());
        System.out.println("Deleted the public IP address");
        return true;
    } catch (Exception e) {
        System.err.println(e.getMessage());
    } finally {
        try {
            System.out.println("Deleting Resource Group: " + rgName);
            azure.resourceGroups().deleteByName(rgName);
            System.out.println("Deleted Resource Group: " + rgName);
        } catch (NullPointerException npe) {
            System.out.println("Did not create any resources in Azure. No clean up is necessary");
        } catch (Exception g) {
            g.printStackTrace();
        }
    }
    return false;
}
Also used : NetworkInterface(com.microsoft.azure.management.network.NetworkInterface) PublicIPAddress(com.microsoft.azure.management.network.PublicIPAddress) Date(java.util.Date) VirtualMachine(com.microsoft.azure.management.compute.VirtualMachine)

Example 10 with PublicIPAddress

use of com.microsoft.azure.management.network.PublicIPAddress in project azure-sdk-for-java by Azure.

the class ManageInternetFacingLoadBalancer method runSample.

/**
     * Main function which runs the actual sample.
     * @param azure instance of the azure client
     * @return true if sample runs successfully
     */
public static boolean runSample(Azure azure) {
    final String rgName = SdkContext.randomResourceName("rgNEML", 15);
    final String vnetName = SdkContext.randomResourceName("vnet", 24);
    final String loadBalancerName1 = SdkContext.randomResourceName("intlb1" + "-", 18);
    final String loadBalancerName2 = SdkContext.randomResourceName("intlb2" + "-", 18);
    final String publicIpName1 = "pip1-" + loadBalancerName1;
    final String publicIpName2 = "pip2-" + loadBalancerName1;
    final String frontendName = loadBalancerName1 + "-FE1";
    final String backendPoolName1 = loadBalancerName1 + "-BAP1";
    final String backendPoolName2 = loadBalancerName1 + "-BAP2";
    final String httpProbe = "httpProbe";
    final String httpsProbe = "httpsProbe";
    final String httpLoadBalancingRule = "httpRule";
    final String httpsLoadBalancingRule = "httpsRule";
    final String natRule5000to22forVM1 = "nat5000to22forVM1";
    final String natRule5001to23forVM1 = "nat5001to23forVM1";
    final String natRule5002to22forVM2 = "nat5002to22forVM2";
    final String natRule5003to23forVM2 = "nat5003to23forVM2";
    final String networkInterfaceName1 = SdkContext.randomResourceName("nic1", 24);
    final String networkInterfaceName2 = SdkContext.randomResourceName("nic2", 24);
    final String availSetName = SdkContext.randomResourceName("av", 24);
    final String userName = "tirekicker";
    final String sshKey = "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCfSPC2K7LZcFKEO+/t3dzmQYtrJFZNxOsbVgOVKietqHyvmYGHEC0J2wPdAqQ/63g/hhAEFRoyehM+rbeDri4txB3YFfnOK58jqdkyXzupWqXzOrlKY4Wz9SKjjN765+dqUITjKRIaAip1Ri137szRg71WnrmdP3SphTRlCx1Bk2nXqWPsclbRDCiZeF8QOTi4JqbmJyK5+0UqhqYRduun8ylAwKKQJ1NJt85sYIHn9f1Rfr6Tq2zS0wZ7DHbZL+zB5rSlAr8QyUdg/GQD+cmSs6LvPJKL78d6hMGk84ARtFo4A79ovwX/Fj01znDQkU6nJildfkaolH2rWFG/qttD azjava@javalib.com";
    try {
        //=============================================================
        // Create a virtual network with a frontend and a backend subnets
        System.out.println("Creating virtual network with a frontend and a backend subnets...");
        Network network = azure.networks().define(vnetName).withRegion(Region.US_EAST).withNewResourceGroup(rgName).withAddressSpace("172.16.0.0/16").defineSubnet("Front-end").withAddressPrefix("172.16.1.0/24").attach().defineSubnet("Back-end").withAddressPrefix("172.16.3.0/24").attach().create();
        System.out.println("Created a virtual network");
        // Print the virtual network details
        Utils.print(network);
        //=============================================================
        // Create a public IP address
        System.out.println("Creating a public IP address...");
        PublicIPAddress publicIPAddress = azure.publicIPAddresses().define(publicIpName1).withRegion(Region.US_EAST).withExistingResourceGroup(rgName).withLeafDomainLabel(publicIpName1).create();
        System.out.println("Created a public IP address");
        // Print the virtual network details
        Utils.print(publicIPAddress);
        //=============================================================
        // Create an Internet facing load balancer
        // Create a frontend IP address
        // Two backend address pools which contain network interfaces for the virtual
        //  machines to receive HTTP and HTTPS network traffic from the load balancer
        // Two load balancing rules for HTTP and HTTPS to map public ports on the load
        //  balancer to ports in the backend address pool
        // Two probes which contain HTTP and HTTPS health probes used to check availability
        //  of virtual machines in the backend address pool
        // Two inbound NAT rules which contain rules that map a public port on the load
        //  balancer to a port for a specific virtual machine in the backend address pool
        //  - this provides direct VM connectivity for SSH to port 22 and TELNET to port 23
        System.out.println("Creating a Internet facing load balancer with ...");
        System.out.println("- A frontend IP address");
        System.out.println("- Two backend address pools which contain network interfaces for the virtual\n" + "  machines to receive HTTP and HTTPS network traffic from the load balancer");
        System.out.println("- Two load balancing rules for HTTP and HTTPS to map public ports on the load\n" + "  balancer to ports in the backend address pool");
        System.out.println("- Two probes which contain HTTP and HTTPS health probes used to check availability\n" + "  of virtual machines in the backend address pool");
        System.out.println("- Two inbound NAT rules which contain rules that map a public port on the load\n" + "  balancer to a port for a specific virtual machine in the backend address pool\n" + "  - this provides direct VM connectivity for SSH to port 22 and TELNET to port 23");
        LoadBalancer loadBalancer1 = azure.loadBalancers().define(loadBalancerName1).withRegion(Region.US_EAST).withExistingResourceGroup(rgName).definePublicFrontend(frontendName).withExistingPublicIPAddress(publicIPAddress).attach().defineBackend(backendPoolName1).attach().defineBackend(backendPoolName2).attach().defineHttpProbe(httpProbe).withRequestPath("/").withPort(80).attach().defineHttpProbe(httpsProbe).withRequestPath("/").withPort(443).attach().defineLoadBalancingRule(httpLoadBalancingRule).withProtocol(TransportProtocol.TCP).withFrontend(frontendName).withFrontendPort(80).withProbe(httpProbe).withBackend(backendPoolName1).attach().defineLoadBalancingRule(httpsLoadBalancingRule).withProtocol(TransportProtocol.TCP).withFrontend(frontendName).withFrontendPort(443).withProbe(httpsProbe).withBackend(backendPoolName2).attach().defineInboundNatRule(natRule5000to22forVM1).withProtocol(TransportProtocol.TCP).withFrontend(frontendName).withFrontendPort(5000).withBackendPort(22).attach().defineInboundNatRule(natRule5001to23forVM1).withProtocol(TransportProtocol.TCP).withFrontend(frontendName).withFrontendPort(5001).withBackendPort(23).attach().defineInboundNatRule(natRule5002to22forVM2).withProtocol(TransportProtocol.TCP).withFrontend(frontendName).withFrontendPort(5002).withBackendPort(22).attach().defineInboundNatRule(natRule5003to23forVM2).withProtocol(TransportProtocol.TCP).withFrontend(frontendName).withFrontendPort(5003).withBackendPort(23).attach().create();
        // Print load balancer details
        System.out.println("Created a load balancer");
        Utils.print(loadBalancer1);
        //=============================================================
        // Define two network interfaces in the frontend subnet
        // associate network interfaces to NAT rules, backend pools
        System.out.println("Creating two network interfaces in the frontend subnet ...");
        System.out.println("- And associating network interfaces to backend pools and NAT rules");
        List<Creatable<NetworkInterface>> networkInterfaceCreatables = new ArrayList<Creatable<NetworkInterface>>();
        Creatable<NetworkInterface> networkInterface1Creatable = azure.networkInterfaces().define(networkInterfaceName1).withRegion(Region.US_EAST).withNewResourceGroup(rgName).withExistingPrimaryNetwork(network).withSubnet("Front-end").withPrimaryPrivateIPAddressDynamic().withExistingLoadBalancerBackend(loadBalancer1, backendPoolName1).withExistingLoadBalancerBackend(loadBalancer1, backendPoolName2).withExistingLoadBalancerInboundNatRule(loadBalancer1, natRule5000to22forVM1).withExistingLoadBalancerInboundNatRule(loadBalancer1, natRule5001to23forVM1);
        networkInterfaceCreatables.add(networkInterface1Creatable);
        Creatable<NetworkInterface> networkInterface2Creatable = azure.networkInterfaces().define(networkInterfaceName2).withRegion(Region.US_EAST).withNewResourceGroup(rgName).withExistingPrimaryNetwork(network).withSubnet("Front-end").withPrimaryPrivateIPAddressDynamic().withExistingLoadBalancerBackend(loadBalancer1, backendPoolName1).withExistingLoadBalancerBackend(loadBalancer1, backendPoolName2).withExistingLoadBalancerInboundNatRule(loadBalancer1, natRule5002to22forVM2).withExistingLoadBalancerInboundNatRule(loadBalancer1, natRule5003to23forVM2);
        networkInterfaceCreatables.add(networkInterface2Creatable);
        //=============================================================
        // Define an availability set
        Creatable<AvailabilitySet> availSet1Definition = azure.availabilitySets().define(availSetName).withRegion(Region.US_EAST).withNewResourceGroup(rgName).withFaultDomainCount(2).withUpdateDomainCount(4).withSku(AvailabilitySetSkuTypes.MANAGED);
        //=============================================================
        // Create two virtual machines and assign network interfaces
        System.out.println("Creating two virtual machines in the frontend subnet ...");
        System.out.println("- And assigning network interfaces");
        List<Creatable<VirtualMachine>> virtualMachineCreateables1 = new ArrayList<Creatable<VirtualMachine>>();
        for (Creatable<NetworkInterface> nicDefinition : networkInterfaceCreatables) {
            virtualMachineCreateables1.add(azure.virtualMachines().define(SdkContext.randomResourceName("lVM1", 24)).withRegion(Region.US_EAST).withExistingResourceGroup(rgName).withNewPrimaryNetworkInterface(nicDefinition).withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS).withRootUsername(userName).withSsh(sshKey).withSize(VirtualMachineSizeTypes.STANDARD_D3_V2).withNewAvailabilitySet(availSet1Definition));
        }
        StopWatch stopwatch = new StopWatch();
        stopwatch.start();
        Collection<VirtualMachine> virtualMachines = azure.virtualMachines().create(virtualMachineCreateables1).values();
        stopwatch.stop();
        System.out.println("Created 2 Linux VMs: (took " + (stopwatch.getTime() / 1000) + " seconds) ");
        System.out.println();
        // Print virtual machine details
        for (VirtualMachine vm : virtualMachines) {
            Utils.print(vm);
            System.out.println();
        }
        //=============================================================
        // Update a load balancer
        //  configure TCP idle timeout to 15 minutes
        System.out.println("Updating the load balancer ...");
        loadBalancer1.update().updateLoadBalancingRule(httpLoadBalancingRule).withIdleTimeoutInMinutes(15).parent().updateLoadBalancingRule(httpsLoadBalancingRule).withIdleTimeoutInMinutes(15).parent().apply();
        System.out.println("Update the load balancer with a TCP idle timeout to 15 minutes");
        //=============================================================
        // Create another public IP address
        System.out.println("Creating another public IP address...");
        PublicIPAddress publicIPAddress2 = azure.publicIPAddresses().define(publicIpName2).withRegion(Region.US_EAST).withExistingResourceGroup(rgName).withLeafDomainLabel(publicIpName2).create();
        System.out.println("Created another public IP address");
        // Print the virtual network details
        Utils.print(publicIPAddress2);
        //=============================================================
        // Create another Internet facing load balancer
        // Create a frontend IP address
        // Two backend address pools which contain network interfaces for the virtual
        //  machines to receive HTTP and HTTPS network traffic from the load balancer
        // Two load balancing rules for HTTP and HTTPS to map public ports on the load
        //  balancer to ports in the backend address pool
        // Two probes which contain HTTP and HTTPS health probes used to check availability
        //  of virtual machines in the backend address pool
        // Two inbound NAT rules which contain rules that map a public port on the load
        //  balancer to a port for a specific virtual machine in the backend address pool
        //  - this provides direct VM connectivity for SSH to port 22 and TELNET to port 23
        System.out.println("Creating another Internet facing load balancer with ...");
        System.out.println("- A frontend IP address");
        System.out.println("- Two backend address pools which contain network interfaces for the virtual\n" + "  machines to receive HTTP and HTTPS network traffic from the load balancer");
        System.out.println("- Two load balancing rules for HTTP and HTTPS to map public ports on the load\n" + "  balancer to ports in the backend address pool");
        System.out.println("- Two probes which contain HTTP and HTTPS health probes used to check availability\n" + "  of virtual machines in the backend address pool");
        System.out.println("- Two inbound NAT rules which contain rules that map a public port on the load\n" + "  balancer to a port for a specific virtual machine in the backend address pool\n" + "  - this provides direct VM connectivity for SSH to port 22 and TELNET to port 23");
        LoadBalancer loadBalancer2 = azure.loadBalancers().define(loadBalancerName2).withRegion(Region.US_EAST).withExistingResourceGroup(rgName).definePublicFrontend(frontendName).withExistingPublicIPAddress(publicIPAddress2).attach().defineBackend(backendPoolName1).attach().defineBackend(backendPoolName2).attach().defineHttpProbe(httpProbe).withRequestPath("/").withPort(80).attach().defineHttpProbe(httpsProbe).withRequestPath("/").withPort(443).attach().defineLoadBalancingRule(httpLoadBalancingRule).withProtocol(TransportProtocol.TCP).withFrontend(frontendName).withFrontendPort(80).withProbe(httpProbe).withBackend(backendPoolName1).attach().defineLoadBalancingRule(httpsLoadBalancingRule).withProtocol(TransportProtocol.TCP).withFrontend(frontendName).withFrontendPort(443).withProbe(httpsProbe).withBackend(backendPoolName2).attach().defineInboundNatRule(natRule5000to22forVM1).withProtocol(TransportProtocol.TCP).withFrontend(frontendName).withFrontendPort(5000).withBackendPort(22).attach().defineInboundNatRule(natRule5001to23forVM1).withProtocol(TransportProtocol.TCP).withFrontend(frontendName).withFrontendPort(5001).withBackendPort(23).attach().defineInboundNatRule(natRule5002to22forVM2).withProtocol(TransportProtocol.TCP).withFrontend(frontendName).withFrontendPort(5002).withBackendPort(22).attach().defineInboundNatRule(natRule5003to23forVM2).withProtocol(TransportProtocol.TCP).withFrontend(frontendName).withFrontendPort(5003).withBackendPort(23).attach().create();
        // Print load balancer details
        System.out.println("Created another load balancer");
        Utils.print(loadBalancer2);
        //=============================================================
        // List load balancers
        List<LoadBalancer> loadBalancers = azure.loadBalancers().list();
        System.out.println("Walking through the list of load balancers");
        for (LoadBalancer loadBalancer : loadBalancers) {
            Utils.print(loadBalancer);
        }
        //=============================================================
        // Remove a load balancer
        System.out.println("Deleting load balancer " + loadBalancerName2 + "(" + loadBalancer2.id() + ")");
        azure.loadBalancers().deleteById(loadBalancer2.id());
        System.out.println("Deleted load balancer" + loadBalancerName2);
        return true;
    } catch (Exception f) {
        System.out.println(f.getMessage());
        f.printStackTrace();
    } finally {
        try {
            System.out.println("Deleting Resource Group: " + rgName);
            azure.resourceGroups().deleteByName(rgName);
            System.out.println("Deleted Resource Group: " + rgName);
        } catch (NullPointerException npe) {
            System.out.println("Did not create any resources in Azure. No clean up is necessary");
        } catch (Exception g) {
            g.printStackTrace();
        }
    }
    return false;
}
Also used : ArrayList(java.util.ArrayList) LoadBalancer(com.microsoft.azure.management.network.LoadBalancer) NetworkInterface(com.microsoft.azure.management.network.NetworkInterface) PublicIPAddress(com.microsoft.azure.management.network.PublicIPAddress) StopWatch(org.apache.commons.lang3.time.StopWatch) Network(com.microsoft.azure.management.network.Network) Creatable(com.microsoft.azure.management.resources.fluentcore.model.Creatable) AvailabilitySet(com.microsoft.azure.management.compute.AvailabilitySet) VirtualMachine(com.microsoft.azure.management.compute.VirtualMachine)

Aggregations

PublicIPAddress (com.microsoft.azure.management.network.PublicIPAddress)24 VirtualMachine (com.microsoft.azure.management.compute.VirtualMachine)10 Network (com.microsoft.azure.management.network.Network)10 ArrayList (java.util.ArrayList)10 LoadBalancer (com.microsoft.azure.management.network.LoadBalancer)7 Region (com.microsoft.azure.management.resources.fluentcore.arm.Region)7 Creatable (com.microsoft.azure.management.resources.fluentcore.model.Creatable)6 LoadBalancerInboundNatRule (com.microsoft.azure.management.network.LoadBalancerInboundNatRule)5 NetworkInterface (com.microsoft.azure.management.network.NetworkInterface)4 ResourceGroup (com.microsoft.azure.management.resources.ResourceGroup)4 Date (java.util.Date)4 VirtualMachineScaleSet (com.microsoft.azure.management.compute.VirtualMachineScaleSet)3 VirtualMachineScaleSetVM (com.microsoft.azure.management.compute.VirtualMachineScaleSetVM)3 VirtualMachineScaleSetNetworkInterface (com.microsoft.azure.management.network.VirtualMachineScaleSetNetworkInterface)3 VirtualMachineScaleSetNicIPConfiguration (com.microsoft.azure.management.network.VirtualMachineScaleSetNicIPConfiguration)3 HashMap (java.util.HashMap)3 Map (java.util.Map)3 JSch (com.jcraft.jsch.JSch)2 Session (com.jcraft.jsch.Session)2 HashSet (java.util.HashSet)2