Search in sources :

Example 21 with StorageAccount

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

Example 22 with StorageAccount

use of com.microsoft.azure.management.storage.StorageAccount in project azure-sdk-for-java by Azure.

the class ManageWebAppStorageAccountConnection 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) {
    // New resources
    final String suffix = ".azurewebsites.net";
    final String app1Name = SdkContext.randomResourceName("webapp1-", 20);
    final String app1Url = app1Name + suffix;
    final String storageName = SdkContext.randomResourceName("jsdkstore", 20);
    final String containerName = SdkContext.randomResourceName("jcontainer", 20);
    final String rgName = SdkContext.randomResourceName("rg1NEMV_", 24);
    try {
        //============================================================
        // Create a storage account for the web app to use
        System.out.println("Creating storage account " + storageName + "...");
        StorageAccount storageAccount = azure.storageAccounts().define(storageName).withRegion(Region.US_WEST).withNewResourceGroup(rgName).create();
        String accountKey = storageAccount.getKeys().get(0).value();
        String connectionString = String.format("DefaultEndpointsProtocol=https;AccountName=%s;AccountKey=%s", storageAccount.name(), accountKey);
        System.out.println("Created storage account " + storageAccount.name());
        //============================================================
        // Upload a few files to the storage account blobs
        System.out.println("Uploading 2 blobs to container " + containerName + "...");
        CloudBlobContainer container = setUpStorageAccount(connectionString, containerName);
        uploadFileToContainer(container, "helloworld.war", ManageWebAppStorageAccountConnection.class.getResource("/helloworld.war").getPath());
        uploadFileToContainer(container, "install_apache.sh", ManageWebAppStorageAccountConnection.class.getResource("/install_apache.sh").getPath());
        System.out.println("Uploaded 2 blobs to container " + container.getName());
        //============================================================
        // Create a web app with a new app service plan
        System.out.println("Creating web app " + app1Name + "...");
        WebApp app1 = azure.webApps().define(app1Name).withRegion(Region.US_WEST).withExistingResourceGroup(rgName).withNewWindowsPlan(PricingTier.STANDARD_S1).withJavaVersion(JavaVersion.JAVA_8_NEWEST).withWebContainer(WebContainer.TOMCAT_8_0_NEWEST).withConnectionString("storage.connectionString", connectionString, ConnectionStringType.CUSTOM).withAppSetting("storage.containerName", containerName).create();
        System.out.println("Created web app " + app1.name());
        Utils.print(app1);
        //============================================================
        // Deploy a web app that connects to the storage account
        // Source code: https://github.com/jianghaolu/azure-samples-blob-explorer
        System.out.println("Deploying azure-samples-blob-traverser.war to " + app1Name + " through FTP...");
        Utils.uploadFileToFtp(app1.getPublishingProfile(), "azure-samples-blob-traverser.war", ManageWebAppStorageAccountConnection.class.getResourceAsStream("/azure-samples-blob-traverser.war"));
        System.out.println("Deployment azure-samples-blob-traverser.war to web app " + app1.name() + " completed");
        Utils.print(app1);
        // warm up
        System.out.println("Warming up " + app1Url + "/azure-samples-blob-traverser...");
        curl("http://" + app1Url + "/azure-samples-blob-traverser");
        Thread.sleep(5000);
        System.out.println("CURLing " + app1Url + "/azure-samples-blob-traverser...");
        System.out.println(curl("http://" + app1Url + "/azure-samples-blob-traverser"));
        return true;
    } catch (Exception e) {
        System.err.println(e.getMessage());
        e.printStackTrace();
    } finally {
        try {
            System.out.println("Deleting Resource Group: " + rgName);
            azure.resourceGroups().beginDeleteByName(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 : StorageAccount(com.microsoft.azure.management.storage.StorageAccount) CloudStorageAccount(com.microsoft.azure.storage.CloudStorageAccount) CloudBlobContainer(com.microsoft.azure.storage.blob.CloudBlobContainer) URISyntaxException(java.net.URISyntaxException) StorageException(com.microsoft.azure.storage.StorageException) IOException(java.io.IOException) InvalidKeyException(java.security.InvalidKeyException) WebApp(com.microsoft.azure.management.appservice.WebApp)

Example 23 with StorageAccount

use of com.microsoft.azure.management.storage.StorageAccount in project azure-sdk-for-java by Azure.

the class ManageBatchAccount 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 batchAccountName = Utils.createRandomName("ba");
    final String storageAccountName = Utils.createRandomName("sa");
    final String applicationName = "application";
    final String applicationDisplayName = "My application display name";
    final String applicationPackageName = "app_package";
    final String batchAccountName2 = Utils.createRandomName("ba2");
    final String rgName = Utils.createRandomName("rgBAMB");
    final Region region = Region.AUSTRALIA_SOUTHEAST;
    final Region region2 = Region.US_WEST;
    try {
        // ===========================================================
        // Get how many batch accounts can be created in specified region.
        int allowedNumberOfBatchAccounts = azure.batchAccounts().getBatchAccountQuotaByLocation(region);
        // ===========================================================
        // List all the batch accounts in subscription.
        List<BatchAccount> batchAccounts = azure.batchAccounts().list();
        int batchAccountsAtSpecificRegion = 0;
        for (BatchAccount batchAccount : batchAccounts) {
            if (batchAccount.region() == region) {
                batchAccountsAtSpecificRegion++;
            }
        }
        if (batchAccountsAtSpecificRegion >= allowedNumberOfBatchAccounts) {
            System.out.println("No more batch accounts can be created at " + region + " region, this region already have " + batchAccountsAtSpecificRegion + " batch accounts, current quota to create batch account in " + region + " region is " + allowedNumberOfBatchAccounts + ".");
            return false;
        }
        // ============================================================
        // Create a batch account
        System.out.println("Creating a batch Account");
        BatchAccount batchAccount = azure.batchAccounts().define(batchAccountName).withRegion(region).withNewResourceGroup(rgName).defineNewApplication(applicationName).defineNewApplicationPackage(applicationPackageName).withAllowUpdates(true).withDisplayName(applicationDisplayName).attach().withNewStorageAccount(storageAccountName).create();
        System.out.println("Created a batch Account:");
        Utils.print(batchAccount);
        // ============================================================
        // Get | regenerate batch account access keys
        System.out.println("Getting batch account access keys");
        BatchAccountKeys batchAccountKeys = batchAccount.getKeys();
        Utils.print(batchAccountKeys);
        System.out.println("Regenerating primary batch account primary access key");
        batchAccountKeys = batchAccount.regenerateKeys(AccountKeyType.PRIMARY);
        Utils.print(batchAccountKeys);
        // ============================================================
        // Regenerate the keys for storage account
        StorageAccount storageAccount = azure.storageAccounts().getByResourceGroup(rgName, storageAccountName);
        List<StorageAccountKey> storageAccountKeys = storageAccount.getKeys();
        Utils.print(storageAccountKeys);
        System.out.println("Regenerating first storage account access key");
        storageAccountKeys = storageAccount.regenerateKey(storageAccountKeys.get(0).keyName());
        Utils.print(storageAccountKeys);
        // ============================================================
        // Synchronize storage account keys with batch account
        batchAccount.synchronizeAutoStorageKeys();
        // ============================================================
        // Update name of application.
        batchAccount.update().updateApplication(applicationName).withDisplayName("New application display name").parent().apply();
        batchAccount.refresh();
        Utils.print(batchAccount);
        // ============================================================
        // Create another batch account
        System.out.println("Creating another Batch Account");
        allowedNumberOfBatchAccounts = azure.batchAccounts().getBatchAccountQuotaByLocation(region2);
        // ===========================================================
        // List all the batch accounts in subscription.
        batchAccounts = azure.batchAccounts().list();
        batchAccountsAtSpecificRegion = 0;
        for (BatchAccount batch : batchAccounts) {
            if (batch.region() == region2) {
                batchAccountsAtSpecificRegion++;
            }
        }
        BatchAccount batchAccount2 = null;
        if (batchAccountsAtSpecificRegion < allowedNumberOfBatchAccounts) {
            batchAccount2 = azure.batchAccounts().define(batchAccountName2).withRegion(region2).withExistingResourceGroup(rgName).withExistingStorageAccount(storageAccount).create();
            System.out.println("Created second Batch Account:");
            Utils.print(batchAccount2);
        }
        // ============================================================
        // List batch accounts
        System.out.println("Listing Batch accounts");
        List<BatchAccount> accounts = azure.batchAccounts().listByResourceGroup(rgName);
        BatchAccount ba;
        for (int i = 0; i < accounts.size(); i++) {
            ba = accounts.get(i);
            System.out.println("Batch Account (" + i + ") " + ba.name());
        }
        // ============================================================
        // Refresh a batch account.
        batchAccount.refresh();
        Utils.print(batchAccount);
        // ============================================================
        // Delete a batch account
        System.out.println("Deleting a batch account - " + batchAccount.name());
        for (Map.Entry<String, Application> applicationEntry : batchAccount.applications().entrySet()) {
            for (Map.Entry<String, ApplicationPackage> applicationPackageEntry : applicationEntry.getValue().applicationPackages().entrySet()) {
                System.out.println("Deleting a application package - " + applicationPackageEntry.getKey());
                applicationPackageEntry.getValue().delete();
            }
            System.out.println("Deleting a application - " + applicationEntry.getKey());
            batchAccount.update().withoutApplication(applicationEntry.getKey()).apply();
        }
        azure.batchAccounts().deleteById(batchAccount.id());
        System.out.println("Deleted batch account");
        if (batchAccount2 != null) {
            System.out.println("Deleting second batch account - " + batchAccount2.name());
            azure.batchAccounts().deleteById(batchAccount2.id());
            System.out.println("Deleted second batch account");
        }
        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 : BatchAccount(com.microsoft.azure.management.batch.BatchAccount) ApplicationPackage(com.microsoft.azure.management.batch.ApplicationPackage) StorageAccount(com.microsoft.azure.management.storage.StorageAccount) StorageAccountKey(com.microsoft.azure.management.storage.StorageAccountKey) Region(com.microsoft.azure.management.resources.fluentcore.arm.Region) BatchAccountKeys(com.microsoft.azure.management.batch.BatchAccountKeys) Map(java.util.Map) Application(com.microsoft.azure.management.batch.Application)

Example 24 with StorageAccount

use of com.microsoft.azure.management.storage.StorageAccount 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 25 with StorageAccount

use of com.microsoft.azure.management.storage.StorageAccount in project azure-sdk-for-java by Azure.

the class ManageResource 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("rgRSMR", 24);
    final String resourceName1 = SdkContext.randomResourceName("rn1", 24);
    final String resourceName2 = SdkContext.randomResourceName("rn2", 24);
    try {
        //=============================================================
        // Create resource group.
        System.out.println("Creating a resource group with name: " + rgName);
        azure.resourceGroups().define(rgName).withRegion(Region.US_WEST).create();
        //=============================================================
        // Create storage account.
        System.out.println("Creating a storage account with name: " + resourceName1);
        StorageAccount storageAccount = azure.storageAccounts().define(resourceName1).withRegion(Region.US_WEST).withExistingResourceGroup(rgName).create();
        System.out.println("Storage account created: " + storageAccount.id());
        //=============================================================
        // Update - set the sku name
        System.out.println("Updating the storage account with name: " + resourceName1);
        storageAccount.update().withSku(SkuName.STANDARD_RAGRS).apply();
        System.out.println("Updated the storage account with name: " + resourceName1);
        //=============================================================
        // Create another storage account.
        System.out.println("Creating another storage account with name: " + resourceName2);
        StorageAccount storageAccount2 = azure.storageAccounts().define(resourceName2).withRegion(Region.US_WEST).withExistingResourceGroup(rgName).create();
        System.out.println("Storage account created: " + storageAccount2.id());
        //=============================================================
        // List storage accounts.
        System.out.println("Listing all storage accounts for resource group: " + rgName);
        for (StorageAccount sAccount : azure.storageAccounts().list()) {
            System.out.println("Storage account: " + sAccount.name());
        }
        //=============================================================
        // Delete a storage accounts.
        System.out.println("Deleting storage account: " + resourceName2);
        azure.storageAccounts().deleteById(storageAccount2.id());
        System.out.println("Deleted storage account: " + resourceName2);
        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 : StorageAccount(com.microsoft.azure.management.storage.StorageAccount)

Aggregations

StorageAccount (com.microsoft.azure.management.storage.StorageAccount)30 ResourceGroup (com.microsoft.azure.management.resources.ResourceGroup)9 ArrayList (java.util.ArrayList)8 ClientStorageAccount (com.microsoft.tooling.msservices.model.storage.ClientStorageAccount)7 VirtualMachine (com.microsoft.azure.management.compute.VirtualMachine)5 Network (com.microsoft.azure.management.network.Network)5 Region (com.microsoft.azure.management.resources.fluentcore.arm.Region)5 Creatable (com.microsoft.azure.management.resources.fluentcore.model.Creatable)5 StorageAccountKey (com.microsoft.azure.management.storage.StorageAccountKey)5 Test (org.junit.Test)5 Func1 (rx.functions.Func1)4 Indexable (com.microsoft.azure.management.resources.fluentcore.model.Indexable)3 CloudStorageAccount (com.microsoft.azure.storage.CloudStorageAccount)3 CloudBlobContainer (com.microsoft.azure.storage.blob.CloudBlobContainer)3 StopWatch (org.apache.commons.lang3.time.StopWatch)3 CloudException (com.microsoft.azure.CloudException)2 WebApp (com.microsoft.azure.management.appservice.WebApp)2 PublicIPAddress (com.microsoft.azure.management.network.PublicIPAddress)2 Resource (com.microsoft.azure.management.resources.fluentcore.arm.models.Resource)2 StorageAccounts (com.microsoft.azure.management.storage.StorageAccounts)2