Search in sources :

Example 36 with VirtualMachine

use of com.microsoft.azure.management.compute.VirtualMachine in project azure-sdk-for-java by Azure.

the class ManageVirtualMachinesInParallelWithNetwork 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 int frontendVMCount = 10;
    final int backendVMCount = 10;
    final String rgName = SdkContext.randomResourceName("rgNEPP", 24);
    final String frontEndNsgName = SdkContext.randomResourceName("fensg", 24);
    final String backEndNsgName = SdkContext.randomResourceName("bensg", 24);
    final String networkName = SdkContext.randomResourceName("vnetCOMV", 24);
    final String storageAccountName = SdkContext.randomResourceName("stgCOMV", 20);
    final String userName = "tirekicker";
    final String password = "12NewPA$$w0rd!";
    try {
        // Create a resource group [Where all resources gets created]
        ResourceGroup resourceGroup = azure.resourceGroups().define(rgName).withRegion(Region.US_EAST).create();
        //============================================================
        // Define a network security group for the front end of a subnet
        // front end subnet contains two rules
        // - ALLOW-SSH - allows SSH traffic into the front end subnet
        // - ALLOW-WEB- allows HTTP traffic into the front end subnet
        Creatable<NetworkSecurityGroup> frontEndNSGCreatable = azure.networkSecurityGroups().define(frontEndNsgName).withRegion(Region.US_EAST).withExistingResourceGroup(resourceGroup).defineRule("ALLOW-SSH").allowInbound().fromAnyAddress().fromAnyPort().toAnyAddress().toPort(22).withProtocol(SecurityRuleProtocol.TCP).withPriority(100).withDescription("Allow SSH").attach().defineRule("ALLOW-HTTP").allowInbound().fromAnyAddress().fromAnyPort().toAnyAddress().toPort(80).withProtocol(SecurityRuleProtocol.TCP).withPriority(101).withDescription("Allow HTTP").attach();
        //============================================================
        // Define a network security group for the back end of a subnet
        // back end subnet contains two rules
        // - ALLOW-SQL - allows SQL traffic only from the front end subnet
        // - DENY-WEB - denies all outbound internet traffic from the back end subnet
        Creatable<NetworkSecurityGroup> backEndNSGCreatable = azure.networkSecurityGroups().define(backEndNsgName).withRegion(Region.US_EAST).withExistingResourceGroup(resourceGroup).defineRule("ALLOW-SQL").allowInbound().fromAddress("172.16.1.0/24").fromAnyPort().toAnyAddress().toPort(1433).withProtocol(SecurityRuleProtocol.TCP).withPriority(100).withDescription("Allow SQL").attach().defineRule("DENY-WEB").denyOutbound().fromAnyAddress().fromAnyPort().toAnyAddress().toAnyPort().withAnyProtocol().withDescription("Deny Web").withPriority(200).attach();
        System.out.println("Creating security group for the front ends - allows SSH and HTTP");
        System.out.println("Creating security group for the back ends - allows SSH and denies all outbound internet traffic");
        @SuppressWarnings("unchecked") Collection<NetworkSecurityGroup> networkSecurityGroups = azure.networkSecurityGroups().create(frontEndNSGCreatable, backEndNSGCreatable).values();
        NetworkSecurityGroup frontendNSG = null;
        NetworkSecurityGroup backendNSG = null;
        for (NetworkSecurityGroup nsg : networkSecurityGroups) {
            if (nsg.name().equalsIgnoreCase(frontEndNsgName)) {
                frontendNSG = nsg;
            }
            if (nsg.name().equalsIgnoreCase(backEndNsgName)) {
                backendNSG = nsg;
            }
        }
        System.out.println("Created a security group for the front end: " + frontendNSG.id());
        Utils.print(frontendNSG);
        System.out.println("Created a security group for the back end: " + backendNSG.id());
        Utils.print(backendNSG);
        // Create Network [Where all the virtual machines get added to]
        Network network = azure.networks().define(networkName).withRegion(Region.US_EAST).withExistingResourceGroup(resourceGroup).withAddressSpace("172.16.0.0/16").defineSubnet("Front-end").withAddressPrefix("172.16.1.0/24").withExistingNetworkSecurityGroup(frontendNSG).attach().defineSubnet("Back-end").withAddressPrefix("172.16.2.0/24").withExistingNetworkSecurityGroup(backendNSG).attach().create();
        // Prepare Creatable Storage account definition [For storing VMs disk]
        Creatable<StorageAccount> creatableStorageAccount = azure.storageAccounts().define(storageAccountName).withRegion(Region.US_EAST).withExistingResourceGroup(resourceGroup);
        // Prepare a batch of Creatable Virtual Machines definitions
        List<Creatable<VirtualMachine>> frontendCreatableVirtualMachines = new ArrayList<>();
        for (int i = 0; i < frontendVMCount; i++) {
            Creatable<VirtualMachine> creatableVirtualMachine = azure.virtualMachines().define("VM-FE-" + i).withRegion(Region.US_EAST).withExistingResourceGroup(resourceGroup).withExistingPrimaryNetwork(network).withSubnet("Front-end").withPrimaryPrivateIPAddressDynamic().withoutPrimaryPublicIPAddress().withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS).withRootUsername(userName).withRootPassword(password).withSize(VirtualMachineSizeTypes.STANDARD_D3_V2).withNewStorageAccount(creatableStorageAccount);
            frontendCreatableVirtualMachines.add(creatableVirtualMachine);
        }
        List<Creatable<VirtualMachine>> backendCreatableVirtualMachines = new ArrayList<>();
        for (int i = 0; i < backendVMCount; i++) {
            Creatable<VirtualMachine> creatableVirtualMachine = azure.virtualMachines().define("VM-BE-" + i).withRegion(Region.US_EAST).withExistingResourceGroup(resourceGroup).withExistingPrimaryNetwork(network).withSubnet("Back-end").withPrimaryPrivateIPAddressDynamic().withoutPrimaryPublicIPAddress().withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS).withRootUsername(userName).withRootPassword(password).withSize(VirtualMachineSizeTypes.STANDARD_D3_V2).withNewStorageAccount(creatableStorageAccount);
            backendCreatableVirtualMachines.add(creatableVirtualMachine);
        }
        System.out.println("Creating the virtual machines");
        List<Creatable<VirtualMachine>> allCreatableVirtualMachines = new ArrayList<>();
        allCreatableVirtualMachines.addAll(frontendCreatableVirtualMachines);
        allCreatableVirtualMachines.addAll(backendCreatableVirtualMachines);
        StopWatch stopwatch = new StopWatch();
        stopwatch.start();
        Collection<VirtualMachine> virtualMachines = azure.virtualMachines().create(allCreatableVirtualMachines).values();
        stopwatch.stop();
        System.out.println("Created virtual machines");
        for (VirtualMachine virtualMachine : virtualMachines) {
            System.out.println(virtualMachine.id());
        }
        System.out.println("Virtual Machines create: (took " + (stopwatch.getTime() / 1000) + " seconds) ");
        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 : NetworkSecurityGroup(com.microsoft.azure.management.network.NetworkSecurityGroup) ArrayList(java.util.ArrayList) StopWatch(org.apache.commons.lang3.time.StopWatch) StorageAccount(com.microsoft.azure.management.storage.StorageAccount) Network(com.microsoft.azure.management.network.Network) Creatable(com.microsoft.azure.management.resources.fluentcore.model.Creatable) ResourceGroup(com.microsoft.azure.management.resources.ResourceGroup) VirtualMachine(com.microsoft.azure.management.compute.VirtualMachine)

Example 37 with VirtualMachine

use of com.microsoft.azure.management.compute.VirtualMachine in project azure-sdk-for-java by Azure.

the class ManageVirtualNetwork 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 vnetName1 = SdkContext.randomResourceName("vnet1", 20);
    final String vnetName2 = SdkContext.randomResourceName("vnet2", 20);
    final String vnet1FrontEndSubnetName = "frontend";
    final String vnet1BackEndSubnetName = "backend";
    final String vnet1FrontEndSubnetNsgName = "frontendnsg";
    final String vnet1BackEndSubnetNsgName = "backendnsg";
    final String frontEndVMName = SdkContext.randomResourceName("fevm", 24);
    final String backEndVMName = SdkContext.randomResourceName("bevm", 24);
    final String publicIPAddressLeafDnsForFrontEndVM = SdkContext.randomResourceName("pip1", 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 rgName = SdkContext.randomResourceName("rgNEMV", 24);
    try {
        //============================================================
        // Create a virtual network with specific address-space and two subnet
        // Creates a network security group for backend subnet
        System.out.println("Creating a network security group for virtual network backend subnet...");
        NetworkSecurityGroup backEndSubnetNsg = azure.networkSecurityGroups().define(vnet1BackEndSubnetNsgName).withRegion(Region.US_EAST).withNewResourceGroup(rgName).defineRule("DenyInternetInComing").denyInbound().fromAddress("INTERNET").fromAnyPort().toAnyAddress().toAnyPort().withAnyProtocol().attach().defineRule("DenyInternetOutGoing").denyOutbound().fromAnyAddress().fromAnyPort().toAddress("INTERNET").toAnyPort().withAnyProtocol().attach().create();
        System.out.println("Created network security group");
        // Print the network security group
        Utils.print(backEndSubnetNsg);
        // Create the virtual network with frontend and backend subnets, with
        // network security group rule applied to backend subnet]
        System.out.println("Creating virtual network #1...");
        Network virtualNetwork1 = azure.networks().define(vnetName1).withRegion(Region.US_EAST).withExistingResourceGroup(rgName).withAddressSpace("192.168.0.0/16").withSubnet(vnet1FrontEndSubnetName, "192.168.1.0/24").defineSubnet(vnet1BackEndSubnetName).withAddressPrefix("192.168.2.0/24").withExistingNetworkSecurityGroup(backEndSubnetNsg).attach().create();
        System.out.println("Created a virtual network");
        // Print the virtual network details
        Utils.print(virtualNetwork1);
        //============================================================
        // Update a virtual network
        // Creates a network security group for frontend subnet
        System.out.println("Creating a network security group for virtual network backend subnet...");
        NetworkSecurityGroup frontEndSubnetNsg = azure.networkSecurityGroups().define(vnet1FrontEndSubnetNsgName).withRegion(Region.US_EAST).withExistingResourceGroup(rgName).defineRule("AllowHttpInComing").allowInbound().fromAddress("INTERNET").fromAnyPort().toAnyAddress().toPort(80).withProtocol(SecurityRuleProtocol.TCP).attach().defineRule("DenyInternetOutGoing").denyOutbound().fromAnyAddress().fromAnyPort().toAddress("INTERNET").toAnyPort().withAnyProtocol().attach().create();
        System.out.println("Created network security group");
        // Print the network security group
        Utils.print(frontEndSubnetNsg);
        // Update the virtual network frontend subnet by associating it with network security group
        System.out.println("Associating network security group rule to frontend subnet");
        virtualNetwork1.update().updateSubnet(vnet1FrontEndSubnetName).withExistingNetworkSecurityGroup(frontEndSubnetNsg).parent().apply();
        System.out.println("Network security group rule associated with the frontend subnet");
        // Print the virtual network details
        Utils.print(virtualNetwork1);
        //============================================================
        // Create a virtual machine in each subnet
        // Creates the first virtual machine in frontend subnet
        System.out.println("Creating a Linux virtual machine in the frontend subnet");
        Date t1 = new Date();
        VirtualMachine frontEndVM = azure.virtualMachines().define(frontEndVMName).withRegion(Region.US_EAST).withExistingResourceGroup(rgName).withExistingPrimaryNetwork(virtualNetwork1).withSubnet(vnet1FrontEndSubnetName).withPrimaryPrivateIPAddressDynamic().withNewPrimaryPublicIPAddress(publicIPAddressLeafDnsForFrontEndVM).withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS).withRootUsername(userName).withSsh(sshKey).withSize(VirtualMachineSizeTypes.STANDARD_D3_V2).create();
        Date t2 = new Date();
        System.out.println("Created Linux VM: (took " + ((t2.getTime() - t1.getTime()) / 1000) + " seconds) " + frontEndVM.id());
        // Print virtual machine details
        Utils.print(frontEndVM);
        // Creates the second virtual machine in the backend subnet
        System.out.println("Creating a Linux virtual machine in the backend subnet");
        Date t3 = new Date();
        VirtualMachine backEndVM = azure.virtualMachines().define(backEndVMName).withRegion(Region.US_EAST).withExistingResourceGroup(rgName).withExistingPrimaryNetwork(virtualNetwork1).withSubnet(vnet1BackEndSubnetName).withPrimaryPrivateIPAddressDynamic().withoutPrimaryPublicIPAddress().withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS).withRootUsername(userName).withSsh(sshKey).withSize(VirtualMachineSizeTypes.STANDARD_D3_V2).create();
        Date t4 = new Date();
        System.out.println("Created Linux VM: (took " + ((t4.getTime() - t3.getTime()) / 1000) + " seconds) " + backEndVM.id());
        // Print virtual machine details
        Utils.print(backEndVM);
        //============================================================
        // Create a virtual network with default address-space and one default subnet
        System.out.println("Creating virtual network #2...");
        Network virtualNetwork2 = azure.networks().define(vnetName2).withRegion(Region.US_EAST).withNewResourceGroup(rgName).create();
        System.out.println("Created a virtual network");
        // Print the virtual network details
        Utils.print(virtualNetwork2);
        for (Network virtualNetwork : azure.networks().listByResourceGroup(rgName)) {
            Utils.print(virtualNetwork);
        }
        //============================================================
        // Delete a virtual network
        System.out.println("Deleting the virtual network");
        azure.networks().deleteById(virtualNetwork2.id());
        System.out.println("Deleted the virtual network");
        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 : NetworkSecurityGroup(com.microsoft.azure.management.network.NetworkSecurityGroup) Network(com.microsoft.azure.management.network.Network) Date(java.util.Date) VirtualMachine(com.microsoft.azure.management.compute.VirtualMachine)

Example 38 with VirtualMachine

use of com.microsoft.azure.management.compute.VirtualMachine in project azure-sdk-for-java by Azure.

the class ManageVirtualNetworkAsync 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 String vnetName1 = SdkContext.randomResourceName("vnet1", 20);
    final String vnetName2 = SdkContext.randomResourceName("vnet2", 20);
    final String vnet1FrontEndSubnetName = "frontend";
    final String vnet1BackEndSubnetName = "backend";
    final String vnet1FrontEndSubnetNsgName = "frontendnsg";
    final String vnet1BackEndSubnetNsgName = "backendnsg";
    final String frontEndVMName = SdkContext.randomResourceName("fevm", 24);
    final String backEndVMName = SdkContext.randomResourceName("bevm", 24);
    final String publicIPAddressLeafDnsForFrontEndVM = SdkContext.randomResourceName("pip1", 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 rgName = SdkContext.randomResourceName("rgNEMV", 24);
    try {
        //============================================================
        // Create a virtual network with specific address-space and two subnet
        // Creates a network security group for backend subnet
        System.out.println("Creating a network security group for virtual network backend subnet...");
        // Creates a network security group for frontend subnet
        System.out.println("Creating a network security group for virtual network backend subnet...");
        final Map<String, Indexable> createdResources = new TreeMap<>();
        Observable.merge(azure.networkSecurityGroups().define(vnet1BackEndSubnetNsgName).withRegion(Region.US_EAST).withNewResourceGroup(rgName).defineRule("DenyInternetInComing").denyInbound().fromAddress("INTERNET").fromAnyPort().toAnyAddress().toAnyPort().withAnyProtocol().attach().defineRule("DenyInternetOutGoing").denyOutbound().fromAnyAddress().fromAnyPort().toAddress("INTERNET").toAnyPort().withAnyProtocol().attach().createAsync().flatMap(new Func1<Indexable, Observable<Indexable>>() {

            @Override
            public Observable<Indexable> call(Indexable indexable) {
                if (indexable instanceof NetworkSecurityGroup) {
                    NetworkSecurityGroup backEndNsg = (NetworkSecurityGroup) indexable;
                    System.out.println("Creating virtual network #1...");
                    return Observable.merge(Observable.just(indexable), azure.networks().define(vnetName1).withRegion(Region.US_EAST).withExistingResourceGroup(rgName).withAddressSpace("192.168.0.0/16").withSubnet(vnet1FrontEndSubnetName, "192.168.1.0/24").defineSubnet(vnet1BackEndSubnetName).withAddressPrefix("192.168.2.0/24").withExistingNetworkSecurityGroup(backEndNsg).attach().createAsync());
                }
                return Observable.just(indexable);
            }
        }), azure.networkSecurityGroups().define(vnet1FrontEndSubnetNsgName).withRegion(Region.US_EAST).withExistingResourceGroup(rgName).defineRule("AllowHttpInComing").allowInbound().fromAddress("INTERNET").fromAnyPort().toAnyAddress().toPort(80).withProtocol(SecurityRuleProtocol.TCP).attach().defineRule("DenyInternetOutGoing").denyOutbound().fromAnyAddress().fromAnyPort().toAddress("INTERNET").toAnyPort().withAnyProtocol().attach().createAsync()).map(new Func1<Indexable, Indexable>() {

            @Override
            public Indexable call(Indexable indexable) {
                if (indexable instanceof NetworkSecurityGroup) {
                    NetworkSecurityGroup nsg = (NetworkSecurityGroup) indexable;
                    System.out.println("Created network security group");
                    // Print the network security group
                    Utils.print(nsg);
                    createdResources.put(nsg.name(), nsg);
                } else if (indexable instanceof Network) {
                    Network vn = (Network) indexable;
                    System.out.println("Created a virtual network");
                    // Print the virtual network details
                    Utils.print(vn);
                    createdResources.put(vn.name(), vn);
                }
                return indexable;
            }
        }).toBlocking().subscribe();
        NetworkSecurityGroup frontEndSubnetNsg = (NetworkSecurityGroup) createdResources.get(vnet1FrontEndSubnetNsgName);
        Network virtualNetwork1 = (Network) createdResources.get(vnetName1);
        //============================================================
        // Update a virtual network
        // Update the virtual network frontend subnet by associating it with network security group
        System.out.println("Associating network security group rule to frontend subnet");
        virtualNetwork1.update().updateSubnet(vnet1FrontEndSubnetName).withExistingNetworkSecurityGroup(frontEndSubnetNsg).parent().applyAsync().toCompletable().await();
        System.out.println("Network security group rule associated with the frontend subnet");
        // Print the virtual network details
        Utils.print(virtualNetwork1);
        //============================================================
        // Create a virtual machine in each subnet and another virtual network
        // Creates the first virtual machine in frontend subnet
        System.out.println("Creating a Linux virtual machine in the frontend subnet");
        // Creates the second virtual machine in the backend subnet
        System.out.println("Creating a Linux virtual machine in the backend subnet");
        // Create a virtual network with default address-space and one default subnet
        System.out.println("Creating virtual network #2...");
        final Date t1 = new Date();
        Observable.merge(azure.virtualMachines().define(frontEndVMName).withRegion(Region.US_EAST).withExistingResourceGroup(rgName).withExistingPrimaryNetwork(virtualNetwork1).withSubnet(vnet1FrontEndSubnetName).withPrimaryPrivateIPAddressDynamic().withNewPrimaryPublicIPAddress(publicIPAddressLeafDnsForFrontEndVM).withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS).withRootUsername(userName).withSsh(sshKey).withSize(VirtualMachineSizeTypes.STANDARD_D3_V2).createAsync(), azure.virtualMachines().define(backEndVMName).withRegion(Region.US_EAST).withExistingResourceGroup(rgName).withExistingPrimaryNetwork(virtualNetwork1).withSubnet(vnet1BackEndSubnetName).withPrimaryPrivateIPAddressDynamic().withoutPrimaryPublicIPAddress().withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS).withRootUsername(userName).withSsh(sshKey).withSize(VirtualMachineSizeTypes.STANDARD_D3_V2).createAsync(), azure.networks().define(vnetName2).withRegion(Region.US_EAST).withNewResourceGroup(rgName).createAsync()).map(new Func1<Indexable, Indexable>() {

            @Override
            public Indexable call(Indexable indexable) {
                Date t2 = new Date();
                long duration = ((t2.getTime() - t1.getTime()) / 1000);
                if (indexable instanceof VirtualMachine) {
                    VirtualMachine vm = (VirtualMachine) indexable;
                    System.out.println("Created Linux VM: (took " + duration + " seconds) " + vm.id());
                    // Print virtual machine details
                    Utils.print(vm);
                } else if (indexable instanceof Network) {
                    Network vn = (Network) indexable;
                    System.out.println("Created a virtual network: took " + duration + " seconds) " + vn.id());
                    // Print the virtual network details
                    Utils.print(vn);
                }
                return indexable;
            }
        });
        //============================================================
        // List virtual networks and print details
        azure.networks().listByResourceGroupAsync(rgName).map(new Func1<Network, Network>() {

            @Override
            public Network call(Network network) {
                Utils.print(network);
                return network;
            }
        }).toBlocking().subscribe();
        return true;
    } catch (Exception e) {
        System.err.println(e.getMessage());
    } 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 : NetworkSecurityGroup(com.microsoft.azure.management.network.NetworkSecurityGroup) TreeMap(java.util.TreeMap) Observable(rx.Observable) Date(java.util.Date) Network(com.microsoft.azure.management.network.Network) Indexable(com.microsoft.azure.management.resources.fluentcore.model.Indexable) VirtualMachine(com.microsoft.azure.management.compute.VirtualMachine)

Example 39 with VirtualMachine

use of com.microsoft.azure.management.compute.VirtualMachine 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 40 with VirtualMachine

use of com.microsoft.azure.management.compute.VirtualMachine 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)

Aggregations

VirtualMachine (com.microsoft.azure.management.compute.VirtualMachine)68 ArrayList (java.util.ArrayList)21 Region (com.microsoft.azure.management.resources.fluentcore.arm.Region)20 Network (com.microsoft.azure.management.network.Network)17 Date (java.util.Date)12 Disk (com.microsoft.azure.management.compute.Disk)10 PublicIPAddress (com.microsoft.azure.management.network.PublicIPAddress)10 ResourceGroup (com.microsoft.azure.management.resources.ResourceGroup)9 Creatable (com.microsoft.azure.management.resources.fluentcore.model.Creatable)9 Azure (com.microsoft.azure.management.Azure)8 NetworkInterface (com.microsoft.azure.management.network.NetworkInterface)8 IOException (java.io.IOException)8 StopWatch (org.apache.commons.lang3.time.StopWatch)7 VirtualMachineDataDisk (com.microsoft.azure.management.compute.VirtualMachineDataDisk)6 HashMap (java.util.HashMap)6 StorageAccount (com.microsoft.azure.management.storage.StorageAccount)5 JSchException (com.jcraft.jsch.JSchException)4 CloudException (com.microsoft.azure.CloudException)4 DockerHost (com.microsoft.azure.docker.model.DockerHost)4 NetworkSecurityGroup (com.microsoft.azure.management.network.NetworkSecurityGroup)4