Search in sources :

Example 1 with VirtualMachine

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

the class ManageSimpleTrafficManager 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("rgCOPD", 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 int vmCountPerRegion = 2;
    Set<Region> regions = new HashSet<>(Arrays.asList(Region.US_EAST, Region.US_WEST));
    try {
        //=============================================================
        // Create a shared resource group for all the resources so they can all be deleted together
        //
        ResourceGroup resourceGroup = azure.resourceGroups().define(rgName).withRegion(Region.US_EAST).create();
        System.out.println("Created a new resource group - " + resourceGroup.id());
        // Prepare a batch of creatable VM definitions to put behind the traffic manager
        //
        List<Creatable<VirtualMachine>> creatableVirtualMachines = new ArrayList<>();
        for (Region region : regions) {
            String linuxVMNamePrefix = SdkContext.randomResourceName("vm", 15);
            for (int i = 0; i < vmCountPerRegion; i++) {
                //=============================================================
                // Create a virtual machine in its own virtual network
                String vmName = String.format("%s-%d", linuxVMNamePrefix, i);
                Creatable<VirtualMachine> vmDefinition = azure.virtualMachines().define(vmName).withRegion(region).withExistingResourceGroup(resourceGroup).withNewPrimaryNetwork("10.0.0.0/29").withPrimaryPrivateIPAddressDynamic().withNewPrimaryPublicIPAddress(vmName).withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS).withRootUsername(userName).withSsh(sshKey).withSize(VirtualMachineSizeTypes.STANDARD_A1);
                creatableVirtualMachines.add(vmDefinition);
            }
        }
        //=============================================================
        // Create the VMs !!
        StopWatch stopwatch = new StopWatch();
        System.out.println("Creating the virtual machines...");
        stopwatch.start();
        Collection<VirtualMachine> virtualMachines = azure.virtualMachines().create(creatableVirtualMachines).values();
        stopwatch.stop();
        System.out.println(String.format("Created virtual machines in %d seconds.", stopwatch.getTime() / 1000));
        //=============================================================
        // Create 1 traffic manager profile
        //
        String trafficManagerName = SdkContext.randomResourceName("tra", 15);
        TrafficManagerProfile.DefinitionStages.WithEndpoint profileWithEndpoint = azure.trafficManagerProfiles().define(trafficManagerName).withExistingResourceGroup(resourceGroup).withLeafDomainLabel(trafficManagerName).withPerformanceBasedRouting();
        TrafficManagerProfile.DefinitionStages.WithCreate profileWithCreate = null;
        int routingPriority = 1;
        for (VirtualMachine vm : virtualMachines) {
            String endpointName = SdkContext.randomResourceName("ep", 15);
            profileWithCreate = profileWithEndpoint.defineAzureTargetEndpoint(endpointName).toResourceId(vm.getPrimaryPublicIPAddressId()).withRoutingPriority(routingPriority++).attach();
        }
        stopwatch.reset();
        stopwatch.start();
        TrafficManagerProfile trafficManagerProfile = profileWithCreate.create();
        stopwatch.stop();
        System.out.println(String.format("Created a traffic manager profile %s\n in %d seconds.", trafficManagerProfile.id(), stopwatch.getTime() / 1000));
        //=============================================================
        // Modify the traffic manager to use priority based routing
        //
        trafficManagerProfile.update().withPriorityBasedRouting().apply();
        System.out.println("Modified the traffic manager to use priority-based routing.");
        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 : TrafficManagerProfile(com.microsoft.azure.management.trafficmanager.TrafficManagerProfile) ArrayList(java.util.ArrayList) StopWatch(org.apache.commons.lang3.time.StopWatch) Region(com.microsoft.azure.management.resources.fluentcore.arm.Region) Creatable(com.microsoft.azure.management.resources.fluentcore.model.Creatable) ResourceGroup(com.microsoft.azure.management.resources.ResourceGroup) HashSet(java.util.HashSet) VirtualMachine(com.microsoft.azure.management.compute.VirtualMachine)

Example 2 with VirtualMachine

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

the class ManageAvailabilitySet 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 = Utils.createRandomName("rgCOMA");
    final String availSetName1 = Utils.createRandomName("av1");
    final String availSetName2 = Utils.createRandomName("av2");
    final String vm1Name = Utils.createRandomName("vm1");
    final String vm2Name = Utils.createRandomName("vm2");
    final String vnetName = Utils.createRandomName("vnet");
    final String userName = "tirekicker";
    final String password = "12NewPA$$w0rd!";
    try {
        //=============================================================
        // Create an availability set
        System.out.println("Creating an availability set");
        AvailabilitySet availSet1 = azure.availabilitySets().define(availSetName1).withRegion(region).withNewResourceGroup(rgName).withFaultDomainCount(2).withUpdateDomainCount(4).withSku(AvailabilitySetSkuTypes.MANAGED).withTag("cluster", "Windowslinux").withTag("tag1", "tag1val").create();
        System.out.println("Created first availability set: " + availSet1.id());
        Utils.print(availSet1);
        //=============================================================
        // Define a virtual network for the VMs in this availability set
        Creatable<Network> networkDefinition = azure.networks().define(vnetName).withRegion(region).withExistingResourceGroup(rgName).withAddressSpace("10.0.0.0/28");
        //=============================================================
        // Create a Windows VM in the new availability set
        System.out.println("Creating a Windows VM in the availability set");
        VirtualMachine vm1 = azure.virtualMachines().define(vm1Name).withRegion(region).withExistingResourceGroup(rgName).withNewPrimaryNetwork(networkDefinition).withPrimaryPrivateIPAddressDynamic().withoutPrimaryPublicIPAddress().withPopularWindowsImage(KnownWindowsVirtualMachineImage.WINDOWS_SERVER_2012_R2_DATACENTER).withAdminUsername(userName).withAdminPassword(password).withSize(VirtualMachineSizeTypes.STANDARD_D3_V2).withExistingAvailabilitySet(availSet1).create();
        System.out.println("Created first VM:" + vm1.id());
        Utils.print(vm1);
        //=============================================================
        // Create a Linux VM in the same availability set
        System.out.println("Creating a Linux VM in the availability set");
        VirtualMachine vm2 = azure.virtualMachines().define(vm2Name).withRegion(region).withExistingResourceGroup(rgName).withNewPrimaryNetwork(networkDefinition).withPrimaryPrivateIPAddressDynamic().withoutPrimaryPublicIPAddress().withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS).withRootUsername(userName).withRootPassword(password).withSize(VirtualMachineSizeTypes.STANDARD_D3_V2).withExistingAvailabilitySet(availSet1).create();
        System.out.println("Created second VM: " + vm2.id());
        Utils.print(vm2);
        //=============================================================
        // Update - Tag the availability set
        availSet1 = availSet1.update().withTag("server1", "nginx").withTag("server2", "iis").withoutTag("tag1").apply();
        System.out.println("Tagged availability set: " + availSet1.id());
        //=============================================================
        // Create another availability set
        System.out.println("Creating an availability set");
        AvailabilitySet availSet2 = azure.availabilitySets().define(availSetName2).withRegion(region).withExistingResourceGroup(rgName).create();
        System.out.println("Created second availability set: " + availSet2.id());
        Utils.print(availSet2);
        //=============================================================
        // List availability sets
        String resourceGroupName = availSet1.resourceGroupName();
        System.out.println("Printing list of availability sets  =======");
        for (AvailabilitySet availabilitySet : azure.availabilitySets().listByResourceGroup(resourceGroupName)) {
            Utils.print(availabilitySet);
        }
        //=============================================================
        // Delete an availability set
        System.out.println("Deleting an availability set: " + availSet2.id());
        azure.availabilitySets().deleteById(availSet2.id());
        System.out.println("Deleted availability set: " + availSet2.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 (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 : Network(com.microsoft.azure.management.network.Network) Region(com.microsoft.azure.management.resources.fluentcore.arm.Region) AvailabilitySet(com.microsoft.azure.management.compute.AvailabilitySet) VirtualMachine(com.microsoft.azure.management.compute.VirtualMachine)

Example 3 with VirtualMachine

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

the class ManageManagedDisks method prepareSpecializedUnmanagedVirtualMachine.

private static VirtualMachine prepareSpecializedUnmanagedVirtualMachine(Azure azure, Region region, String rgName) {
    final String userName = "tirekicker";
    final String password = "12NewPA$$w0rd!";
    final String linuxVMName1 = SdkContext.randomResourceName("vm" + "-", 10);
    final String publicIpDnsLabel = SdkContext.randomResourceName("pip" + "-", 20);
    VirtualMachine linuxVM = azure.virtualMachines().define(linuxVMName1).withRegion(region).withNewResourceGroup(rgName).withNewPrimaryNetwork("10.0.0.0/28").withPrimaryPrivateIPAddressDynamic().withNewPrimaryPublicIPAddress(publicIpDnsLabel).withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS).withRootUsername(userName).withRootPassword(password).withUnmanagedDisks().defineUnmanagedDataDisk("disk-1").withNewVhd(100).withLun(1).attach().defineUnmanagedDataDisk("disk-2").withNewVhd(50).withLun(2).attach().withSize(VirtualMachineSizeTypes.STANDARD_D3_V2).create();
    // De-provision the virtual machine
    deprovisionAgentInLinuxVM(linuxVM.getPrimaryPublicIPAddress().fqdn(), 22, userName, password);
    System.out.println("Deallocate VM: " + linuxVM.id());
    linuxVM.deallocate();
    System.out.println("Deallocated VM: " + linuxVM.id() + "; state = " + linuxVM.powerState());
    System.out.println("Generalize VM: " + linuxVM.id());
    linuxVM.generalize();
    System.out.println("Generalized VM: " + linuxVM.id());
    return linuxVM;
}
Also used : VirtualMachine(com.microsoft.azure.management.compute.VirtualMachine)

Example 4 with VirtualMachine

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

the class ManageManagedDisks 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_EAST;
    final String rgName = Utils.createRandomName("rgCOMV");
    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 VM
        // Create a virtual machine with an implicit Managed OS disk and explicit Managed data disk
        System.out.println("Creating VM [with an implicit Managed OS disk and explicit Managed data disk]");
        final String linuxVM1Name = SdkContext.randomResourceName("vm" + "-", 18);
        final String linuxVM1Pip = SdkContext.randomResourceName("pip" + "-", 18);
        VirtualMachine linuxVM1 = azure.virtualMachines().define(linuxVM1Name).withRegion(region).withNewResourceGroup(rgName).withNewPrimaryNetwork("10.0.0.0/28").withPrimaryPrivateIPAddressDynamic().withNewPrimaryPublicIPAddress(linuxVM1Pip).withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS).withRootUsername(userName).withSsh(sshkey).withNewDataDisk(100).withSize(VirtualMachineSizeTypes.STANDARD_D3_V2).create();
        System.out.println("Created VM [with an implicit Managed OS disk and explicit Managed data disk]");
        // Creation is simplified with implicit creation of managed disks without specifying all the disk details. You will notice that you do not require storage accounts
        // ::== Update the VM
        // Create a VMSS with implicit managed OS disks and explicit managed data disks
        System.out.println("Creating VMSS [with implicit managed OS disks and explicit managed data disks]");
        final String vmScaleSetName = SdkContext.randomResourceName("vmss" + "-", 18);
        VirtualMachineScaleSet vmScaleSet = azure.virtualMachineScaleSets().define(vmScaleSetName).withRegion(region).withExistingResourceGroup(rgName).withSku(VirtualMachineScaleSetSkuTypes.STANDARD_D5_V2).withExistingPrimaryNetworkSubnet(prepareNetwork(azure, region, rgName), "subnet1").withExistingPrimaryInternetFacingLoadBalancer(prepareLoadBalancer(azure, region, rgName)).withoutPrimaryInternalLoadBalancer().withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS).withRootUsername("tirekicker").withSsh(sshkey).withNewDataDisk(100).withNewDataDisk(100, 1, CachingTypes.READ_WRITE).withNewDataDisk(100, 2, CachingTypes.READ_ONLY).withCapacity(3).create();
        System.out.println("Created VMSS [with implicit managed OS disks and explicit managed data disks]");
        // Create an empty disk and attach to a VM (Manage Virtual Machine With Disk)
        System.out.println("Creating empty data disk [to attach to a VM]");
        final String diskName = SdkContext.randomResourceName("dsk" + "-", 18);
        Disk dataDisk = azure.disks().define(diskName).withRegion(region).withExistingResourceGroup(rgName).withData().withSizeInGB(50).create();
        System.out.println("Created empty data disk [to attach to a VM]");
        System.out.println("Creating VM [with new managed data disks and disk attached]");
        final String linuxVM2Name = SdkContext.randomResourceName("vm" + "-", 10);
        final String linuxVM2Pip = SdkContext.randomResourceName("pip" + "-", 18);
        VirtualMachine linuxVM2 = azure.virtualMachines().define(linuxVM2Name).withRegion(region).withExistingResourceGroup(rgName).withNewPrimaryNetwork("10.0.0.0/28").withPrimaryPrivateIPAddressDynamic().withNewPrimaryPublicIPAddress(linuxVM2Pip).withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS).withRootUsername(userName).withSsh(sshkey).withNewDataDisk(100).withNewDataDisk(100, 1, CachingTypes.READ_WRITE).withExistingDataDisk(dataDisk).withSize(VirtualMachineSizeTypes.STANDARD_D3_V2).create();
        System.out.println("Created VM [with new managed data disks and disk attached]");
        // Update a VM
        System.out.println("Updating VM [by detaching a disk and adding empty disk]");
        linuxVM2.update().withoutDataDisk(2).withNewDataDisk(200).apply();
        System.out.println("Updated VM [by detaching a disk and adding empty disk]");
        // Create a VM from an image (Create Virtual Machine Using Custom Image from VM)
        System.out.println("Preparing specialized virtual machine with un-managed disk");
        final VirtualMachine linuxVM = prepareSpecializedUnmanagedVirtualMachine(azure, region, rgName);
        System.out.println("Prepared specialized virtual machine with un-managed disk");
        System.out.println("Creating custom image from specialized virtual machine");
        final String customImageName = SdkContext.randomResourceName("cimg" + "-", 10);
        VirtualMachineCustomImage virtualMachineCustomImage = azure.virtualMachineCustomImages().define(customImageName).withRegion(region).withExistingResourceGroup(rgName).fromVirtualMachine(// from a deallocated and generalized VM
        linuxVM).create();
        System.out.println("Created custom image from specialized virtual machine");
        System.out.println("Creating VM [from custom image]");
        final String linuxVM3Name = SdkContext.randomResourceName("vm" + "-", 10);
        VirtualMachine linuxVM3 = azure.virtualMachines().define(linuxVM3Name).withRegion(region).withExistingResourceGroup(rgName).withNewPrimaryNetwork("10.0.0.0/28").withPrimaryPrivateIPAddressDynamic().withoutPrimaryPublicIPAddress().withLinuxCustomImage(virtualMachineCustomImage.id()).withRootUsername(userName).withSsh(sshkey).withSize(VirtualMachineSizeTypes.STANDARD_D3_V2).create();
        System.out.println("Created VM [from custom image]");
        // Create a VM from a VHD (Create Virtual Machine Using Specialized VHD)
        final String linuxVMName4 = SdkContext.randomResourceName("vm" + "-", 10);
        final String specializedVhd = linuxVM.osUnmanagedDiskVhdUri();
        azure.virtualMachines().deleteById(linuxVM.id());
        System.out.println("Creating VM [by attaching un-managed disk]");
        VirtualMachine linuxVM4 = azure.virtualMachines().define(linuxVMName4).withRegion(region).withExistingResourceGroup(rgName).withNewPrimaryNetwork("10.0.0.0/28").withPrimaryPrivateIPAddressDynamic().withoutPrimaryPublicIPAddress().withSpecializedOSUnmanagedDisk(specializedVhd, OperatingSystemTypes.LINUX).withSize(VirtualMachineSizeTypes.STANDARD_D3_V2).create();
        System.out.println("Created VM [by attaching un-managed disk]");
        // Create a Snapshot (Create Virtual Machine using specialized disks from snapshot)
        System.out.println("Preparing specialized virtual machine with managed disks");
        final VirtualMachine linuxVM5 = prepareSpecializedManagedVirtualMachine(azure, region, rgName);
        Disk osDisk = azure.disks().getById(linuxVM5.osDiskId());
        List<Disk> dataDisks = new ArrayList<>();
        for (VirtualMachineDataDisk disk : linuxVM5.dataDisks().values()) {
            Disk d = azure.disks().getById(disk.id());
            dataDisks.add(d);
        }
        System.out.println("Prepared specialized virtual machine with managed disks");
        System.out.println("Deleting VM: " + linuxVM5.id());
        azure.virtualMachines().deleteById(linuxVM5.id());
        System.out.println("Deleted the VM: " + linuxVM5.id());
        System.out.println("Creating snapshot [from managed OS disk]");
        // Create a managed snapshot for an OS disk
        final String managedOSSnapshotName = SdkContext.randomResourceName("snp" + "-", 10);
        Snapshot osSnapshot = azure.snapshots().define(managedOSSnapshotName).withRegion(region).withExistingResourceGroup(rgName).withLinuxFromDisk(osDisk).create();
        System.out.println("Created snapshot [from managed OS disk]");
        System.out.println("Creating managed OS disk [from snapshot]");
        // Create a managed disk from the managed snapshot for the OS disk
        final String managedNewOSDiskName = SdkContext.randomResourceName("dsk" + "-", 10);
        Disk newOSDisk = azure.disks().define(managedNewOSDiskName).withRegion(region).withExistingResourceGroup(rgName).withLinuxFromSnapshot(osSnapshot).withSizeInGB(100).create();
        System.out.println("Created managed OS disk [from snapshot]");
        System.out.println("Creating managed data snapshot [from managed data disk]");
        // Create a managed snapshot for a data disk
        final String managedDataDiskSnapshotName = SdkContext.randomResourceName("dsk" + "-", 10);
        Snapshot dataSnapshot = azure.snapshots().define(managedDataDiskSnapshotName).withRegion(region).withExistingResourceGroup(rgName).withDataFromDisk(dataDisks.get(0)).withSku(DiskSkuTypes.STANDARD_LRS).create();
        System.out.println("Created managed data snapshot [from managed data disk]");
        System.out.println("Creating managed data disk [from managed snapshot]");
        // Create a managed disk from the managed snapshot for the data disk
        final String managedNewDataDiskName = SdkContext.randomResourceName("dsk" + "-", 10);
        Disk newDataDisk = azure.disks().define(managedNewDataDiskName).withRegion(region).withExistingResourceGroup(rgName).withData().fromSnapshot(dataSnapshot).create();
        System.out.println("Created managed data disk [from managed snapshot]");
        System.out.println("Creating VM [with specialized OS managed disk]");
        final String linuxVM6Name = SdkContext.randomResourceName("vm" + "-", 10);
        VirtualMachine linuxVM6 = azure.virtualMachines().define(linuxVM6Name).withRegion(region).withExistingResourceGroup(rgName).withNewPrimaryNetwork("10.0.0.0/28").withPrimaryPrivateIPAddressDynamic().withoutPrimaryPublicIPAddress().withSpecializedOSDisk(newOSDisk, OperatingSystemTypes.LINUX).withExistingDataDisk(newDataDisk).withSize(VirtualMachineSizeTypes.STANDARD_D3_V2).create();
        System.out.println("Created VM [with specialized OS managed disk]");
        // ::== Migrate a VM to managed disks with a single reboot
        System.out.println("Creating VM [with un-managed disk for migration]");
        final String linuxVM7Name = SdkContext.randomResourceName("vm" + "-", 10);
        final String linuxVM7Pip = SdkContext.randomResourceName("pip" + "-", 18);
        VirtualMachine linuxVM7 = azure.virtualMachines().define(linuxVM7Name).withRegion(region).withNewResourceGroup(rgName).withNewPrimaryNetwork("10.0.0.0/28").withPrimaryPrivateIPAddressDynamic().withNewPrimaryPublicIPAddress(linuxVM7Pip).withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS).withRootUsername("tirekicker").withSsh(sshkey).withUnmanagedDisks().withNewUnmanagedDataDisk(100).withSize(VirtualMachineSizeTypes.STANDARD_D3_V2).create();
        System.out.println("Created VM [with un-managed disk for migration]");
        System.out.println("De-allocating VM :" + linuxVM7.id());
        linuxVM7.deallocate();
        System.out.println("De-allocated VM :" + linuxVM7.id());
        System.out.println("Migrating VM");
        linuxVM7.convertToManaged();
        System.out.println("Migrated VM");
        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 : VirtualMachineDataDisk(com.microsoft.azure.management.compute.VirtualMachineDataDisk) Snapshot(com.microsoft.azure.management.compute.Snapshot) VirtualMachineCustomImage(com.microsoft.azure.management.compute.VirtualMachineCustomImage) ArrayList(java.util.ArrayList) Region(com.microsoft.azure.management.resources.fluentcore.arm.Region) VirtualMachineScaleSet(com.microsoft.azure.management.compute.VirtualMachineScaleSet) VirtualMachineDataDisk(com.microsoft.azure.management.compute.VirtualMachineDataDisk) Disk(com.microsoft.azure.management.compute.Disk) IOException(java.io.IOException) JSchException(com.jcraft.jsch.JSchException) VirtualMachine(com.microsoft.azure.management.compute.VirtualMachine)

Example 5 with VirtualMachine

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

the class ConvertVirtualMachineToManagedDisks 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 linuxVMName = Utils.createRandomName("VM1");
    final String rgName = Utils.createRandomName("rgCOMV");
    final String userName = "tirekicker";
    final String password = "12NewPA$$w0rd!";
    final Region region = Region.US_WEST_CENTRAL;
    try {
        //=============================================================
        // Create a Linux VM using a PIR image with un-managed OS and data disks
        System.out.println("Creating an un-managed Linux VM");
        VirtualMachine linuxVM = azure.virtualMachines().define(linuxVMName).withRegion(region).withNewResourceGroup(rgName).withNewPrimaryNetwork("10.0.0.0/28").withPrimaryPrivateIPAddressDynamic().withoutPrimaryPublicIPAddress().withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS).withRootUsername(userName).withRootPassword(password).withUnmanagedDisks().defineUnmanagedDataDisk("disk-1").withNewVhd(100).withLun(1).attach().defineUnmanagedDataDisk("disk-2").withNewVhd(50).withLun(2).attach().withSize(VirtualMachineSizeTypes.STANDARD_D3_V2).create();
        System.out.println("Created a Linux VM with un-managed OS and data disks: " + linuxVM.id());
        Utils.print(linuxVM);
        //=============================================================
        // Deallocate the virtual machine
        System.out.println("Deallocate VM: " + linuxVM.id());
        linuxVM.deallocate();
        System.out.println("De-allocated VM: " + linuxVM.id() + "; state = " + linuxVM.powerState());
        //=============================================================
        // Migrate the virtual machine
        System.out.println("Migrate VM: " + linuxVM.id());
        linuxVM.convertToManaged();
        System.out.println("Migrated VM: " + linuxVM.id());
        Utils.print(linuxVM);
        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 : Region(com.microsoft.azure.management.resources.fluentcore.arm.Region) 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