def create_account(self): self.log("Creating account {0}".format(self.name)) if not self.location: self.fail('Parameter error: location required when creating a storage account.') if not self.account_type: self.fail('Parameter error: account_type required when creating a storage account.') self.check_name_availability() self.results['changed'] = True if self.check_mode: account_dict = dict( location=self.location, account_type=self.account_type, name=self.name, resource_group=self.resource_group, tags=dict() ) if self.tags: account_dict['tags'] = self.tags return account_dict sku = Sku(SkuName(self.account_type)) sku.tier = SkuTier.standard if 'Standard' in self.account_type else SkuTier.premium parameters = StorageAccountCreateParameters(sku, self.kind, self.location, tags=self.tags) self.log(str(parameters)) try: poller = self.storage_client.storage_accounts.create(self.resource_group, self.name, parameters) self.get_poller_result(poller) except AzureHttpError as e: self.log('Error creating storage account.') self.fail("Failed to create account: {0}".format(str(e))) # the poller doesn't actually return anything return self.get_account()
def create_account(self): self.log("Creating account {0}".format(self.name)) if not self.location: self.fail('Parameter error: location required when creating a storage account.') if not self.account_type: self.fail('Parameter error: account_type required when creating a storage account.') self.check_name_availability() self.results['changed'] = True if self.check_mode: account_dict = dict( location=self.location, account_type=self.account_type, name=self.name, resource_group=self.resource_group, tags=dict() ) if self.tags: account_dict['tags'] = self.tags return account_dict sku = Sku(SkuName(self.account_type)) sku.tier = SkuTier.standard if 'Standard' in self.account_type else SkuTier['Pemium'] parameters = StorageAccountCreateParameters(sku, self.kind, self.location, tags=self.tags) self.log(str(parameters)) try: poller = self.storage_client.storage_accounts.create(self.resource_group, self.name, parameters) self.get_poller_result(poller) except AzureHttpError, e: self.log('Error creating storage account.') self.fail("Failed to create account: {0}".format(str(e)))
def update_account(self): self.log('Update storage account {0}'.format(self.name)) if self.account_type: if self.account_type != self.account_dict['sku_name']: # change the account type if self.account_dict['sku_name'] in [SkuName.premium_lrs, SkuName.standard_zrs]: self.fail("Storage accounts of type {0} and {1} cannot be changed.".format( SkuName.premium_lrs, SkuName.standard_zrs)) if self.account_type in [SkuName.premium_lrs, SkuName.standard_zrs]: self.fail("Storage account of type {0} cannot be changed to a type of {1} or {2}.".format( self.account_dict['sku_name'], SkuName.premium_lrs, SkuName.standard_zrs)) self.results['changed'] = True self.account_dict['sku_name'] = self.account_type if self.results['changed'] and not self.check_mode: # Perform the update. The API only allows changing one attribute per call. try: self.log("sku_name: %s" % self.account_dict['sku_name']) self.log("sku_tier: %s" % self.account_dict['sku_tier']) sku = Sku(SkuName(self.account_dict['sku_name'])) sku.tier = SkuTier(self.account_dict['sku_tier']) parameters = StorageAccountUpdateParameters(sku=sku) self.storage_client.storage_accounts.update(self.resource_group, self.name, parameters) except Exception as exc: self.fail("Failed to update account type: {0}".format(str(exc))) if self.custom_domain: if not self.account_dict['custom_domain'] or \ self.account_dict['custom_domain'] != self.account_dict['custom_domain']: self.results['changed'] = True self.account_dict['custom_domain'] = self.custom_domain if self.results['changed'] and not self.check_mode: new_domain = CustomDomain(name=self.custom_domain['name'], use_sub_domain=self.custom_domain['use_sub_domain']) parameters = StorageAccountUpdateParameters(custom_domain=new_domain) try: self.storage_client.storage_accounts.update(self.resource_group, self.name, parameters) except Exception as exc: self.fail("Failed to update custom domain: {0}".format(str(exc))) update_tags, self.account_dict['tags'] = self.update_tags(self.account_dict['tags']) if update_tags: self.results['changed'] = True if not self.check_mode: parameters = StorageAccountUpdateParameters(tags=self.account_dict['tags']) try: self.storage_client.storage_accounts.update(self.resource_group, self.name, parameters) except Exception as exc: self.fail("Failed to update tags: {0}".format(str(exc)))
def create_storage_account(self): self.resource_client.providers.register('Microsoft.Storage') storage_name = Utils.name_generator() # Check availability availability = self.storage_client.storage_accounts.check_name_availability( storage_name) while not availability: storage_name = Utils.name_generator() availability = self.storage_client.storage_accounts.check_name_availability( storage_name) if availability: storage_async_operation = self.storage_client.storage_accounts.create( 'InstanT', storage_name, StorageAccountCreateParameters( sku=Sku(name=SkuName.standard_ragrs), kind=Kind.storage, location='francecentral', enable_https_traffic_only=True)) storage_account = storage_async_operation.result() Utils.print_storage(self, storage_account) storage_keys = self.storage_client.storage_accounts.list_keys( 'InstanT', storage_name) storage_keys = {v.key_name: v.value for v in storage_keys.keys} connection_str = Utils.connection_string(storage_name, storage_keys['key1']) blob_service_client = BlobServiceClient.from_connection_string( connection_str) container_name = "test" + str(uuid.uuid4()) container_client = blob_service_client.create_container( container_name, public_access=PublicAccess.Container) return storage_name, connection_str, container_name
def create_storage_account(self, parameters, storage_client): """ Creates a Storage Account under the Resource Group, if it does not already exist. In the case where no resource group is specified, a default storage account is created. Args: parameters: A dict, containing all the parameters necessary to authenticate this user with Azure. credentials: A ServicePrincipalCredentials instance, that can be used to access or create any resources. Raises: AgentConfigurationException: If there was a problem creating or accessing a storage account with the given subscription. """ storage_account = parameters[self.PARAM_STORAGE_ACCOUNT] rg_name = parameters[self.PARAM_RESOURCE_GROUP] try: AppScaleLogger.log( "Creating a new storage account '{0}' under the " "resource group '{1}'.".format(storage_account, rg_name)) result = storage_client.storage_accounts.create( rg_name, storage_account, StorageAccountCreateParameters( sku=Sku(SkuName.standard_lrs), kind=Kind.storage, location=parameters[self.PARAM_ZONE])) # Result is a msrestazure.azure_operation.AzureOperationPoller instance. # wait() insures polling the underlying async operation until it's done. result.wait() except CloudError as error: raise AgentConfigurationException( "Unable to create a storage account " "using the credentials provided: {}".format(error.message))
def __create_storage_account_and_get_key(self): basic_token_auth = BasicTokenAuthentication( {'access_token': self.__get_access_token()}) client = StorageManagementClient(basic_token_auth, self.__subscription_id) storage_accounts = list( client.storage_accounts.list_by_resource_group( self.__resource_group)) if (not any( [x.name == self.__storage_account_name for x in storage_accounts])): print("Creating storage account", self.__storage_account_name) client.storage_accounts.create( self.__resource_group, self.__storage_account_name, StorageAccountCreateParameters( sku=Sku(SkuName.standard_ragrs), kind=Kind.storage, location=self.__location)).result() print("Created storage account", self.__storage_account_name) storage_keys = client.storage_accounts.list_keys( self.__resource_group, self.__storage_account_name) storage_keys = {v.key_name: v.value for v in storage_keys.keys} return storage_keys['key1']
def create_acct_if_not_exists(context): storage_acct_name = context.obj['storage_account'] storage_client = context.obj['storage_client'] availability = storage_client.storage_accounts.check_name_availability( storage_acct_name) if not availability.name_available: if availability.reason.value == 'AlreadyExists': LOGGER.info( cli.utils.already_exists(STORAGE_ACCOUNT_TYPE, storage_acct_name)) set_storage_account_key(context) else: LOGGER.warning( cli.utils.create_failed(STORAGE_ACCOUNT_TYPE, storage_acct_name, availability.message)) return False else: storage_client.storage_accounts.create( context.obj['resource_group'], storage_acct_name, StorageAccountCreateParameters(sku=Sku(SkuName.standard_ragrs), kind=Kind.storage, location=context.obj['location'])) LOGGER.info(cli.utils.created(STORAGE_ACCOUNT_TYPE, storage_acct_name)) # wait for storage account to be provisioning state 'Succeeded' print('Storage account is being allocated...') provisioning_state = get_storage_account_state(context) while provisioning_state != 'Succeeded': time.sleep(ONE_SECOND) print('Waiting on storage account allocation...') provisioning_state = get_storage_account_state(context) set_storage_account_key(context) return True
def get_or_create_container(self, region, storage_account_name, group_name, container_name): # TODO ME # if storage account doesn't exist storage_async_operation = self.storage_client.storage_accounts.create( group_name, storage_account_name, StorageAccountCreateParameters( sku=Sku(name=SkuName.standard_ragrs), kind=Kind.storage, location=region)) storage_account = storage_async_operation.result() storage_keys = self.storage_client.storage_accounts.list_keys( group_name, storage_account_name) storage_keys = {v.key_name: v.value for v in storage_keys.keys} block_blob_service = BlockBlobService(account_name=storage_account, account_key=storage_keys['key1']) containers = block_blob_service.list_containers() if list( filter(lambda container: container['name'] == container_name, containers)): return block_blob_service else: block_blob_service.create_container(container_name) return block_blob_service
def create_sto_account(self): if self.check_if_sto_acc_exist(): return False if self.env == 'prod': tag = {'project': 'jahia_cloud_prod'} else: tag = {'project': 'jahia_cloud_dev'} client = self.return_session(StorageManagementClient) sto_async_operation = client.storage_accounts.create( self.rg, self.sto_account, StorageAccountCreateParameters( sku=Sku(name=SkuName.standard_ragrs), kind=Kind.storage_v2, location=self.region_name, tags=tag)) if sto_async_operation.result(): logging.info( "Storage {} is now created in {} on location {}".format( self.sto_account, self.rg, self.region_name)) logging.debug(sto_async_operation.result()) return True else: logging.error("Cannot create Storage Account {} in {}".format( self.sto_account, self.rg)) logging.error(sto_async_operation.result()) return False
def create_account(storage_client, resource_group_name, name, location): future = storage_client.storage_accounts.create( resource_group_name, name, StorageAccountCreateParameters(sku=Sku(SkuName.standard_ragrs), kind=Kind.storage, location=location)) future.result() return get_account(storage_client, resource_group_name, name)
def test_ml(self): self.create_resource_group() region = 'southcentralus' # Create a storage account and get keys storage_name = self.get_resource_name('pystorage') storage_client = azure.mgmt.storage.StorageManagementClient( credentials=self.settings.get_credentials(), subscription_id=self.settings.SUBSCRIPTION_ID) storage_async_operation = storage_client.storage_accounts.create( self.group_name, storage_name, StorageAccountCreateParameters(sku=Sku(SkuName.standard_ragrs), kind=Kind.storage, location=region)) storage_async_operation.wait() storage_key = storage_client.storage_accounts.list_keys( self.group_name, storage_name).keys[0].value # Create Commitment plan commitplan_name = self.get_resource_name('pycommit') commitplan = self.resource_client.resources.create_or_update( resource_group_name=self.group_name, resource_provider_namespace="Microsoft.MachineLearning", parent_resource_path="", resource_type="commitmentPlans", resource_name=commitplan_name, api_version="2016-05-01-preview", parameters={ 'location': region, 'sku': { 'name': "DevTest", 'tier': 'Standard', 'capacity': '1' } }) # Create WebService ws_name = self.get_resource_name('pyws') self.client.web_services.create_or_update( { 'location': region, 'properties': { 'storage_account': { 'name': storage_name, 'key': storage_key }, 'machine_learning_workspace': { 'id': commitplan.id }, 'packageType': 'Graph' } }, self.group_name, ws_name)
def create_account(self): self.log("Creating account {0}".format(self.name)) if not self.location: self.fail('Parameter error: location required when creating a storage account.') if not self.account_type: self.fail('Parameter error: account_type required when creating a storage account.') if not self.access_tier and self.kind == 'BlobStorage': self.fail('Parameter error: access_tier required when creating a storage account of type BlobStorage.') self.check_name_availability() self.results['changed'] = True if self.check_mode: account_dict = dict( location=self.location, account_type=self.account_type, name=self.name, resource_group=self.resource_group, tags=dict() ) if self.tags: account_dict['tags'] = self.tags return account_dict sku = Sku(SkuName(self.account_type)) sku.tier = SkuTier.standard if 'Standard' in self.account_type else SkuTier.premium parameters = StorageAccountCreateParameters(sku, self.kind, self.location, tags=self.tags, access_tier=self.access_tier) self.log(str(parameters)) try: poller = self.storage_client.storage_accounts.create(self.resource_group, self.name, parameters) self.get_poller_result(poller) except CloudError as e: self.log('Error creating storage account.') self.fail("Failed to create account: {0}".format(str(e))) # the poller doesn't actually return anything return self.get_account()
def storage_account(self): # Creates storage account using arguements from above storage_client = StorageManagementClient(self.credentials(), self.subscription_id()) storage_async_operation = storage_client.storage_accounts.create( self.args.resource_group, self.args.storage_account, StorageAccountCreateParameters( sku=Sku(name=SkuName.standard_ragrs), kind=Kind.storage, location=self.args.location)) storage_account = storage_async_operation.result() print("Creating storage account: " + self.args.storage_account) return storage_account
def set_storage_account_properties( resource_group_name, account_name, sku=None, tags=None, custom_domain=None, encryption=None, access_tier=None): ''' Update storage account property (only one at a time).''' from azure.mgmt.storage.models import \ (StorageAccountUpdateParameters, Sku, CustomDomain, Encryption, AccessTier) scf = storage_client_factory() params = StorageAccountUpdateParameters( sku=Sku(sku) if sku else None, tags=tags, custom_domain=CustomDomain(custom_domain) if custom_domain else None, encryption=encryption, access_tier=AccessTier(access_tier) if access_tier else None) return scf.storage_accounts.update(resource_group_name, account_name, params)
def create_storage_account(self, location, resource_group_name, account_name): try: return self.storage_client.storage_accounts.begin_create( resource_group_name, account_name, StorageAccountCreateParameters( sku=Sku(name=SkuName.standard_ragrs), kind=Kind.storage, location=location, enable_https_traffic_only=True, ), ) except ClientException as exc: raise AzureBackendError(exc)
def create_storage_account(resource_group_name, account_name, location, account_type, tags=None): ''' Create a storage account. ''' from azure.mgmt.storage.models import StorageAccountCreateParameters, Sku scf = storage_client_factory() # TODO Add the other new params from rc5 # https://github.com/Azure/azure-sdk-for-python/blob/v2.0.0rc5/ # azure-mgmt-storage/azure/mgmt/storage/models/storage_account_create_parameters.py # accountType is now called sku.name also. params = StorageAccountCreateParameters(Sku(account_type), 'Storage', location, tags) return scf.storage_accounts.create(resource_group_name, account_name, params)
def create_storage_account(resource_group_name, account_name, sku, location, kind=Kind.storage.value, tags=None, custom_domain=None, encryption=None, access_tier=None): ''' Create a storage account. ''' from azure.mgmt.storage.models import \ (StorageAccountCreateParameters, Sku, CustomDomain, Encryption, AccessTier) scf = storage_client_factory() params = StorageAccountCreateParameters( sku=Sku(sku), kind=Kind(kind), location=location, tags=tags, custom_domain=CustomDomain(custom_domain) if custom_domain else None, encryption=encryption, access_tier=AccessTier(access_tier) if access_tier else None) return scf.storage_accounts.create(resource_group_name, account_name, params)
def create_storage_account(credentials, subscription_id, **kwargs): """ Create a Storage account :param credentials: msrestazure.azure_active_directory.AdalAuthentication :param subscription_id: str :param **resource_group: str :param **storage_account: str :param **region: str """ storage_management_client = StorageManagementClient(credentials, subscription_id) storage_account = storage_management_client.storage_accounts.create( resource_group_name=kwargs.get("resource_group", DefaultSettings.resource_group), account_name=kwargs.get("storage_account", DefaultSettings.storage_account), parameters=StorageAccountCreateParameters( sku=Sku(SkuName.standard_lrs), kind=Kind.storage, location=kwargs.get('region', DefaultSettings.region))) return storage_account.result().id
def set_storage_account_properties(resource_group_name, account_name, account_type=None, tags='', custom_domain=None): ''' Update storage account property (only one at a time). :param str custom_domain:the custom domain name ''' from azure.mgmt.storage.models import StorageAccountUpdateParameters, CustomDomain, Sku scf = storage_client_factory() # TODO Add the new params encryption and access_tier after rc5 update sku = Sku(account_type) if account_type else None params = StorageAccountUpdateParameters(sku=sku, tags=tags, custom_domain=custom_domain) return scf.storage_accounts.update(resource_group_name, account_name, params)
def create_storage(self): """Function that creates a new storage account :raises: :class:`Exception` """ if not self._resource_management_integration_service\ .resource_group_exists( self._vdc_storage_account_resource_group): self._logger.info( 'No resource group: {} found, provisioning one.'.format( self._vdc_storage_account_resource_group)) self._resource_management_integration_service\ .create_or_update_resource_group( self._vdc_storage_account_resource_group, self._location) self._logger.info('Attempting authentication.') parameters: StorageAccountCreateParameters encryptionService = EncryptionService(enabled=True) encryptionServices = EncryptionServices(blob=encryptionService) encryption = Encryption(services=encryptionServices) parameters = StorageAccountCreateParameters( sku=Sku(name='Standard_LRS'), kind='BlobStorage', location=self._location, encryption=encryption, access_tier='Cool', enable_https_traffic_only=True) self._logger.info( 'creating storage account using rg: {} and account name: {}'. format(self._vdc_storage_account_resource_group, self._vdc_storage_account_name)) async_operation = self._storage_management_client.storage_accounts.create( self._vdc_storage_account_resource_group, self._vdc_storage_account_name, parameters) async_operation.wait() self._logger.info('vdc storage created')
def _create_storage_account(self, credentials, subscription_id, resource_group, name, sku, location): """ Creates requested storage account on Azure. Returns storage id, a url endpoint and single key """ from azure.mgmt.storage.models import StorageAccountCreateParameters, Kind, Sku storage_client = azstorage_mgmt.StorageManagementClient( credentials, subscription_id) storage_async_operation = storage_client.storage_accounts.create( resource_group_name=resource_group, account_name=name, parameters=StorageAccountCreateParameters(sku=Sku(name=sku), kind=Kind.storage, location=location)) storage_account = storage_async_operation.result() storage_keys = storage_client.storage_accounts.list_keys( resource_group_name=resource_group, account_name=name) return (storage_account.id, storage_account.name, storage_keys.keys[0].value)
def _create_auto_storage_account(storage_client, resource_group, location): """Creates new auto storage account in the given resource group and location :param StorageManagementClient storage_client: storage client. :param str resource_group: name of the resource group. :param str location: location. :return str: name of the created storage account. """ from azure.mgmt.storage.models import Kind, Sku, SkuName name = _generate_auto_storage_account_name() check = storage_client.storage_accounts.check_name_availability(name) while not check.name_available: name = _generate_auto_storage_account_name() check = storage_client.storage_accounts.check_name_availability(name).name_available storage_client.storage_accounts.create(resource_group, name, { 'sku': Sku(SkuName.standard_lrs), 'kind': Kind.storage, 'location': location}).result() return name
def create_storage_account( self, sa_name, sa_group, location, kind="storage_v2", sku_name="standard_lrs", timeout=120, ): """ Create Storage Account with given parameters. Args: sa_name (str): Azure Storage Account name sa_group (str): Azure Storage Account resource group location (str): Azure location kind (str): Storage Account kind; available kinds: * Storage, * StorageV2, * BlobStorage sku_name (str): Sku name for SA. Available options: * standard_lrs * standard_grs * standard_ragrs * standard_zrs * premium_lrs timeout (int): operation timeout (in seconds) """ self.storage_acc_name = sa_name self.storage_acc_group = sa_group storage_async_operation = self.storage_client.storage_accounts.create( self.storage_acc_group, self.storage_acc_name, StorageAccountCreateParameters(sku=Sku(name=SkuName[sku_name]), kind=Kind[kind], location=location), ) self._changed_properties["storage_acc_key_1"] = True self._changed_properties["storage_acc_key_2"] = True self._changed_properties["storage_acc_name"] = True return storage_async_operation.result(timeout=timeout)
def create_storage(resource_group: str, account_name: str, location: str) -> str: params = StorageAccountCreateParameters( sku=Sku(name=SkuName.premium_lrs), kind=Kind.block_blob_storage, location=location, tags={"storage_type": "corpus"}, access_tier=AccessTier.hot, allow_blob_public_access=False, minimum_tls_version="TLS1_2", ) client = get_client_from_cli_profile(StorageManagementClient) account = client.storage_accounts.create(resource_group, account_name, params).result() if account.provisioning_state != "Succeeded": raise Exception( "storage account creation failed: %s", json.dumps(account.as_dict(), indent=4, sort_keys=True), ) return account.id
def update_storage_account(instance, sku=None, tags=None, custom_domain=None, encryption=None, access_tier=None): from azure.mgmt.storage.models import \ (StorageAccountCreateParameters, Sku, CustomDomain, AccessTier) params = StorageAccountCreateParameters( sku=Sku(sku) if sku is not None else instance.sku, kind=instance.kind, location=instance.location, tags=tags if tags is not None else instance.tags, custom_domain=CustomDomain(custom_domain) if custom_domain is not None else instance.custom_domain, # pylint: disable=line-too-long encryption=encryption if encryption is not None else instance.encryption, access_tier=AccessTier(access_tier) if access_tier is not None else instance.access_tier) return params
def createStorageAccount(self, resourceGroupName, storageAccountName, resourceGroupLocation, subscriptionId): logging.info("Creating new Storage Account with Name: " + storageAccountName + " and Location: " + resourceGroupLocation) storageClient = self.getStorageManagementClient(subscriptionId) check = self.__checkStorageAccountExists(storageAccountName, storageClient) if check: logging.info("Storage Account with Name: " + storageAccountName + " and Location: " + resourceGroupLocation + " already exists.") return self.getStorageAccount(resourceGroupName, storageAccountName, subscriptionId) storage_async_operation = storageClient.storage_accounts.create( resourceGroupName, storageAccountName, StorageAccountCreateParameters( sku=Sku(name=SkuName.standard_lrs), kind=Kind.storage_v2, location=resourceGroupLocation, supportsHttpsTrafficOnly=True ) ) storageAccount = storage_async_operation.result() logging.info("Storage account created successfully with Name: " + storageAccountName + " and Location: " + resourceGroupLocation) return storageAccount
def create_storage_account_if_not_exists(self, region, resource_group_name, storage_account_name): """Creates the storage account if it does not exist. In either case, returns the StorageAccount class that matches the given arguments.""" storage_accounts = (self.storage_client.storage_accounts. list_by_resource_group(resource_group_name)) storage_account = next( filter( lambda storage_account: storage_account.name == storage_account_name, storage_accounts), None) if storage_account: return storage_account logging.info( "Creating Azure Storage account '{}' in Resource Group '{}'". format(storage_account_name, resource_group_name)) storage_async_operation = self.storage_client.storage_accounts.create( resource_group_name, storage_account_name, StorageAccountCreateParameters( sku=Sku(name=SkuName.standard_ragrs), kind=Kind.storage, location=region)) return storage_async_operation.result()
def create(cls, auth, location, group_name, account_name, account_kind, account_type, access_tier=None): '''Factory method: create an instance when the account does not exist. ''' client = auth.StorageManagementClient() kwargs = {} if account_kind == 'BlobStorage': kwargs['access_tier'] = access_tier params = StorageAccountCreateParameters(Sku(account_type), account_kind, location, **kwargs) request = client.storage_accounts.create(group_name, account_name, params) acc = request.result() key_list = client.storage_accounts.list_keys(group_name, account_name) return cls(acc, key_list.keys[0].value)
def update_storage_account(instance, sku=None, tags=None, custom_domain=None, use_subdomain=None, encryption=None, access_tier=None): from azure.mgmt.storage.models import \ (StorageAccountUpdateParameters, Sku, CustomDomain, AccessTier) domain = instance.custom_domain if custom_domain is not None: domain = CustomDomain(custom_domain) if use_subdomain is not None: domain.name = use_subdomain == 'true' params = StorageAccountUpdateParameters( sku=Sku(sku) if sku is not None else instance.sku, tags=tags if tags is not None else instance.tags, custom_domain=domain, encryption=encryption if encryption is not None else instance.encryption, access_tier=AccessTier(access_tier) if access_tier is not None else instance.access_tier) return params
def run_example(): """Storage management example.""" # # Create the Resource Manager Client with an Application (service principal) token provider # credentials, subscription_id = get_credentials() resource_client = ResourceManagementClient(credentials, subscription_id) storage_client = StorageManagementClient(credentials, subscription_id) # You MIGHT need to add Storage as a valid provider for these credentials # If so, this operation has to be done only once for each credentials resource_client.providers.register('Microsoft.Storage') # Create Resource group print('Create Resource Group') resource_group_params = {'location':'westus'} print_item(resource_client.resource_groups.create_or_update(GROUP_NAME, resource_group_params)) # Check availability print('Check name availability') bad_account_name = 'invalid-or-used-name' availability = storage_client.storage_accounts.check_name_availability(bad_account_name) print('The account {} is available: {}'.format(bad_account_name, availability.name_available)) print('Reason: {}'.format(availability.reason)) print('Detailed message: {}'.format(availability.message)) print('\n\n') # Create a storage account print('Create a storage account') storage_async_operation = storage_client.storage_accounts.create( GROUP_NAME, STORAGE_ACCOUNT_NAME, StorageAccountCreateParameters( sku=Sku(SkuName.standard_ragrs), kind=Kind.storage, location='westus' ) ) storage_account = storage_async_operation.result() print_item(storage_account) print('\n\n') # Get storage account properties print('Get storage account properties') storage_account = storage_client.storage_accounts.get_properties( GROUP_NAME, STORAGE_ACCOUNT_NAME) print_item(storage_account) print("\n\n") # List Storage accounts print('List storage accounts') for item in storage_client.storage_accounts.list(): print_item(item) print("\n\n") # List Storage accounts by resource group print('List storage accounts by resource group') for item in storage_client.storage_accounts.list_by_resource_group(GROUP_NAME): print_item(item) print("\n\n") # Get the account keys print('Get the account keys') storage_keys = storage_client.storage_accounts.list_keys(GROUP_NAME, STORAGE_ACCOUNT_NAME) storage_keys = {v.key_name: v.value for v in storage_keys.keys} print('\tKey 1: {}'.format(storage_keys['key1'])) print('\tKey 2: {}'.format(storage_keys['key2'])) print("\n\n") # Regenerate the account key 1 print('Regenerate the account key 1') storage_keys = storage_client.storage_accounts.regenerate_key( GROUP_NAME, STORAGE_ACCOUNT_NAME, 'key1') storage_keys = {v.key_name: v.value for v in storage_keys.keys} print('\tNew key 1: {}'.format(storage_keys['key1'])) print("\n\n") # Update storage account print('Update storage account') storage_account = storage_client.storage_accounts.update( GROUP_NAME, STORAGE_ACCOUNT_NAME, StorageAccountUpdateParameters( sku=Sku(SkuName.standard_grs) ) ) print_item(storage_account) print("\n\n") # Delete the storage account print('Delete the storage account') storage_client.storage_accounts.delete(GROUP_NAME, STORAGE_ACCOUNT_NAME) print("\n\n") # Delete Resource group and everything in it print('Delete Resource Group') delete_async_operation = resource_client.resource_groups.delete(GROUP_NAME) delete_async_operation.wait() print("Deleted: {}".format(GROUP_NAME)) print("\n\n") # List usage print('List usage') for usage in storage_client.usage.list(): print('\t{}'.format(usage.name.value))
workspace_name = os.environ["workspace_name"] # Create Azure Credential object credentials = ServicePrincipalCredentials(client_id=client_id, secret=secret, tenant=tenant) client = ResourceManagementClient(credentials, subscription_id) # Create Resource Group resource_group_param = {"location": location} client.resource_groups.create_or_update(resource_group, resource_group_param) # Create Azure Storage Account storage_account_param = StorageAccountCreateParameters( sku=Sku(name=SkuName.standard_ragrs), kind=Kind.storage, location=location) storage_client = StorageManagementClient(credentials, subscription_id) storage_async_operation = storage_client.storage_accounts.create( resource_group, storage_account_name, storage_account_param) storage_account = storage_async_operation.result() # Create Azure Keyvault key_vault_params = { 'location': location, 'properties': { 'sku': { 'family': 'A', 'name': 'standard' }, 'tenantId': tenant, 'accessPolicies': [],