Search in sources :

Example 1 with StorageAccountKey

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

the class RegistryImpl method handleStorageSettings.

private Observable<StorageAccountParameters> handleStorageSettings() {
    final Func1<StorageAccount, StorageAccountParameters> onStorageAccountReady = new Func1<StorageAccount, StorageAccountParameters>() {

        @Override
        public StorageAccountParameters call(StorageAccount storageAccount) {
            RegistryImpl.this.storageAccount = storageAccount;
            List<StorageAccountKey> keys = storageAccount.getKeys();
            StorageAccountParameters storageAccountParameters = new StorageAccountParameters();
            storageAccountParameters.withName(storageAccount.name());
            storageAccountParameters.withAccessKey(keys.get(0).value());
            return storageAccountParameters;
        }
    };
    if (this.creatableStorageAccountKey != null) {
        return Observable.just((StorageAccount) this.createdResource(this.creatableStorageAccountKey)).map(onStorageAccountReady);
    } else {
        return Observable.just(this.storageAccount).map(onStorageAccountReady);
    }
}
Also used : StorageAccount(com.microsoft.azure.management.storage.StorageAccount) StorageAccountKey(com.microsoft.azure.management.storage.StorageAccountKey) Func1(rx.functions.Func1) StorageAccountParameters(com.microsoft.azure.management.containerregistry.StorageAccountParameters)

Example 2 with StorageAccountKey

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

the class ManageStorageAccountAsync method runSample.

/**
     * Main function which runs the actual sample.
     * @param azure instance of the azure client
     * @return true if sample runs successfully
     */
public static boolean runSample(final Azure azure) {
    final String storageAccountName = Utils.createRandomName("sa");
    final String storageAccountName2 = Utils.createRandomName("sa2");
    final String rgName = Utils.createRandomName("rgSTMS");
    try {
        // ============================================================
        // Create storage accounts
        System.out.println("Creating a Storage Accounts");
        Observable.merge(azure.storageAccounts().define(storageAccountName).withRegion(Region.US_EAST).withNewResourceGroup(rgName).createAsync(), azure.storageAccounts().define(storageAccountName2).withRegion(Region.US_EAST).withNewResourceGroup(rgName).createAsync()).map(new Func1<Indexable, Indexable>() {

            @Override
            public Indexable call(Indexable indexable) {
                if (indexable instanceof StorageAccount) {
                    StorageAccount storageAccount = (StorageAccount) indexable;
                    System.out.println("Created a Storage Account:");
                    Utils.print(storageAccount);
                }
                return indexable;
            }
        }).toBlocking().last();
        // ============================================================
        // List storage accounts and regenerate storage account access keys
        System.out.println("Listing storage accounts");
        StorageAccounts storageAccounts = azure.storageAccounts();
        storageAccounts.listByResourceGroupAsync(rgName).flatMap(new Func1<StorageAccount, Observable<List<StorageAccountKey>>>() {

            @Override
            public Observable<List<StorageAccountKey>> call(final StorageAccount storageAccount) {
                System.out.println("Getting storage account access keys for Storage Account " + storageAccount.name() + " created @ " + storageAccount.creationTime());
                return storageAccount.getKeysAsync().flatMap(new Func1<List<StorageAccountKey>, Observable<List<StorageAccountKey>>>() {

                    @Override
                    public Observable<List<StorageAccountKey>> call(List<StorageAccountKey> storageAccountKeys) {
                        System.out.println("Regenerating first storage account access key");
                        return storageAccount.regenerateKeyAsync(storageAccountKeys.get(0).keyName());
                    }
                });
            }
        }).map(new Func1<List<StorageAccountKey>, List<StorageAccountKey>>() {

            @Override
            public List<StorageAccountKey> call(List<StorageAccountKey> storageAccountKeys) {
                Utils.print(storageAccountKeys);
                return storageAccountKeys;
            }
        }).toBlocking().last();
        // ============================================================
        // Delete storage accounts
        storageAccounts.listByResourceGroupAsync(rgName).flatMap(new Func1<StorageAccount, Observable<Void>>() {

            @Override
            public Observable<Void> call(StorageAccount storageAccount) {
                System.out.println("Deleting a storage account - " + storageAccount.name() + " created @ " + storageAccount.creationTime());
                return azure.storageAccounts().deleteByIdAsync(storageAccount.id()).toObservable();
            }
        }).toCompletable().await();
        return true;
    } catch (Exception f) {
        System.out.println(f.getMessage());
        f.printStackTrace();
    } finally {
        try {
            System.out.println("Deleting Resource Group: " + rgName);
            azure.resourceGroups().deleteByNameAsync(rgName).await();
            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 : Observable(rx.Observable) StorageAccount(com.microsoft.azure.management.storage.StorageAccount) StorageAccountKey(com.microsoft.azure.management.storage.StorageAccountKey) Indexable(com.microsoft.azure.management.resources.fluentcore.model.Indexable) List(java.util.List) StorageAccounts(com.microsoft.azure.management.storage.StorageAccounts) Func1(rx.functions.Func1)

Example 3 with StorageAccountKey

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

the class ManageStorageAccount 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 storageAccountName = Utils.createRandomName("sa");
    final String storageAccountName2 = Utils.createRandomName("sa2");
    final String rgName = Utils.createRandomName("rgSTMS");
    try {
        // ============================================================
        // Create a storage account
        System.out.println("Creating a Storage Account");
        StorageAccount storageAccount = azure.storageAccounts().define(storageAccountName).withRegion(Region.US_EAST).withNewResourceGroup(rgName).create();
        System.out.println("Created a Storage Account:");
        Utils.print(storageAccount);
        // ============================================================
        // Get | regenerate storage account access keys
        System.out.println("Getting storage account access keys");
        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);
        // ============================================================
        // Create another storage account
        System.out.println("Creating a 2nd Storage Account");
        StorageAccount storageAccount2 = azure.storageAccounts().define(storageAccountName2).withRegion(Region.US_EAST).withNewResourceGroup(rgName).create();
        System.out.println("Created a Storage Account:");
        Utils.print(storageAccount2);
        // ============================================================
        // List storage accounts
        System.out.println("Listing storage accounts");
        StorageAccounts storageAccounts = azure.storageAccounts();
        List<StorageAccount> accounts = storageAccounts.listByResourceGroup(rgName);
        StorageAccount sa;
        for (int i = 0; i < accounts.size(); i++) {
            sa = (StorageAccount) accounts.get(i);
            System.out.println("Storage Account (" + i + ") " + sa.name() + " created @ " + sa.creationTime());
        }
        // ============================================================
        // Delete a storage account
        System.out.println("Deleting a storage account - " + storageAccount.name() + " created @ " + storageAccount.creationTime());
        azure.storageAccounts().deleteById(storageAccount.id());
        System.out.println("Deleted storage 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 : StorageAccount(com.microsoft.azure.management.storage.StorageAccount) StorageAccountKey(com.microsoft.azure.management.storage.StorageAccountKey) StorageAccounts(com.microsoft.azure.management.storage.StorageAccounts)

Example 4 with StorageAccountKey

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

the class VirtualMachineScaleSetOperationsTests method canUpdateVirtualMachineScaleSetWithExtensionProtectedSettings.

@Test
public void canUpdateVirtualMachineScaleSetWithExtensionProtectedSettings() throws Exception {
    final String vmssName = generateRandomResourceName("vmss", 10);
    final String uname = "jvuser";
    final String password = "123OData!@#123";
    ResourceGroup resourceGroup = this.resourceManager.resourceGroups().define(RG_NAME).withRegion(REGION).create();
    StorageAccount storageAccount = this.storageManager.storageAccounts().define(generateRandomResourceName("stg", 15)).withRegion(REGION).withExistingResourceGroup(resourceGroup).create();
    List<StorageAccountKey> keys = storageAccount.getKeys();
    Assert.assertNotNull(keys);
    Assert.assertTrue(keys.size() > 0);
    String storageAccountKey = keys.get(0).value();
    final String storageConnectionString = String.format("DefaultEndpointsProtocol=http;AccountName=%s;AccountKey=%s", storageAccount.name(), storageAccountKey);
    // Get the script to upload
    //
    InputStream scriptFileAsStream = VirtualMachineScaleSetOperationsTests.class.getResourceAsStream("/install_apache.sh");
    // Get the size of the stream
    //
    int fileSize;
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    byte[] buffer = new byte[256];
    int bytesRead;
    while ((bytesRead = scriptFileAsStream.read(buffer)) != -1) {
        outputStream.write(buffer, 0, bytesRead);
    }
    fileSize = outputStream.size();
    outputStream.close();
    // Upload the script file as block blob
    //
    URI fileUri;
    if (IS_MOCKED) {
        fileUri = new URI("http://nonexisting.blob.core.windows.net/scripts/install_apache.sh");
    } else {
        CloudStorageAccount account = CloudStorageAccount.parse(storageConnectionString);
        CloudBlobClient cloudBlobClient = account.createCloudBlobClient();
        CloudBlobContainer container = cloudBlobClient.getContainerReference("scripts");
        container.createIfNotExists();
        CloudBlockBlob blob = container.getBlockBlobReference("install_apache.sh");
        blob.upload(scriptFileAsStream, fileSize);
        fileUri = blob.getUri();
    }
    List<String> fileUris = new ArrayList<>();
    fileUris.add(fileUri.toString());
    Network network = this.networkManager.networks().define(generateRandomResourceName("vmssvnet", 15)).withRegion(REGION).withExistingResourceGroup(resourceGroup).withAddressSpace("10.0.0.0/28").withSubnet("subnet1", "10.0.0.0/28").create();
    VirtualMachineScaleSet virtualMachineScaleSet = this.computeManager.virtualMachineScaleSets().define(vmssName).withRegion(REGION).withExistingResourceGroup(resourceGroup).withSku(VirtualMachineScaleSetSkuTypes.STANDARD_A0).withExistingPrimaryNetworkSubnet(network, "subnet1").withoutPrimaryInternetFacingLoadBalancer().withoutPrimaryInternalLoadBalancer().withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS).withRootUsername(uname).withRootPassword(password).withUnmanagedDisks().withNewStorageAccount(generateRandomResourceName("stg", 15)).withExistingStorageAccount(storageAccount).defineNewExtension("CustomScriptForLinux").withPublisher("Microsoft.OSTCExtensions").withType("CustomScriptForLinux").withVersion("1.4").withMinorVersionAutoUpgrade().withPublicSetting("fileUris", fileUris).withProtectedSetting("commandToExecute", "bash install_apache.sh").withProtectedSetting("storageAccountName", storageAccount.name()).withProtectedSetting("storageAccountKey", storageAccountKey).attach().create();
    // Validate extensions after create
    //
    Map<String, VirtualMachineScaleSetExtension> extensions = virtualMachineScaleSet.extensions();
    Assert.assertNotNull(extensions);
    Assert.assertEquals(1, extensions.size());
    Assert.assertTrue(extensions.containsKey("CustomScriptForLinux"));
    VirtualMachineScaleSetExtension extension = extensions.get("CustomScriptForLinux");
    Assert.assertNotNull(extension.publicSettings());
    Assert.assertEquals(1, extension.publicSettings().size());
    Assert.assertNotNull(extension.publicSettingsAsJsonString());
    // Retrieve scale set
    VirtualMachineScaleSet scaleSet = this.computeManager.virtualMachineScaleSets().getById(virtualMachineScaleSet.id());
    // Validate extensions after get
    //
    extensions = virtualMachineScaleSet.extensions();
    Assert.assertNotNull(extensions);
    Assert.assertEquals(1, extensions.size());
    Assert.assertTrue(extensions.containsKey("CustomScriptForLinux"));
    extension = extensions.get("CustomScriptForLinux");
    Assert.assertNotNull(extension.publicSettings());
    Assert.assertEquals(1, extension.publicSettings().size());
    Assert.assertNotNull(extension.publicSettingsAsJsonString());
    // Update VMSS capacity
    //
    int newCapacity = (int) (scaleSet.capacity() + 1);
    virtualMachineScaleSet.update().withCapacity(newCapacity).apply();
    // Validate extensions after update
    //
    extensions = virtualMachineScaleSet.extensions();
    Assert.assertNotNull(extensions);
    Assert.assertEquals(1, extensions.size());
    Assert.assertTrue(extensions.containsKey("CustomScriptForLinux"));
    extension = extensions.get("CustomScriptForLinux");
    Assert.assertNotNull(extension.publicSettings());
    Assert.assertEquals(1, extension.publicSettings().size());
    Assert.assertNotNull(extension.publicSettingsAsJsonString());
}
Also used : CloudBlobClient(com.microsoft.azure.storage.blob.CloudBlobClient) InputStream(java.io.InputStream) CloudStorageAccount(com.microsoft.azure.storage.CloudStorageAccount) ArrayList(java.util.ArrayList) ByteArrayOutputStream(java.io.ByteArrayOutputStream) CloudBlockBlob(com.microsoft.azure.storage.blob.CloudBlockBlob) URI(java.net.URI) StorageAccount(com.microsoft.azure.management.storage.StorageAccount) CloudStorageAccount(com.microsoft.azure.storage.CloudStorageAccount) StorageAccountKey(com.microsoft.azure.management.storage.StorageAccountKey) CloudBlobContainer(com.microsoft.azure.storage.blob.CloudBlobContainer) ResourceGroup(com.microsoft.azure.management.resources.ResourceGroup) Test(org.junit.Test)

Example 5 with StorageAccountKey

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

Aggregations

StorageAccountKey (com.microsoft.azure.management.storage.StorageAccountKey)7 StorageAccount (com.microsoft.azure.management.storage.StorageAccount)5 Func1 (rx.functions.Func1)3 StorageAccounts (com.microsoft.azure.management.storage.StorageAccounts)2 List (java.util.List)2 Application (com.microsoft.azure.management.batch.Application)1 ApplicationPackage (com.microsoft.azure.management.batch.ApplicationPackage)1 BatchAccount (com.microsoft.azure.management.batch.BatchAccount)1 BatchAccountKeys (com.microsoft.azure.management.batch.BatchAccountKeys)1 StorageAccountParameters (com.microsoft.azure.management.containerregistry.StorageAccountParameters)1 ResourceGroup (com.microsoft.azure.management.resources.ResourceGroup)1 Region (com.microsoft.azure.management.resources.fluentcore.arm.Region)1 Indexable (com.microsoft.azure.management.resources.fluentcore.model.Indexable)1 TrafficManagerAzureEndpoint (com.microsoft.azure.management.trafficmanager.TrafficManagerAzureEndpoint)1 TrafficManagerExternalEndpoint (com.microsoft.azure.management.trafficmanager.TrafficManagerExternalEndpoint)1 TrafficManagerNestedProfileEndpoint (com.microsoft.azure.management.trafficmanager.TrafficManagerNestedProfileEndpoint)1 CloudStorageAccount (com.microsoft.azure.storage.CloudStorageAccount)1 CloudBlobClient (com.microsoft.azure.storage.blob.CloudBlobClient)1 CloudBlobContainer (com.microsoft.azure.storage.blob.CloudBlobContainer)1 CloudBlockBlob (com.microsoft.azure.storage.blob.CloudBlockBlob)1