Search in sources :

Example 26 with Network

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

the class TestLoadBalancer method ensureVMs.

// Ensure VMs for the LB
private static VirtualMachine[] ensureVMs(Networks networks, VirtualMachines vms, AvailabilitySets availabilitySets, int count) throws Exception {
    // Create a network for the VMs
    Network network = networks.define("net" + TEST_ID).withRegion(REGION).withNewResourceGroup(GROUP_NAME).withAddressSpace("10.0.0.0/28").withSubnet("subnet1", "10.0.0.0/29").withSubnet("subnet2", "10.0.0.8/29").create();
    Creatable<AvailabilitySet> availabilitySetDefinition = availabilitySets.define("as" + TEST_ID).withRegion(REGION).withExistingResourceGroup(GROUP_NAME).withSku(AvailabilitySetSkuTypes.MANAGED);
    // Create the requested number of VM definitions
    String userName = "testuser" + TEST_ID;
    List<Creatable<VirtualMachine>> vmDefinitions = new ArrayList<>();
    for (int i = 0; i < count; i++) {
        String vmName = SdkContext.randomResourceName("vm", 15);
        Creatable<VirtualMachine> vm = vms.define(vmName).withRegion(REGION).withExistingResourceGroup(GROUP_NAME).withExistingPrimaryNetwork(network).withSubnet(network.subnets().values().iterator().next().name()).withPrimaryPrivateIPAddressDynamic().withoutPrimaryPublicIPAddress().withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_14_04_LTS).withRootUsername(userName).withRootPassword("Abcdef.123456").withNewAvailabilitySet(availabilitySetDefinition).withSize(VirtualMachineSizeTypes.STANDARD_A1);
        vmDefinitions.add(vm);
    }
    CreatedResources<VirtualMachine> createdVMs2 = vms.create(vmDefinitions);
    VirtualMachine[] array = new VirtualMachine[createdVMs2.size()];
    for (int index = 0; index < createdVMs2.size(); index++) {
        array[index] = createdVMs2.get(vmDefinitions.get(index).key());
    }
    return array;
}
Also used : Network(com.microsoft.azure.management.network.Network) ArrayList(java.util.ArrayList) Creatable(com.microsoft.azure.management.resources.fluentcore.model.Creatable) AvailabilitySet(com.microsoft.azure.management.compute.AvailabilitySet) VirtualMachine(com.microsoft.azure.management.compute.VirtualMachine)

Example 27 with Network

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

the class ManageSqlDatabasesAcrossDifferentDataCenters 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 sqlServerName = Utils.createRandomName("sqlserver");
    final String rgName = Utils.createRandomName("rgRSSDRE");
    final String administratorLogin = "sqladmin3423";
    final String administratorPassword = "myS3cureP@ssword";
    final String slaveSqlServer1Name = "slave1sql";
    final String slaveSqlServer2Name = "slave2sql";
    final String databaseName = "mydatabase";
    final String networkNamePrefix = "network";
    final String virtualMachineNamePrefix = "samplevm";
    try {
        // ============================================================
        // Create a SQL Server, with 2 firewall rules.
        SqlServer masterSqlServer = azure.sqlServers().define(sqlServerName).withRegion(Region.US_EAST).withNewResourceGroup(rgName).withAdministratorLogin(administratorLogin).withAdministratorPassword(administratorPassword).create();
        Utils.print(masterSqlServer);
        // ============================================================
        // Create a Database in master SQL server created above.
        System.out.println("Creating a database");
        SqlDatabase masterDatabase = masterSqlServer.databases().define(databaseName).withEdition(DatabaseEditions.BASIC).create();
        Utils.print(masterDatabase);
        // ============================================================
        // Create secondary SQLServer/Database for the master database
        System.out.println("Creating server in secondary location for master SQL Server");
        SqlServer sqlServerInSecondaryLocation = azure.sqlServers().define(Utils.createRandomName(slaveSqlServer1Name)).withRegion(masterDatabase.defaultSecondaryLocation()).withExistingResourceGroup(rgName).withAdministratorLogin(administratorLogin).withAdministratorPassword(administratorPassword).create();
        Utils.print(sqlServerInSecondaryLocation);
        System.out.println("Creating database in slave SQL Server.");
        SqlDatabase secondaryDatabase = sqlServerInSecondaryLocation.databases().define(databaseName).withSourceDatabase(masterDatabase).withMode(CreateMode.ONLINE_SECONDARY).create();
        Utils.print(secondaryDatabase);
        // ============================================================
        // Create another slave SQLServer/Database for the master database
        System.out.println("Creating server in another location for master SQL Server");
        SqlServer sqlServerInEurope = azure.sqlServers().define(Utils.createRandomName(slaveSqlServer2Name)).withRegion(Region.EUROPE_WEST).withExistingResourceGroup(rgName).withAdministratorLogin(administratorLogin).withAdministratorPassword(administratorPassword).create();
        Utils.print(sqlServerInEurope);
        System.out.println("Creating database in second slave SQL Server.");
        SqlDatabase secondaryDatabaseInEurope = sqlServerInEurope.databases().define(databaseName).withSourceDatabase(masterDatabase).withMode(CreateMode.ONLINE_SECONDARY).create();
        Utils.print(secondaryDatabaseInEurope);
        // ============================================================
        // Create Virtual Networks in different regions
        List<Region> regions = new ArrayList<>();
        regions.add(Region.US_EAST);
        regions.add(Region.US_WEST);
        regions.add(Region.EUROPE_NORTH);
        regions.add(Region.ASIA_SOUTHEAST);
        regions.add(Region.JAPAN_EAST);
        List<Creatable<Network>> creatableNetworks = new ArrayList<>();
        System.out.println("Creating virtual networks in different regions.");
        for (Region region : regions) {
            creatableNetworks.add(azure.networks().define(Utils.createRandomName(networkNamePrefix)).withRegion(region).withExistingResourceGroup(rgName));
        }
        Collection<Network> networks = azure.networks().create(creatableNetworks).values();
        // ============================================================
        // Create virtual machines attached to different virtual networks created above.
        List<Creatable<VirtualMachine>> creatableVirtualMachines = new ArrayList<>();
        System.out.println("Creating virtual machines in different regions.");
        for (Network network : networks) {
            String vmName = Utils.createRandomName(virtualMachineNamePrefix);
            Creatable<PublicIPAddress> publicIPAddressCreatable = azure.publicIPAddresses().define(vmName).withRegion(network.region()).withExistingResourceGroup(rgName).withLeafDomainLabel(vmName);
            creatableVirtualMachines.add(azure.virtualMachines().define(vmName).withRegion(network.region()).withExistingResourceGroup(rgName).withExistingPrimaryNetwork(network).withSubnet(network.subnets().values().iterator().next().name()).withPrimaryPrivateIPAddressDynamic().withNewPrimaryPublicIPAddress(publicIPAddressCreatable).withPopularWindowsImage(KnownWindowsVirtualMachineImage.WINDOWS_SERVER_2012_R2_DATACENTER).withAdminUsername(administratorLogin).withAdminPassword(administratorPassword).withSize(VirtualMachineSizeTypes.STANDARD_D3_V2));
        }
        HashMap<String, String> ipAddresses = new HashMap<>();
        for (VirtualMachine virtualMachine : azure.virtualMachines().create(creatableVirtualMachines).values()) {
            ipAddresses.put(virtualMachine.name(), virtualMachine.getPrimaryPublicIPAddress().ipAddress());
        }
        System.out.println("Adding firewall rule for each of virtual network network");
        List<SqlServer> sqlServers = new ArrayList<>();
        sqlServers.add(sqlServerInSecondaryLocation);
        sqlServers.add(sqlServerInEurope);
        sqlServers.add(masterSqlServer);
        for (SqlServer sqlServer : sqlServers) {
            for (Map.Entry<String, String> ipAddress : ipAddresses.entrySet()) {
                sqlServer.firewallRules().define(ipAddress.getKey()).withIPAddress(ipAddress.getValue()).create();
            }
        }
        for (SqlServer sqlServer : sqlServers) {
            System.out.println("Print firewall rules in Sql Server in " + sqlServer.regionName());
            List<SqlFirewallRule> firewallRules = sqlServer.firewallRules().list();
            for (SqlFirewallRule firewallRule : firewallRules) {
                Utils.print(firewallRule);
            }
        }
        // Delete the SQL Server.
        System.out.println("Deleting all Sql Servers");
        for (SqlServer sqlServer : sqlServers) {
            azure.sqlServers().deleteById(sqlServer.id());
        }
        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 (Exception e) {
            System.out.println("Did not create any resources in Azure. No clean up is necessary");
        }
    }
    return false;
}
Also used : HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) PublicIPAddress(com.microsoft.azure.management.network.PublicIPAddress) SqlServer(com.microsoft.azure.management.sql.SqlServer) Network(com.microsoft.azure.management.network.Network) Region(com.microsoft.azure.management.resources.fluentcore.arm.Region) Creatable(com.microsoft.azure.management.resources.fluentcore.model.Creatable) SqlDatabase(com.microsoft.azure.management.sql.SqlDatabase) SqlFirewallRule(com.microsoft.azure.management.sql.SqlFirewallRule) HashMap(java.util.HashMap) Map(java.util.Map) VirtualMachine(com.microsoft.azure.management.compute.VirtualMachine)

Example 28 with Network

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

the class ManageVirtualMachineAsync 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(final Azure azure) {
    final Region region = Region.US_WEST_CENTRAL;
    final String windowsVMName = Utils.createRandomName("wVM");
    final String linuxVMName = Utils.createRandomName("lVM");
    final String rgName = Utils.createRandomName("rgCOMV");
    final String userName = "tirekicker";
    final String password = "12NewPA$$w0rd!";
    final String windowsVmKey = "WindowsVM";
    final String linuxVmKey = "LinuxVM";
    try {
        //=============================================================
        // Create a Windows virtual machine
        // Prepare a creatable data disk for VM
        //
        final Date t1 = new Date();
        final Creatable<Disk> dataDiskCreatable = azure.disks().define(Utils.createRandomName("dsk-")).withRegion(region).withExistingResourceGroup(rgName).withData().withSizeInGB(100);
        // Create a data disk to attach to VM
        //
        Observable<Indexable> dataDiskObservable = azure.disks().define(Utils.createRandomName("dsk-")).withRegion(region).withNewResourceGroup(rgName).withData().withSizeInGB(50).createAsync();
        final Map<String, VirtualMachine> createdVms = new TreeMap<>();
        dataDiskObservable.flatMap(new Func1<Indexable, Observable<Indexable>>() {

            @Override
            public Observable<Indexable> call(Indexable createdResource) {
                if (createdResource instanceof Disk) {
                    System.out.println("Creating a Windows VM");
                    return azure.virtualMachines().define(windowsVMName).withRegion(region).withNewResourceGroup(rgName).withNewPrimaryNetwork("10.0.0.0/28").withPrimaryPrivateIPAddressDynamic().withoutPrimaryPublicIPAddress().withPopularWindowsImage(KnownWindowsVirtualMachineImage.WINDOWS_SERVER_2012_R2_DATACENTER).withAdminUsername(userName).withAdminPassword(password).withNewDataDisk(10).withNewDataDisk(dataDiskCreatable).withExistingDataDisk((Disk) createdResource).withSize(VirtualMachineSizeTypes.STANDARD_D3_V2).createAsync();
                }
                return Observable.just(createdResource);
            }
        }).flatMap(new Func1<Indexable, Observable<Indexable>>() {

            @Override
            public Observable<Indexable> call(Indexable createdResource) {
                if (createdResource instanceof Network) {
                    // Once Network object is created we can start creation of Linux VM in the same network
                    Network network = (Network) createdResource;
                    System.out.println("Created Network");
                    Utils.print(network);
                    System.out.println("Creating a Linux VM in the same network");
                    return azure.virtualMachines().define(linuxVMName).withRegion(region).withExistingResourceGroup(rgName).withExistingPrimaryNetwork(network).withSubnet(// Referencing the default subnet name when no name specified at creation
                    "subnet1").withPrimaryPrivateIPAddressDynamic().withoutPrimaryPublicIPAddress().withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS).withRootUsername(userName).withRootPassword(password).withSize(VirtualMachineSizeTypes.STANDARD_D3_V2).createAsync();
                }
                return Observable.just(createdResource);
            }
        }).map(new Func1<Indexable, Indexable>() {

            @Override
            public Indexable call(Indexable createdResource) {
                if (createdResource instanceof VirtualMachine) {
                    Date t2 = new Date();
                    VirtualMachine virtualMachine = (VirtualMachine) createdResource;
                    if (isWindowsVM(virtualMachine)) {
                        createdVms.put(windowsVmKey, virtualMachine);
                        System.out.println("Created Windows VM: " + virtualMachine.id());
                    } else {
                        createdVms.put(linuxVmKey, virtualMachine);
                        System.out.println("Created a Linux VM (in the same virtual network): " + virtualMachine.id());
                    }
                    System.out.println("Virtual machine creation took " + ((t2.getTime() - t1.getTime()) / 1000) + " seconds");
                    // Print virtual machine details
                    Utils.print(virtualMachine);
                }
                return createdResource;
            }
        }).toBlocking().subscribe();
        final VirtualMachine windowsVM = createdVms.get(windowsVmKey);
        final VirtualMachine linuxVM = createdVms.get(linuxVmKey);
        //=============================================================
        // Update virtual machines
        // - Tag the virtual machine on Linux VM
        Observable<VirtualMachine> updateLinuxVMChain = linuxVM.update().withTag("who-rocks-on-linux", "java").withTag("where", "on azure").applyAsync().map(new Func1<VirtualMachine, VirtualMachine>() {

            @Override
            public VirtualMachine call(VirtualMachine virtualMachine) {
                System.out.println("Tagged Linux VM: " + virtualMachine.id());
                return virtualMachine;
            }
        });
        // - Add a data disk on Windows VM.
        Observable<VirtualMachine> updateWindowsVMChain = windowsVM.update().withNewDataDisk(200).applyAsync();
        Observable.merge(updateLinuxVMChain, updateWindowsVMChain).toBlocking().subscribe();
        //=============================================================
        // List virtual machines and print details
        azure.virtualMachines().listByResourceGroupAsync(rgName).map(new Func1<VirtualMachine, VirtualMachine>() {

            @Override
            public VirtualMachine call(VirtualMachine virtualMachine) {
                System.out.println("Retrieved details for VM: " + virtualMachine.id());
                Utils.print(virtualMachine);
                return virtualMachine;
            }
        }).toBlocking().subscribe();
        //=============================================================
        // Delete the virtual machines in parallel
        Observable.merge(azure.virtualMachines().deleteByIdAsync(windowsVM.id()).toObservable(), azure.virtualMachines().deleteByIdAsync(linuxVM.id()).toObservable()).toBlocking().subscribe();
        return true;
    } catch (Exception f) {
        System.out.println(f.getMessage());
        f.printStackTrace();
    } finally {
        try {
            System.out.println("Deleting Resource Group: " + rgName);
            azure.resourceGroups().deleteByNameAsync(rgName).await();
            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 : TreeMap(java.util.TreeMap) Date(java.util.Date) Observable(rx.Observable) Network(com.microsoft.azure.management.network.Network) Region(com.microsoft.azure.management.resources.fluentcore.arm.Region) Indexable(com.microsoft.azure.management.resources.fluentcore.model.Indexable) Func1(rx.functions.Func1) Disk(com.microsoft.azure.management.compute.Disk) VirtualMachine(com.microsoft.azure.management.compute.VirtualMachine)

Example 29 with Network

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

the class ManageVirtualMachineScaleSet 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 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).withNewDataDisk(100).withNewDataDisk(100, 1, CachingTypes.READ_WRITE).withNewDataDisk(100, 2, CachingTypes.READ_WRITE, StorageAccountTypes.STANDARD_LRS).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");
        //=============================================================
        // Deallocate the virtual machine scale set
        System.out.println("De-allocating virtual machine scale set ...");
        virtualMachineScaleSet.deallocate();
        System.out.println("De-allocated virtual machine scale set");
        //=============================================================
        // Update the virtual machine scale set by removing and adding disk
        System.out.println("Updating virtual machine scale set managed data disks...");
        virtualMachineScaleSet.update().withoutDataDisk(0).withoutDataDisk(200).apply();
        System.out.println("Updated 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 30 with Network

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

the class ManageVirtualMachineScaleSetAsync 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(final 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 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 ...");
        System.out.println("Creating a public IP address...");
        System.out.println("Creating a load balancer");
        final List<Indexable> createdResources = new ArrayList<>();
        Observable.merge(azure.networks().define(vnetName).withRegion(region).withNewResourceGroup(rgName).withAddressSpace("172.16.0.0/16").defineSubnet("Front-end").withAddressPrefix("172.16.1.0/24").attach().createAsync(), azure.publicIPAddresses().define(publicIpName).withRegion(region).withExistingResourceGroup(rgName).withLeafDomainLabel(publicIpName).createAsync().flatMap(new Func1<Indexable, Observable<Indexable>>() {

            @Override
            public Observable<Indexable> call(Indexable indexable) {
                if (indexable instanceof PublicIPAddress) {
                    PublicIPAddress publicIp = (PublicIPAddress) indexable;
                    //=============================================================
                    // 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");
                    return Observable.merge(Observable.just(indexable), azure.loadBalancers().define(loadBalancerName1).withRegion(region).withExistingResourceGroup(rgName).definePublicFrontend(frontendName).withExistingPublicIPAddress(publicIp).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().createAsync());
                }
                return Observable.just(indexable);
            }
        })).toBlocking().subscribe(new Action1<Indexable>() {

            @Override
            public void call(Indexable indexable) {
                createdResources.add(indexable);
            }
        });
        Network network = null;
        PublicIPAddress publicIPAddress = null;
        LoadBalancer loadBalancer1 = null;
        for (Indexable indexable : createdResources) {
            if (indexable instanceof PublicIPAddress) {
                publicIPAddress = (PublicIPAddress) indexable;
                System.out.println("Created a public IP address");
                // Print the virtual network details
                Utils.print(publicIPAddress);
            } else if (indexable instanceof Network) {
                network = (Network) indexable;
                System.out.println("Created a virtual network");
                // Print the virtual network details
                Utils.print(network);
            } else if (indexable instanceof LoadBalancer) {
                loadBalancer1 = (LoadBalancer) indexable;
                // 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 ...");
        final Date t1 = new Date();
        VirtualMachineScaleSet 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).withNewDataDisk(100).withNewDataDisk(100, 1, CachingTypes.READ_WRITE).withNewDataDisk(100, 2, CachingTypes.READ_WRITE, StorageAccountTypes.STANDARD_LRS).withCapacity(3).defineNewExtension("CustomScriptForLinux").withPublisher("Microsoft.OSTCExtensions").withType("CustomScriptForLinux").withVersion("1.4").withMinorVersionAutoUpgrade().withPublicSetting("fileUris", fileUris).withPublicSetting("commandToExecute", installCommand).attach().createAsync().map(new Func1<Indexable, Indexable>() {

            @Override
            public Indexable call(Indexable indexable) {
                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();
                return indexable;
            }
        }).toBlocking().last();
        final String pipFqdn = publicIPAddress.fqdn();
        //=============================================================
        // 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...");
        virtualMachineScaleSet.virtualMachines().listAsync().map(new Func1<VirtualMachineScaleSetVM, VirtualMachineScaleSetVM>() {

            @Override
            public VirtualMachineScaleSetVM call(VirtualMachineScaleSetVM instance) {
                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 + "@" + pipFqdn + ":" + natRule.frontendPort());
                                break;
                            }
                        }
                        break;
                    }
                }
                return instance;
            }
        }).toBlocking().subscribe();
        //=============================================================
        // Stop the virtual machine scale set
        System.out.println("Updating virtual machine scale set ...");
        // Stop the virtual machine scale set
        virtualMachineScaleSet.powerOffAsync().concatWith(virtualMachineScaleSet.deallocateAsync()).concatWith(virtualMachineScaleSet.startAsync()).toObservable().concatWith(virtualMachineScaleSet.update().withCapacity(6).withoutDataDisk(0).withoutDataDisk(200).applyAsync().flatMap(new Func1<VirtualMachineScaleSet, Observable<Void>>() {

            @Override
            public Observable<Void> call(VirtualMachineScaleSet virtualMachineScaleSet) {
                System.out.println("Updated virtual machine scale set");
                // Restart the virtual machine scale set
                return virtualMachineScaleSet.restartAsync().toObservable();
            }
        })).toBlocking().subscribe();
        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 : PagedList(com.microsoft.azure.PagedList) 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) Indexable(com.microsoft.azure.management.resources.fluentcore.model.Indexable) VirtualMachineScaleSet(com.microsoft.azure.management.compute.VirtualMachineScaleSet) ArrayList(java.util.ArrayList) PagedList(com.microsoft.azure.PagedList) List(java.util.List) Func1(rx.functions.Func1)

Aggregations

Network (com.microsoft.azure.management.network.Network)37 VirtualMachine (com.microsoft.azure.management.compute.VirtualMachine)17 Region (com.microsoft.azure.management.resources.fluentcore.arm.Region)15 ArrayList (java.util.ArrayList)14 Creatable (com.microsoft.azure.management.resources.fluentcore.model.Creatable)11 PublicIPAddress (com.microsoft.azure.management.network.PublicIPAddress)10 ResourceGroup (com.microsoft.azure.management.resources.ResourceGroup)10 Date (java.util.Date)10 LoadBalancer (com.microsoft.azure.management.network.LoadBalancer)7 NetworkInterface (com.microsoft.azure.management.network.NetworkInterface)7 StopWatch (org.apache.commons.lang3.time.StopWatch)6 NetworkSecurityGroup (com.microsoft.azure.management.network.NetworkSecurityGroup)5 Indexable (com.microsoft.azure.management.resources.fluentcore.model.Indexable)5 StorageAccount (com.microsoft.azure.management.storage.StorageAccount)5 HashMap (java.util.HashMap)5 Test (org.junit.Test)5 AvailabilitySet (com.microsoft.azure.management.compute.AvailabilitySet)4 Subnet (com.microsoft.azure.management.network.Subnet)4 VirtualNetwork (com.microsoft.tooling.msservices.model.vm.VirtualNetwork)4 VirtualMachineScaleSet (com.microsoft.azure.management.compute.VirtualMachineScaleSet)3