def test_resize_action(self, update_mock): p = self.load_policy({ 'name': 'resize-sqldatabase', 'resource': 'azure.sqldatabase', 'filters': [ { 'type': 'value', 'key': 'name', 'value': 'cctestdb' } ], 'actions': [ { 'type': 'resize', 'tier': 'Standard', 'capacity': 100, 'max_size_bytes': 21474836480 } ], }) self.resources = p.run() self.assertEqual(len(self.resources), 1) self.assertEqual(self.resources[0]['name'], 'cctestdb') parent_id = ResourceIdParser.get_resource_name(self.resources[0]['c7n:parent-id']) expected_db_update = DatabaseUpdate(sku=Sku(capacity=100, tier='Standard', name='Standard'), max_size_bytes=21474836480) update_mock.assert_called_once() name, args, kwargs = update_mock.mock_calls[0] self.assertEqual('test_sqlserver', args[0]) self.assertEqual(parent_id, args[1]) self.assertEqual('cctestdb', args[2]) self.assertEqual(expected_db_update, args[3])
def _process_resource(self, database): sku = Sku(capacity=self.capacity, tier=self.tier, name=self.tier) max_size_bytes = self.max_size_bytes if not 0 else database[ 'properties']['maxSizeBytes'] self.client.databases.update( database['resourceGroup'], ResourceIdParser.get_resource_name(database['c7n:parent-id']), database['name'], DatabaseUpdate(sku=sku, max_size_bytes=max_size_bytes))
def __init__(self, sql_credentials: SQLCredentials, identity: Identity, **options): self.sql_credentials = sql_credentials self.default_RG = options.get( 'resource_group_name') or "default_rg_python" self.region = options.get('region') or "westus" self.sku = options.get('sku') or Sku(name='Free') self.db_object = None self.resource_client = identity.resource_client self.sql_client = SqlManagementClient(identity.credentials, identity.subscription_id)
def test_resize_action(self): p = self.load_policy({ 'name': 'resize-sqldatabase', 'resource': 'azure.sqldatabase', 'filters': [{ 'type': 'value', 'key': 'name', 'value': 'cctestdb' }], 'actions': [{ 'type': 'resize', 'tier': 'Standard', 'capacity': 100, 'max_size_bytes': 21474836480 }], }) self.resources = p.run() self.assertEqual(len(self.resources), 1) self.assertEqual(self.resources[0]['name'], 'cctestdb') updated_database = self.client.databases.get( 'test_sqlserver', ResourceIdParser.get_resource_name( self.resources[0]['c7n:parent-id']), 'cctestdb') self.assertEqual(updated_database.sku.capacity, 100) self.assertEqual(updated_database.sku.tier, 'Standard') # The value for max_size_bytes returned by api is stale, # so we can't make an assertion until it's fixed # self.assertEqual(database.max_size_bytes, 21474836480) # Revert action self.client.databases.update( 'test_sqlserver', ResourceIdParser.get_resource_name( self.resources[0]['c7n:parent-id']), 'cctestdb', DatabaseUpdate(sku=Sku(capacity=125, tier='Premium', name='Premium'), max_size_bytes=2147483648))
def define_sku(self, name='Free', tier='Free', size=None, family=None, capacity=None): """ Define the sku of the DB you want to create. By default it will create free DB. :param name: Required. The name of the SKU, typically, a letter + Number code, e.g. P3. :param tier: The tier or edition of the particular SKU, e.g. Basic, Premium. :param size: Size of the SKU :param family: If the service has different generations of hardware, for the same SKU, then that can be captured here. :param capacity: Capacity of the SKU :return: """ self.sku = Sku(name=name, tier=tier, size=size, family=family, capacity=capacity)
def create_database(cmd, database_provider, name, location, admin, password): database_settings = {} if database_provider.lower() == 'mysql': server_client = cf_mysql_servers(cmd.cli_ctx, None) database_client = cf_mysql_db(cmd.cli_ctx, None) admin = admin[:16] database_settings['engine'] = 'django.db.backends.mysql' def server_creator(): sku_name = 'B_Gen5_1' parameters = ServerForCreate( sku=MySqlSku(name=sku_name), location=location, properties=ServerPropertiesForDefaultCreate( administrator_login=admin, administrator_login_password=password, version='5.7', ssl_enforcement='Enabled', storage_profile=StorageProfile( backup_retention_days=0, geo_redundant_backup='Disabled', storage_mb=5120))) return server_client.create(resource_group_name=name, server_name=name, parameters=parameters) def database_creator(): return database_client.create_or_update(resource_group_name=name, server_name=name, database_name=name) elif database_provider.lower() == 'cosmosdb' or database_provider.lower( ) == 'mongodb': from azure.mgmt.cosmosdb import CosmosDB cosmosdb_client = get_mgmt_service_client(cmd.cli_ctx, CosmosDB) from azure.mgmt.cosmosdb.models import ( DatabaseAccountCreateUpdateParameters, DatabaseAccountKind, Location, ConsistencyPolicy) def server_creator(): params = DatabaseAccountCreateUpdateParameters( location=location, locations=[ Location(location_name=location, failover_priority=0, is_zone_redundant=False) ], kind=DatabaseAccountKind.mongo_db.value, consistency_policy=ConsistencyPolicy( default_consistency_level=1, max_staleness_prefix=100, max_interval_in_seconds=5)) return cosmosdb_client.database_accounts.create_or_update( name, name, params) def database_creator(): return cosmosdb_client.database_accounts.create_update_mongo_db_database( resource_group_name=name, account_name=name, database_name=name, resource={'id': name}, options={}) else: sql_client = get_sql_management_client(cmd.cli_ctx) sql_parameters = { 'location': location, # "self.region" is 'west-us' by default 'version': '12.0', 'administrator_login': admin, 'administrator_login_password': password } sku = Sku(capacity=10, name='Standard', tier='Standard') def server_creator(): return sql_server_create(sql_client.servers, name, name, **sql_parameters) def database_creator(): return sql_database_create(cmd, sql_client.databases, database_name=name, server_name=name, resource_group_name=name, location=location, sku=sku, elastic_pool_id=None) wrapper = DatabaseCreator(database_creator) poller = server_creator() poller.add_done_callback(wrapper.create_database) # poller.add_done_callback(print(poller.result())) return wrapper
def exec_module(self, **kwargs): """Main module execution method""" for key in list(self.module_arg_spec.keys()) + ['tags']: if hasattr(self, key): setattr(self, key, kwargs[key]) elif kwargs[key] is not None: if key == "location": self.parameters["location"] = kwargs[key] elif key == "collation": self.parameters["collation"] = kwargs[key] elif key == "create_mode": self.parameters["create_mode"] = _snake_to_camel( kwargs[key], True) elif key == "source_database_id": self.parameters["source_database_id"] = kwargs[key] elif key == "source_database_deletion_date": self.parameters["source_database_deletion_date"] = kwargs[key] elif key == "restore_point_in_time": self.parameters["restore_point_in_time"] = kwargs[key] elif key == "recovery_services_recovery_point_resource_id": self.parameters["recovery_services_recovery_point_resource_id"] = kwargs[key] elif key == "edition": ev = get_sku_name(kwargs[key]) self.parameters["sku"] = Sku(name=ev) elif key == "sku": ev = kwargs[key] self.parameters["sku"] = Sku( name=ev['name'], tier=ev['tier'], size=ev['size'], family=ev['family'], capacity=ev['capacity']) elif key == "max_size_bytes": self.parameters["max_size_bytes"] = kwargs[key] elif key == "elastic_pool_name": self.parameters["elastic_pool_id"] = kwargs[key] elif key == "read_scale": self.parameters["read_scale"] = 'Enabled' if kwargs[key] else 'Disabled' elif key == "sample_name": ev = kwargs[key] if ev == 'adventure_works_lt': ev = 'AdventureWorksLT' self.parameters["sample_name"] = ev elif key == "zone_redundant": self.parameters["zone_redundant"] = True if kwargs[key] else False old_response = None response = None resource_group = self.get_resource_group(self.resource_group) if "location" not in self.parameters: self.parameters["location"] = resource_group.location if "elastic_pool_id" in self.parameters: self.format_elastic_pool_id() old_response = self.get_sqldatabase() if not old_response: self.log("SQL Database instance doesn't exist") if self.state == 'absent': self.log("Old instance didn't exist") else: self.to_do = Actions.Create else: self.log("SQL Database instance already exists") if self.state == 'absent': self.to_do = Actions.Delete elif self.state == 'present': self.log( "Need to check if SQL Database instance has to be deleted or may be updated") if ('location' in self.parameters) and (self.parameters['location'] != old_response['location']): self.to_do = Actions.Update if (('read_scale' in self.parameters) and (self.parameters['read_scale'] != old_response['read_scale'])): self.to_do = Actions.Update if (('max_size_bytes' in self.parameters) and (self.parameters['max_size_bytes'] != old_response['max_size_bytes'])): self.to_do = Actions.Update if (('sku' in self.parameters) and (self.parameters['sku'] != old_response['sku'])): self.to_do = Actions.Update update_tags, newtags = self.update_tags( old_response.get('tags', dict())) if update_tags: self.tags = newtags self.to_do = Actions.Update if (self.to_do == Actions.Create) or (self.to_do == Actions.Update): self.log("Need to Create / Update the SQL Database instance") if self.check_mode: self.results['changed'] = True return self.results self.parameters['tags'] = self.tags response = self.create_update_sqldatabase() if not old_response: self.results['changed'] = True else: self.results['changed'] = old_response.__ne__(response) self.log("Creation / Update done") elif self.to_do == Actions.Delete: self.log("SQL Database instance deleted") self.results['changed'] = True if self.check_mode: return self.results self.delete_sqldatabase() # make sure instance is actually deleted, for some Azure resources, instance is hanging around # for some time after deletion -- this should be really fixed in Azure while self.get_sqldatabase(): time.sleep(20) else: self.log("SQL Database instance unchanged") self.results['changed'] = False response = old_response if response: self.results["id"] = response["id"] self.results["database_id"] = response["database_id"] self.results["status"] = response["status"] return self.results