Search in sources :

Example 6 with VirtualMachine

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

the class CreateVirtualMachineUsingCustomImageFromVM 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 linuxVMName1 = Utils.createRandomName("VM1");
    final String linuxVMName2 = Utils.createRandomName("VM2");
    final String linuxVMName3 = Utils.createRandomName("VM3");
    final String customImageName = Utils.createRandomName("img");
    final String rgName = Utils.createRandomName("rgCOMV");
    final String publicIpDnsLabel = Utils.createRandomName("pip");
    final String userName = "tirekicker";
    final String password = "12NewPA$$w0rd!";
    final Region region = Region.US_WEST_CENTRAL;
    final String apacheInstallScript = "https://raw.githubusercontent.com/Azure/azure-sdk-for-java/master/azure-samples/src/main/resources/install_apache.sh";
    final String apacheInstallCommand = "bash install_apache.sh";
    List<String> apacheInstallScriptUris = new ArrayList<>();
    apacheInstallScriptUris.add(apacheInstallScript);
    try {
        //=============================================================
        // Create a Linux VM using a PIR image with un-managed OS and data disks and customize virtual
        // machine using custom script extension
        System.out.println("Creating a un-managed Linux VM");
        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().defineNewExtension("CustomScriptForLinux").withPublisher("Microsoft.OSTCExtensions").withType("CustomScriptForLinux").withVersion("1.4").withMinorVersionAutoUpgrade().withPublicSetting("fileUris", apacheInstallScriptUris).withPublicSetting("commandToExecute", apacheInstallCommand).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);
        // De-provision the virtual machine
        deprovisionAgentInLinuxVM(linuxVM.getPrimaryPublicIPAddress().fqdn(), 22, userName, password);
        //=============================================================
        // Deallocate the virtual machine
        System.out.println("Deallocate VM: " + linuxVM.id());
        linuxVM.deallocate();
        System.out.println("De-allocated VM: " + linuxVM.id() + "; state = " + linuxVM.powerState());
        //=============================================================
        // Generalize the virtual machine
        System.out.println("Generalize VM: " + linuxVM.id());
        linuxVM.generalize();
        System.out.println("Generalized VM: " + linuxVM.id());
        //=============================================================
        // Capture the virtual machine to get a 'Generalized image' with Apache
        System.out.println("Capturing VM as custom image: " + linuxVM.id());
        VirtualMachineCustomImage virtualMachineCustomImage = azure.virtualMachineCustomImages().define(customImageName).withRegion(region).withExistingResourceGroup(rgName).fromVirtualMachine(linuxVM).create();
        System.out.println("Captured VM: " + linuxVM.id());
        Utils.print(virtualMachineCustomImage);
        //=============================================================
        // Create a Linux VM using custom image
        System.out.println("Creating a Linux VM using custom image - " + virtualMachineCustomImage.id());
        VirtualMachine linuxVM2 = azure.virtualMachines().define(linuxVMName2).withRegion(region).withExistingResourceGroup(rgName).withNewPrimaryNetwork("10.0.0.0/28").withPrimaryPrivateIPAddressDynamic().withoutPrimaryPublicIPAddress().withLinuxCustomImage(virtualMachineCustomImage.id()).withRootUsername(userName).withRootPassword(password).withSize(VirtualMachineSizeTypes.STANDARD_D3_V2).create();
        Utils.print(linuxVM2);
        //=============================================================
        // Create another Linux VM using custom image and configure the data disks from image and
        // add another data disk
        System.out.println("Creating another Linux VM with additional data disks using custom image - " + virtualMachineCustomImage.id());
        VirtualMachine linuxVM3 = azure.virtualMachines().define(linuxVMName3).withRegion(region).withExistingResourceGroup(rgName).withNewPrimaryNetwork("10.0.0.0/28").withPrimaryPrivateIPAddressDynamic().withoutPrimaryPublicIPAddress().withLinuxCustomImage(virtualMachineCustomImage.id()).withRootUsername(userName).withRootPassword(password).withNewDataDiskFromImage(1, 200, // TODO: Naming needs to be finalized
        CachingTypes.READ_WRITE).withNewDataDiskFromImage(2, 100, CachingTypes.READ_ONLY).withNewDataDisk(50).withSize(VirtualMachineSizeTypes.STANDARD_D3_V2).create();
        Utils.print(linuxVM3);
        // Getting the SAS URIs requires virtual machines to be de-allocated
        // [Access not permitted because'disk' is currently attached to running VM]
        //
        System.out.println("De-allocating the virtual machine - " + linuxVM3.id());
        linuxVM3.deallocate();
        //=============================================================
        // Get the readonly SAS URI to the OS and data disks
        System.out.println("Getting OS and data disks SAS Uris");
        // OS Disk SAS Uri
        Disk osDisk = azure.disks().getById(linuxVM3.osDiskId());
        String osDiskSasUri = osDisk.grantAccess(24 * 60);
        System.out.println("OS disk SAS Uri: " + osDiskSasUri);
        // Data disks SAS Uri
        for (VirtualMachineDataDisk disk : linuxVM3.dataDisks().values()) {
            Disk dataDisk = azure.disks().getById(disk.id());
            String dataDiskSasUri = dataDisk.grantAccess(24 * 60);
            System.out.println(String.format("Data disk (lun: %d) SAS Uri: %s", disk.lun(), dataDiskSasUri));
        }
        //=============================================================
        // Deleting the custom image
        System.out.println("Deleting custom Image: " + virtualMachineCustomImage.id());
        azure.virtualMachineCustomImages().deleteById(virtualMachineCustomImage.id());
        System.out.println("Deleted custom image");
        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) VirtualMachineCustomImage(com.microsoft.azure.management.compute.VirtualMachineCustomImage) ArrayList(java.util.ArrayList) Region(com.microsoft.azure.management.resources.fluentcore.arm.Region) 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 7 with VirtualMachine

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

the class ManageVirtualMachine 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 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!";
    try {
        //=============================================================
        // Create a Windows virtual machine
        // Prepare a creatable data disk for VM
        //
        Creatable<Disk> dataDiskCreatable = azure.disks().define(Utils.createRandomName("dsk-")).withRegion(region).withExistingResourceGroup(rgName).withData().withSizeInGB(100);
        // Create a data disk to attach to VM
        //
        Disk dataDisk = azure.disks().define(Utils.createRandomName("dsk-")).withRegion(region).withNewResourceGroup(rgName).withData().withSizeInGB(50).create();
        System.out.println("Creating a Windows VM");
        Date t1 = new Date();
        VirtualMachine windowsVM = 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(dataDisk).withSize(VirtualMachineSizeTypes.STANDARD_D3_V2).create();
        Date t2 = new Date();
        System.out.println("Created VM: (took " + ((t2.getTime() - t1.getTime()) / 1000) + " seconds) " + windowsVM.id());
        // Print virtual machine details
        Utils.print(windowsVM);
        //=============================================================
        // Update - Tag the virtual machine
        windowsVM.update().withTag("who-rocks", "java").withTag("where", "on azure").apply();
        System.out.println("Tagged VM: " + windowsVM.id());
        //=============================================================
        // Update - Add data disk
        windowsVM.update().withNewDataDisk(10).apply();
        System.out.println("Added a data disk to VM" + windowsVM.id());
        Utils.print(windowsVM);
        //=============================================================
        // Update - detach data disk
        windowsVM.update().withoutDataDisk(0).apply();
        System.out.println("Detached data disk at lun 0 from VM " + windowsVM.id());
        //=============================================================
        // Restart the virtual machine
        System.out.println("Restarting VM: " + windowsVM.id());
        windowsVM.restart();
        System.out.println("Restarted VM: " + windowsVM.id() + "; state = " + windowsVM.powerState());
        //=============================================================
        // Stop (powerOff) the virtual machine
        System.out.println("Powering OFF VM: " + windowsVM.id());
        windowsVM.powerOff();
        System.out.println("Powered OFF VM: " + windowsVM.id() + "; state = " + windowsVM.powerState());
        // Get the network where Windows VM is hosted
        Network network = windowsVM.getPrimaryNetworkInterface().primaryIPConfiguration().getNetwork();
        //=============================================================
        // Create a Linux VM in the same virtual network
        System.out.println("Creating a Linux VM in the network");
        VirtualMachine linuxVM = 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).create();
        System.out.println("Created a Linux VM (in the same virtual network): " + linuxVM.id());
        Utils.print(linuxVM);
        //=============================================================
        // List virtual machines in the resource group
        String resourceGroupName = windowsVM.resourceGroupName();
        System.out.println("Printing list of VMs =======");
        for (VirtualMachine virtualMachine : azure.virtualMachines().listByResourceGroup(resourceGroupName)) {
            Utils.print(virtualMachine);
        }
        //=============================================================
        // Delete the virtual machine
        System.out.println("Deleting VM: " + windowsVM.id());
        azure.virtualMachines().deleteById(windowsVM.id());
        System.out.println("Deleted VM: " + windowsVM.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) Disk(com.microsoft.azure.management.compute.Disk) Date(java.util.Date) VirtualMachine(com.microsoft.azure.management.compute.VirtualMachine)

Example 8 with VirtualMachine

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

the class TestResourceStreaming method createResource.

@Override
public VirtualMachine createResource(VirtualMachines virtualMachines) throws Exception {
    final String vmName = "vm" + this.testId;
    System.out.println("In createResource \n\n\n");
    Creatable<ResourceGroup> rgCreatable = virtualMachines.manager().resourceManager().resourceGroups().define(SdkContext.randomResourceName("rg" + vmName, 20)).withRegion(Region.US_EAST);
    Creatable<StorageAccount> storageCreatable = this.storageAccounts.define(SdkContext.randomResourceName("stg", 20)).withRegion(Region.US_EAST).withNewResourceGroup(rgCreatable);
    final AtomicInteger resourceCount = new AtomicInteger(0);
    VirtualMachine virtualMachine = (VirtualMachine) virtualMachines.define(vmName).withRegion(Region.US_EAST).withNewResourceGroup(rgCreatable).withNewPrimaryNetwork("10.0.0.0/28").withPrimaryPrivateIPAddressDynamic().withNewPrimaryPublicIPAddress(SdkContext.randomResourceName("pip", 20)).withPopularWindowsImage(KnownWindowsVirtualMachineImage.WINDOWS_SERVER_2012_R2_DATACENTER).withAdminUsername("testuser").withAdminPassword("12NewPA$$w0rd!").withSize(VirtualMachineSizeTypes.STANDARD_D1_V2).withNewStorageAccount(storageCreatable).withNewAvailabilitySet(SdkContext.randomResourceName("avset", 10)).createAsync().map(new Func1<Indexable, Resource>() {

        @Override
        public Resource call(Indexable resource) {
            resourceCount.incrementAndGet();
            Resource createdResource = (Resource) resource;
            System.out.println("Created :" + createdResource.id());
            return createdResource;
        }
    }).toBlocking().last();
    Assert.assertTrue(resourceCount.get() == 7);
    return virtualMachine;
}
Also used : AtomicInteger(java.util.concurrent.atomic.AtomicInteger) StorageAccount(com.microsoft.azure.management.storage.StorageAccount) Resource(com.microsoft.azure.management.resources.fluentcore.arm.models.Resource) Indexable(com.microsoft.azure.management.resources.fluentcore.model.Indexable) Func1(rx.functions.Func1) ResourceGroup(com.microsoft.azure.management.resources.ResourceGroup) VirtualMachine(com.microsoft.azure.management.compute.VirtualMachine)

Example 9 with VirtualMachine

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

the class TestVirtualMachineInAvailabilitySet method createResource.

@Override
public VirtualMachine createResource(VirtualMachines virtualMachines) throws Exception {
    final String vmName = "vm" + this.testId;
    final String newRgName = SdkContext.randomResourceName("rgVmInAvail", 10);
    final String newAvailSetName = SdkContext.randomResourceName("avai", 10);
    VirtualMachine vm = virtualMachines.define(vmName).withRegion(Region.US_EAST).withNewResourceGroup(newRgName).withNewPrimaryNetwork("10.0.0.0/28").withPrimaryPrivateIPAddressDynamic().withoutPrimaryPublicIPAddress().withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS).withRootUsername("testuser").withRootPassword("12NewPA$$w0rd!").withComputerName("myvm123").withSize(VirtualMachineSizeTypes.STANDARD_D3_V2).withNewAvailabilitySet(newAvailSetName).create();
    Assert.assertNotNull(vm.availabilitySetId());
    Assert.assertNotNull(vm.computerName());
    Assert.assertTrue(vm.computerName().equalsIgnoreCase("myvm123"));
    return vm;
}
Also used : VirtualMachine(com.microsoft.azure.management.compute.VirtualMachine)

Example 10 with VirtualMachine

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

the class ManageIPAddress method runSample.

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

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