Search in sources :

Example 36 with ResourceGroup

use of com.microsoft.azure.management.resources.ResourceGroup in project azure-sdk-for-java by Azure.

the class VirtualMachineOperationsTests method canDeleteRelatedResourcesFromFailedParallelVMCreations.

@Test
@Ignore("Can't be played from recording for some reason...")
public void canDeleteRelatedResourcesFromFailedParallelVMCreations() {
    final int desiredVMCount = 40;
    final Region region = Region.US_EAST;
    final String resourceGroupName = RG_NAME;
    // Create one resource group for everything, to ensure no reliance on resource groups
    ResourceGroup resourceGroup = resourceManager.resourceGroups().define(resourceGroupName).withRegion(region).create();
    // Needed for tracking related resources
    final Map<String, Collection<Creatable<? extends Resource>>> vmNonNicResourceDefinitions = new HashMap<>();
    // Tracking NICs separately because they have to be deleted first
    final Map<String, Creatable<NetworkInterface>> nicDefinitions = new HashMap<>();
    final Map<String, Creatable<VirtualMachine>> vmDefinitions = new HashMap<>();
    final Map<String, String> createdResourceIds = new HashMap<>();
    final List<Throwable> errors = new ArrayList<>();
    // Prepare a number of VM definitions along with their related resource definitions
    for (int i = 0; i < desiredVMCount; i++) {
        Collection<Creatable<? extends Resource>> relatedDefinitions = new ArrayList<>();
        // Define a network for each VM
        String networkName = SdkContext.randomResourceName("net", 14);
        Creatable<Network> networkDefinition = networkManager.networks().define(networkName).withRegion(region).withExistingResourceGroup(resourceGroup).withAddressSpace("10.0." + i + ".0/29");
        relatedDefinitions.add(networkDefinition);
        // Define a PIP for each VM
        String pipName = SdkContext.randomResourceName("pip", 14);
        PublicIPAddress.DefinitionStages.WithCreate pipDefinition = this.networkManager.publicIPAddresses().define(pipName).withRegion(region).withExistingResourceGroup(resourceGroup);
        relatedDefinitions.add(pipDefinition);
        // Define a NIC for each VM
        String nicName = SdkContext.randomResourceName("nic", 14);
        Creatable<NetworkInterface> nicDefinition = networkManager.networkInterfaces().define(nicName).withRegion(region).withExistingResourceGroup(resourceGroup).withNewPrimaryNetwork(networkDefinition).withPrimaryPrivateIPAddressDynamic().withNewPrimaryPublicIPAddress(pipDefinition);
        // Define a storage account for each VM
        String storageAccountName = SdkContext.randomResourceName("st", 14);
        Creatable<StorageAccount> storageAccountDefinition = storageManager.storageAccounts().define(storageAccountName).withRegion(region).withExistingResourceGroup(resourceGroup);
        relatedDefinitions.add(storageAccountDefinition);
        // Define an availability set for each VM
        String availabilitySetName = SdkContext.randomResourceName("as", 14);
        Creatable<AvailabilitySet> availabilitySetDefinition = computeManager.availabilitySets().define(availabilitySetName).withRegion(region).withExistingResourceGroup(resourceGroup);
        relatedDefinitions.add(availabilitySetDefinition);
        String vmName = SdkContext.randomResourceName("vm", 14);
        // Define a VM
        String userName;
        if (i == desiredVMCount / 2) {
            // Intentionally cause a failure in one of the VMs
            userName = "";
        } else {
            userName = "tester";
        }
        Creatable<VirtualMachine> vmDefinition = computeManager.virtualMachines().define(vmName).withRegion(region).withExistingResourceGroup(resourceGroup).withNewPrimaryNetworkInterface(nicDefinition).withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS).withRootUsername(userName).withRootPassword("Abcdef.123456!").withNewStorageAccount(storageAccountDefinition).withSize(VirtualMachineSizeTypes.STANDARD_DS1_V2).withNewAvailabilitySet(availabilitySetDefinition);
        // Keep track of all the related resource definitions based on the VM definition
        vmNonNicResourceDefinitions.put(vmDefinition.key(), relatedDefinitions);
        nicDefinitions.put(vmDefinition.key(), nicDefinition);
        vmDefinitions.put(vmDefinition.key(), vmDefinition);
    }
    // Start the parallel creation of everything
    computeManager.virtualMachines().createAsync(new ArrayList<>(vmDefinitions.values())).map(new Func1<Indexable, Indexable>() {

        @Override
        public Indexable call(Indexable createdResource) {
            if (createdResource instanceof Resource) {
                Resource resource = (Resource) createdResource;
                System.out.println("Created: " + resource.id());
                if (resource instanceof VirtualMachine) {
                    VirtualMachine virtualMachine = (VirtualMachine) resource;
                    // Record that this VM was created successfully
                    vmDefinitions.remove(virtualMachine.key());
                    // Remove the associated resources from cleanup list
                    vmNonNicResourceDefinitions.remove(virtualMachine.key());
                    // Remove the associated NIC from cleanup list
                    nicDefinitions.remove(virtualMachine.key());
                } else {
                    // Add this related resource to potential cleanup list
                    createdResourceIds.put(resource.key(), resource.id());
                }
            }
            return createdResource;
        }
    }).onErrorReturn(new Func1<Throwable, Indexable>() {

        @Override
        public Indexable call(Throwable throwable) {
            errors.add(throwable);
            return null;
        }
    }).toBlocking().last();
    // Delete remaining successfully created NICs of failed VM creations
    Collection<String> nicIdsToDelete = new ArrayList<>();
    for (Creatable<NetworkInterface> nicDefinition : nicDefinitions.values()) {
        String nicId = createdResourceIds.get(nicDefinition.key());
        if (nicId != null) {
            nicIdsToDelete.add(nicId);
        }
    }
    if (!nicIdsToDelete.isEmpty()) {
        networkManager.networkInterfaces().deleteByIds(nicIdsToDelete);
    }
    // Delete remaining successfully created resources of failed VM creations
    Collection<Completable> deleteObservables = new ArrayList<>();
    for (Collection<Creatable<? extends Resource>> relatedResources : vmNonNicResourceDefinitions.values()) {
        for (Creatable<? extends Resource> resource : relatedResources) {
            String createdResourceId = createdResourceIds.get(resource.key());
            if (createdResourceId != null) {
                deleteObservables.add(resourceManager.genericResources().deleteByIdAsync(createdResourceId));
            }
        }
    }
    // Delete as much as possible, postponing the errors till the end
    Completable.mergeDelayError(deleteObservables).await();
    // Show any errors
    for (Throwable error : errors) {
        System.out.println("\n### ERROR ###\n");
        if (error instanceof CloudException) {
            CloudException ce = (CloudException) error;
            System.out.println("CLOUD EXCEPTION: " + ce.getMessage());
        } else {
            error.printStackTrace();
        }
    }
    System.out.println("Number of failed/cleaned up VM creations: " + vmNonNicResourceDefinitions.size());
    // Verifications
    final int successfulVMCount = desiredVMCount - vmNonNicResourceDefinitions.size();
    final int actualVMCount = computeManager.virtualMachines().listByResourceGroup(resourceGroupName).size();
    System.out.println("Number of actual successful VMs: " + actualVMCount);
    Assert.assertEquals(successfulVMCount, actualVMCount);
    final int actualNicCount = networkManager.networkInterfaces().listByResourceGroup(resourceGroupName).size();
    Assert.assertEquals(successfulVMCount, actualNicCount);
    final int actualNetworkCount = networkManager.networks().listByResourceGroup(resourceGroupName).size();
    Assert.assertEquals(successfulVMCount, actualNetworkCount);
    final int actualPipCount = networkManager.publicIPAddresses().listByResourceGroup(resourceGroupName).size();
    Assert.assertEquals(successfulVMCount, actualPipCount);
    final int actualAvailabilitySetCount = computeManager.availabilitySets().listByResourceGroup(resourceGroupName).size();
    Assert.assertEquals(successfulVMCount, actualAvailabilitySetCount);
    final int actualStorageAccountCount = storageManager.storageAccounts().listByResourceGroup(resourceGroupName).size();
    Assert.assertEquals(successfulVMCount, actualStorageAccountCount);
    // Verify that at least one VM failed.
    // TODO: Ideally only one, but today the internal RX logic terminates eagerly -- need to change that for parallel creation to terminate more "lazily" in the future
    Assert.assertTrue(successfulVMCount < desiredVMCount);
}
Also used : Completable(rx.Completable) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) Network(com.microsoft.azure.management.network.Network) Creatable(com.microsoft.azure.management.resources.fluentcore.model.Creatable) Indexable(com.microsoft.azure.management.resources.fluentcore.model.Indexable) Func1(rx.functions.Func1) ResourceGroup(com.microsoft.azure.management.resources.ResourceGroup) Resource(com.microsoft.azure.management.resources.fluentcore.arm.models.Resource) NetworkInterface(com.microsoft.azure.management.network.NetworkInterface) CloudException(com.microsoft.azure.CloudException) StorageAccount(com.microsoft.azure.management.storage.StorageAccount) Region(com.microsoft.azure.management.resources.fluentcore.arm.Region) Collection(java.util.Collection) Ignore(org.junit.Ignore) Test(org.junit.Test)

Example 37 with ResourceGroup

use of com.microsoft.azure.management.resources.ResourceGroup in project azure-sdk-for-java by Azure.

the class VirtualMachineManagedDiskOperationsTests method canCreateVirtualMachineFromCustomImageWithManagedDisks.

@Test
public void canCreateVirtualMachineFromCustomImageWithManagedDisks() {
    final String publicIpDnsLabel = generateRandomResourceName("pip", 20);
    final String uname = "juser";
    final String password = "123tEst!@|ac";
    // Create with implicit + explicit empty disks, check default and override
    //
    final String vmName1 = "myvm1";
    final String explicitlyCreatedEmptyDiskName1 = generateRandomResourceName(vmName1 + "_mdisk_", 25);
    final String explicitlyCreatedEmptyDiskName2 = generateRandomResourceName(vmName1 + "_mdisk_", 25);
    final String explicitlyCreatedEmptyDiskName3 = generateRandomResourceName(vmName1 + "_mdisk_", 25);
    ResourceGroup resourceGroup = resourceManager.resourceGroups().define(RG_NAME).withRegion(region).create();
    Creatable<Disk> creatableEmptyDisk1 = computeManager.disks().define(explicitlyCreatedEmptyDiskName1).withRegion(region).withExistingResourceGroup(resourceGroup).withData().withSizeInGB(150);
    Creatable<Disk> creatableEmptyDisk2 = computeManager.disks().define(explicitlyCreatedEmptyDiskName2).withRegion(region).withExistingResourceGroup(resourceGroup).withData().withSizeInGB(150);
    Creatable<Disk> creatableEmptyDisk3 = computeManager.disks().define(explicitlyCreatedEmptyDiskName3).withRegion(region).withExistingResourceGroup(resourceGroup).withData().withSizeInGB(150);
    VirtualMachine virtualMachine1 = computeManager.virtualMachines().define(vmName1).withRegion(region).withExistingResourceGroup(resourceGroup).withNewPrimaryNetwork("10.0.0.0/28").withPrimaryPrivateIPAddressDynamic().withNewPrimaryPublicIPAddress(publicIpDnsLabel).withPopularLinuxImage(linuxImage).withRootUsername(uname).withRootPassword(password).withNewDataDisk(// CreateOption: EMPTY
    100).withNewDataDisk(100, 1, // CreateOption: EMPTY
    CachingTypes.READ_ONLY).withNewDataDisk(// CreateOption: ATTACH
    creatableEmptyDisk1).withNewDataDisk(creatableEmptyDisk2, 2, // CreateOption: ATTACH
    CachingTypes.NONE).withNewDataDisk(creatableEmptyDisk3, 3, // CreateOption: ATTACH
    CachingTypes.NONE).withSize(VirtualMachineSizeTypes.STANDARD_D5_V2).withOSDiskCaching(CachingTypes.READ_WRITE).create();
    System.out.println("Waiting for some time before de-provision");
    // Wait for some time to ensure vm is publicly accessible
    sleep(60 * 1000);
    deprovisionAgentInLinuxVM(virtualMachine1.getPrimaryPublicIPAddress().fqdn(), 22, uname, password);
    virtualMachine1.deallocate();
    virtualMachine1.generalize();
    final String customImageName = generateRandomResourceName("img-", 10);
    VirtualMachineCustomImage customImage = computeManager.virtualMachineCustomImages().define(customImageName).withRegion(region).withExistingResourceGroup(resourceGroup).fromVirtualMachine(virtualMachine1).create();
    Assert.assertNotNull(customImage);
    Assert.assertNotNull(customImage.sourceVirtualMachineId());
    Assert.assertTrue(customImage.sourceVirtualMachineId().equalsIgnoreCase(virtualMachine1.id().toLowerCase()));
    Assert.assertNotNull(customImage.osDiskImage());
    Assert.assertEquals(customImage.osDiskImage().osState(), OperatingSystemStateTypes.GENERALIZED);
    Assert.assertEquals(customImage.osDiskImage().osType(), OperatingSystemTypes.LINUX);
    Assert.assertNotNull(customImage.dataDiskImages());
    Assert.assertEquals(customImage.dataDiskImages().size(), 5);
    for (ImageDataDisk imageDataDisk : customImage.dataDiskImages().values()) {
        Assert.assertNull(imageDataDisk.blobUri());
        Assert.assertNotNull(imageDataDisk.managedDisk().id());
    }
    // Create virtual machine from the custom image
    // This one relies on CRP's capability to create implicit data disks from the virtual machine
    // image data disk images.
    //
    final String vmName2 = "myvm2";
    VirtualMachine virtualMachine2 = computeManager.virtualMachines().define(vmName2).withRegion(region).withExistingResourceGroup(resourceGroup).withNewPrimaryNetwork("10.0.0.0/28").withPrimaryPrivateIPAddressDynamic().withoutPrimaryPublicIPAddress().withLinuxCustomImage(customImage.id()).withRootUsername(uname).withRootPassword(password).withSize(VirtualMachineSizeTypes.STANDARD_D5_V2).withOSDiskCaching(CachingTypes.READ_WRITE).create();
    Map<Integer, VirtualMachineDataDisk> dataDisks = virtualMachine2.dataDisks();
    Assert.assertNotNull(dataDisks);
    Assert.assertEquals(dataDisks.size(), customImage.dataDiskImages().size());
    for (ImageDataDisk imageDataDisk : customImage.dataDiskImages().values()) {
        Assert.assertTrue(dataDisks.containsKey(imageDataDisk.lun()));
        VirtualMachineDataDisk dataDisk = dataDisks.get(imageDataDisk.lun());
        Assert.assertEquals(dataDisk.cachingType(), imageDataDisk.caching());
    // Fails due to CRP bug: Managed disk size is not returned on gets.
    // Assert.assertEquals(dataDisk.size(), (long) imageDataDisk.diskSizeGB());
    }
    // Create virtual machine from the custom image
    // This one override the size and caching type of data disks from data disk images and
    // adds one additional disk
    //
    final String vmName3 = "myvm3";
    VirtualMachine.DefinitionStages.WithManagedCreate creatableVirtualMachine3 = computeManager.virtualMachines().define(vmName3).withRegion(region).withExistingResourceGroup(resourceGroup).withNewPrimaryNetwork("10.0.0.0/28").withPrimaryPrivateIPAddressDynamic().withoutPrimaryPublicIPAddress().withLinuxCustomImage(customImage.id()).withRootUsername(uname).withRootPassword(password);
    for (ImageDataDisk dataDiskImage : customImage.dataDiskImages().values()) {
        // Explicitly override the properties of the data disks created from disk image
        //
        // CreateOption: FROM_IMAGE
        VirtualMachineDataDisk dataDisk = dataDisks.get(dataDiskImage.lun());
        creatableVirtualMachine3.withNewDataDiskFromImage(dataDiskImage.lun(), // increase size by 10 GB
        dataDisk.size() + 10, CachingTypes.READ_ONLY);
    }
    VirtualMachine virtualMachine3 = creatableVirtualMachine3.withNewDataDisk(// CreateOption: EMPTY
    200).withSize(VirtualMachineSizeTypes.STANDARD_D5_V2).withOSDiskCaching(CachingTypes.READ_WRITE).create();
    dataDisks = virtualMachine3.dataDisks();
    Assert.assertNotNull(dataDisks);
    Assert.assertEquals(dataDisks.size(), customImage.dataDiskImages().size() + 1);
    for (ImageDataDisk imageDataDisk : customImage.dataDiskImages().values()) {
        Assert.assertTrue(dataDisks.containsKey(imageDataDisk.lun()));
        VirtualMachineDataDisk dataDisk = dataDisks.get(imageDataDisk.lun());
        Assert.assertEquals(dataDisk.cachingType(), CachingTypes.READ_ONLY);
    // Fails due to CRP bug: Managed disk size is not returned on gets.
    // Assert.assertEquals(dataDisk.size(), (long) imageDataDisk.diskSizeGB() + 10);
    }
}
Also used : ResourceGroup(com.microsoft.azure.management.resources.ResourceGroup) Test(org.junit.Test)

Example 38 with ResourceGroup

use of com.microsoft.azure.management.resources.ResourceGroup in project azure-sdk-for-java by Azure.

the class ManagedDiskOperationsTests method canOperateOnEmptyManagedDisk.

@Test
public void canOperateOnEmptyManagedDisk() {
    final String diskName = generateRandomResourceName("md-empty-", 20);
    final DiskSkuTypes updateTo = DiskSkuTypes.STANDARD_LRS;
    ResourceGroup resourceGroup = resourceManager.resourceGroups().define(RG_NAME).withRegion(region).create();
    // Create an empty managed disk
    //
    Disk disk = computeManager.disks().define(diskName).withRegion(region).withExistingResourceGroup(resourceGroup.name()).withData().withSizeInGB(100).withSku(DiskSkuTypes.STANDARD_LRS).withTag("tkey1", "tval1").create();
    Assert.assertNotNull(disk.id());
    Assert.assertTrue(disk.name().equalsIgnoreCase(diskName));
    Assert.assertEquals(disk.sku(), DiskSkuTypes.STANDARD_LRS);
    Assert.assertEquals(disk.creationMethod(), DiskCreateOption.EMPTY);
    Assert.assertFalse(disk.isAttachedToVirtualMachine());
    Assert.assertEquals(disk.sizeInGB(), 100);
    Assert.assertNull(disk.osType());
    Assert.assertNotNull(disk.source());
    Assert.assertEquals(disk.source().type(), CreationSourceType.EMPTY);
    Assert.assertNull(disk.source().sourceId());
    // Resize and change storage account type
    //
    disk = disk.update().withSku(updateTo).withSizeInGB(200).apply();
    Assert.assertEquals(disk.sku(), updateTo);
    Assert.assertEquals(disk.sizeInGB(), 200);
    disk = computeManager.disks().getByResourceGroup(disk.resourceGroupName(), disk.name());
    Assert.assertNotNull(disk);
    PagedList<Disk> myDisks = computeManager.disks().listByResourceGroup(disk.resourceGroupName());
    Assert.assertNotNull(myDisks);
    Assert.assertTrue(myDisks.size() > 0);
    String sasUrl = disk.grantAccess(100);
    Assert.assertTrue(sasUrl != null && sasUrl != "");
    // Requires access to be revoked before deleting the disk
    //
    disk.revokeAccess();
    computeManager.disks().deleteById(disk.id());
}
Also used : ResourceGroup(com.microsoft.azure.management.resources.ResourceGroup) Test(org.junit.Test)

Example 39 with ResourceGroup

use of com.microsoft.azure.management.resources.ResourceGroup in project azure-sdk-for-java by Azure.

the class ManagedDiskOperationsTests method canOperateOnManagedDiskFromSnapshot.

@Test
public void canOperateOnManagedDiskFromSnapshot() {
    final String emptyDiskName = generateRandomResourceName("md-empty-", 20);
    final String snapshotBasedDiskName = generateRandomResourceName("md-snp-", 20);
    final String snapshotName = generateRandomResourceName("snp-", 20);
    ResourceGroup resourceGroup = resourceManager.resourceGroups().define(RG_NAME).withRegion(region).create();
    Disk emptyDisk = computeManager.disks().define(emptyDiskName).withRegion(region).withExistingResourceGroup(resourceGroup).withData().withSizeInGB(100).create();
    Snapshot snapshot = computeManager.snapshots().define(snapshotName).withRegion(region).withExistingResourceGroup(resourceGroup).withDataFromDisk(emptyDisk).withSizeInGB(200).withSku(DiskSkuTypes.STANDARD_LRS).create();
    Assert.assertNotNull(snapshot.id());
    Assert.assertTrue(snapshot.name().equalsIgnoreCase(snapshotName));
    Assert.assertEquals(snapshot.sku(), DiskSkuTypes.STANDARD_LRS);
    Assert.assertEquals(snapshot.creationMethod(), DiskCreateOption.COPY);
    Assert.assertEquals(snapshot.sizeInGB(), 200);
    Assert.assertNull(snapshot.osType());
    Assert.assertNotNull(snapshot.source());
    Assert.assertEquals(snapshot.source().type(), CreationSourceType.COPIED_FROM_DISK);
    Assert.assertTrue(snapshot.source().sourceId().equalsIgnoreCase(emptyDisk.id()));
    Disk fromSnapshotDisk = computeManager.disks().define(snapshotBasedDiskName).withRegion(region).withExistingResourceGroup(resourceGroup).withData().fromSnapshot(snapshot).withSizeInGB(300).create();
    Assert.assertNotNull(fromSnapshotDisk.id());
    Assert.assertTrue(fromSnapshotDisk.name().equalsIgnoreCase(snapshotBasedDiskName));
    Assert.assertEquals(fromSnapshotDisk.sku(), DiskSkuTypes.STANDARD_LRS);
    Assert.assertEquals(fromSnapshotDisk.creationMethod(), DiskCreateOption.COPY);
    Assert.assertEquals(fromSnapshotDisk.sizeInGB(), 300);
    Assert.assertNull(fromSnapshotDisk.osType());
    Assert.assertNotNull(fromSnapshotDisk.source());
    Assert.assertEquals(fromSnapshotDisk.source().type(), CreationSourceType.COPIED_FROM_SNAPSHOT);
    Assert.assertTrue(fromSnapshotDisk.source().sourceId().equalsIgnoreCase(snapshot.id()));
}
Also used : ResourceGroup(com.microsoft.azure.management.resources.ResourceGroup) Test(org.junit.Test)

Example 40 with ResourceGroup

use of com.microsoft.azure.management.resources.ResourceGroup in project azure-sdk-for-java by Azure.

the class CreateVirtualMachinesInParallel 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";
    Map<Region, Integer> virtualMachinesByLocation = new HashMap<Region, Integer>();
    // debug target
    /**
         virtualMachinesByLocation.put(Region.US_EAST, 5);
         virtualMachinesByLocation.put(Region.US_SOUTH_CENTRAL, 5);
         */
    // final demo target
    virtualMachinesByLocation.put(Region.US_EAST, 12);
    virtualMachinesByLocation.put(Region.US_SOUTH_CENTRAL, 12);
    virtualMachinesByLocation.put(Region.US_WEST, 12);
    virtualMachinesByLocation.put(Region.US_NORTH_CENTRAL, 12);
    try {
        //=============================================================
        // Create a resource group (Where all resources gets created)
        //
        ResourceGroup resourceGroup = azure.resourceGroups().define(rgName).withRegion(Region.US_EAST).create();
        System.out.println("Created a new resource group - " + resourceGroup.id());
        List<String> publicIpCreatableKeys = new ArrayList<>();
        // Prepare a batch of Creatable definitions
        //
        List<Creatable<VirtualMachine>> creatableVirtualMachines = new ArrayList<>();
        for (Map.Entry<Region, Integer> entry : virtualMachinesByLocation.entrySet()) {
            Region region = entry.getKey();
            Integer vmCount = entry.getValue();
            //=============================================================
            // Create 1 network creatable per region
            // Prepare Creatable Network definition (Where all the virtual machines get added to)
            //
            String networkName = SdkContext.randomResourceName("vnetCOPD-", 20);
            Creatable<Network> networkCreatable = azure.networks().define(networkName).withRegion(region).withExistingResourceGroup(resourceGroup).withAddressSpace("172.16.0.0/16");
            //=============================================================
            // Create 1 storage creatable per region (For storing VMs disk)
            //
            String storageAccountName = SdkContext.randomResourceName("stgcopd", 20);
            Creatable<StorageAccount> storageAccountCreatable = azure.storageAccounts().define(storageAccountName).withRegion(region).withExistingResourceGroup(resourceGroup);
            String linuxVMNamePrefix = SdkContext.randomResourceName("vm-", 15);
            for (int i = 1; i <= vmCount; i++) {
                //=============================================================
                // Create 1 public IP address creatable
                //
                Creatable<PublicIPAddress> publicIPAddressCreatable = azure.publicIPAddresses().define(String.format("%s-%d", linuxVMNamePrefix, i)).withRegion(region).withExistingResourceGroup(resourceGroup).withLeafDomainLabel(SdkContext.randomResourceName("pip", 10));
                publicIpCreatableKeys.add(publicIPAddressCreatable.key());
                //=============================================================
                // Create 1 virtual machine creatable
                Creatable<VirtualMachine> virtualMachineCreatable = azure.virtualMachines().define(String.format("%s-%d", linuxVMNamePrefix, i)).withRegion(region).withExistingResourceGroup(resourceGroup).withNewPrimaryNetwork(networkCreatable).withPrimaryPrivateIPAddressDynamic().withNewPrimaryPublicIPAddress(publicIPAddressCreatable).withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS).withRootUsername(userName).withSsh(sshKey).withSize(VirtualMachineSizeTypes.STANDARD_DS3_V2).withNewStorageAccount(storageAccountCreatable);
                creatableVirtualMachines.add(virtualMachineCreatable);
            }
        }
        //=============================================================
        // Create !!
        StopWatch stopwatch = new StopWatch();
        System.out.println("Creating the virtual machines");
        stopwatch.start();
        CreatedResources<VirtualMachine> virtualMachines = azure.virtualMachines().create(creatableVirtualMachines);
        stopwatch.stop();
        System.out.println("Created virtual machines");
        for (VirtualMachine virtualMachine : virtualMachines.values()) {
            System.out.println(virtualMachine.id());
        }
        System.out.println("Virtual Machines created: (took " + (stopwatch.getTime() / 1000) + " seconds to create) == " + virtualMachines.size() + " == virtual machines");
        List<String> publicIpResourceIds = new ArrayList<>();
        for (String publicIpCreatableKey : publicIpCreatableKeys) {
            PublicIPAddress pip = (PublicIPAddress) virtualMachines.createdRelatedResource(publicIpCreatableKey);
            publicIpResourceIds.add(pip.id());
        }
        //=============================================================
        // Create 1 Traffic Manager Profile
        //
        String trafficManagerName = SdkContext.randomResourceName("tra", 15);
        TrafficManagerProfile.DefinitionStages.WithEndpoint profileWithEndpoint = azure.trafficManagerProfiles().define(trafficManagerName).withExistingResourceGroup(resourceGroup).withLeafDomainLabel(trafficManagerName).withPerformanceBasedRouting();
        int endpointPriority = 1;
        TrafficManagerProfile.DefinitionStages.WithCreate profileWithCreate = null;
        for (String publicIpResourceId : publicIpResourceIds) {
            String endpointName = String.format("azendpoint-%d", endpointPriority);
            if (endpointPriority == 1) {
                profileWithCreate = profileWithEndpoint.defineAzureTargetEndpoint(endpointName).toResourceId(publicIpResourceId).withRoutingPriority(endpointPriority).attach();
            } else {
                profileWithCreate = profileWithCreate.defineAzureTargetEndpoint(endpointName).toResourceId(publicIpResourceId).withRoutingPriority(endpointPriority).attach();
            }
            endpointPriority++;
        }
        System.out.println("Creating a traffic manager profile for the VMs");
        stopwatch.reset();
        stopwatch.start();
        TrafficManagerProfile trafficManagerProfile = profileWithCreate.create();
        stopwatch.stop();
        System.out.println("Created a traffic manager profile (took " + (stopwatch.getTime() / 1000) + " seconds to create): " + trafficManagerProfile.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 : HashMap(java.util.HashMap) TrafficManagerProfile(com.microsoft.azure.management.trafficmanager.TrafficManagerProfile) ArrayList(java.util.ArrayList) PublicIPAddress(com.microsoft.azure.management.network.PublicIPAddress) Network(com.microsoft.azure.management.network.Network) Creatable(com.microsoft.azure.management.resources.fluentcore.model.Creatable) ResourceGroup(com.microsoft.azure.management.resources.ResourceGroup) StopWatch(org.apache.commons.lang3.time.StopWatch) StorageAccount(com.microsoft.azure.management.storage.StorageAccount) Region(com.microsoft.azure.management.resources.fluentcore.arm.Region) HashMap(java.util.HashMap) Map(java.util.Map) VirtualMachine(com.microsoft.azure.management.compute.VirtualMachine)

Aggregations

ResourceGroup (com.microsoft.azure.management.resources.ResourceGroup)53 Test (org.junit.Test)22 Region (com.microsoft.azure.management.resources.fluentcore.arm.Region)13 SubscriptionDetail (com.microsoft.azuretools.authmanage.models.SubscriptionDetail)12 ArrayList (java.util.ArrayList)10 Network (com.microsoft.azure.management.network.Network)9 StorageAccount (com.microsoft.azure.management.storage.StorageAccount)9 VirtualMachine (com.microsoft.azure.management.compute.VirtualMachine)8 Creatable (com.microsoft.azure.management.resources.fluentcore.model.Creatable)7 AzureManager (com.microsoft.azuretools.sdkmanage.AzureManager)7 Azure (com.microsoft.azure.management.Azure)6 AppServicePlan (com.microsoft.azure.management.appservice.AppServicePlan)6 WebApp (com.microsoft.azure.management.appservice.WebApp)6 HashMap (java.util.HashMap)5 StopWatch (org.apache.commons.lang3.time.StopWatch)5 PublicIPAddress (com.microsoft.azure.management.network.PublicIPAddress)4 Location (com.microsoft.azure.management.resources.Location)4 CloudException (com.microsoft.azure.CloudException)3 Period (org.joda.time.Period)3 ApplicationGateway (com.microsoft.azure.management.network.ApplicationGateway)2