Skip to content

Commit 8037302

Browse files
authored
Merge pull request Azure#17 from mjain2/arde/removeDuplicateRGfromMySQL
Refactoring flexible server create
2 parents e69b330 + ba74bd7 commit 8037302

File tree

4 files changed

+161
-134
lines changed

4 files changed

+161
-134
lines changed

src/azure-cli/azure/cli/command_modules/rdbms/_flexible_server_util.py

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -65,8 +65,6 @@ def generate_password(administrator_login_password):
6565
administrator_login_password = secrets.token_urlsafe(passwordLength)
6666
random_position = random.randint(1, len(administrator_login_password)-1)
6767
administrator_login_password = administrator_login_password[:random_position] + special_character + administrator_login_password[random_position + 1:]
68-
#password_character = string.ascii_letters + string.digits + '!@#,?;:$&*' # Allowing limited punctuations to avoid unicode errors
69-
#administrator_login_password = "".join(random.choice(password_character) for i in range(passwordLength))
7068
return administrator_login_password
7169

7270

@@ -95,9 +93,12 @@ def create_firewall_rule(db_context, cmd, resource_group_name, server_name, star
9593
if start_ip == '0.0.0.0' and end_ip == '0.0.0.0':
9694
logger.warning('Configuring server firewall rule, \'azure-access\', to accept connections from all '
9795
'Azure resources...')
96+
firewall_name = 'AllowAllAzureServicesAndResourcesWithinAzureIps_{}-{}-{}_{}-{}-{}'.format(now.year, now.month, now.day, now.hour, now.minute, now.second)
9897
elif start_ip == end_ip:
9998
logger.warning('Configuring server firewall rule to accept connections from \'%s\'...', start_ip)
10099
else:
100+
if start_ip == '0.0.0.0' and end_ip == '255.255.255.255':
101+
firewall_name = 'AllowAll_{}-{}-{}_{}-{}-{}'.format(now.year, now.month, now.day, now.hour, now.minute, now.second)
101102
logger.warning('Configuring server firewall rule to accept connections from \'%s\' to \'%s\'...', start_ip, end_ip)
102103
firewall_client = cf_firewall(cmd.cli_ctx, None)
103104
'''
@@ -148,6 +149,7 @@ def parse_maintenance_window(maintenance_window_string):
148149
return parsed_input[0], parsed_input[1], parsed_input[2]
149150
return None, None, None
150151

152+
151153
def _update_location(cmd, resource_group_name):
152154
resource_client = resource_client_factory(cmd.cli_ctx)
153155
rg = resource_client.resource_groups.get(resource_group_name)

src/azure-cli/azure/cli/command_modules/rdbms/flexible_server_custom_mysql.py

Lines changed: 81 additions & 68 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@
1515
from ._client_factory import get_mysql_flexible_management_client, cf_mysql_flexible_firewall_rules, cf_mysql_flexible_db
1616
from ._flexible_server_util import resolve_poller, generate_missing_parameters, create_vnet, create_firewall_rule, \
1717
parse_public_access_input, update_kwargs, generate_password, parse_maintenance_window
18-
from .flexible_server_custom_common import user_confirmation
18+
from .flexible_server_custom_common import user_confirmation, _server_list_custom_func
1919

2020
logger = get_logger(__name__)
2121
DEFAULT_DB_NAME = 'flexibleserverdb'
@@ -28,76 +28,87 @@ def _flexible_server_create(cmd, client, resource_group_name=None, server_name=N
2828
backup_retention=None, tags=None, public_access=None, database_name=None,
2929
subnet_arm_resource_id=None, high_availability=None, zone=None, assign_identity=False):
3030
from azure.mgmt.rdbms import mysql
31-
db_context = DbContext(
32-
azure_sdk=mysql, cf_firewall=cf_mysql_flexible_firewall_rules, cf_db=cf_mysql_flexible_db, logging_name='MySQL', command_group='mysql', server_client=client)
33-
34-
subnet_id = firewall_id = None
35-
36-
if subnet_arm_resource_id is not None:
37-
subnet_id = subnet_arm_resource_id # set the subnet id to be the one passed in
38-
delegated_subnet_arguments = mysql.flexibleservers.models.DelegatedSubnetArguments(
39-
subnet_arm_resource_id=subnet_id
40-
)
41-
else:
42-
delegated_subnet_arguments = None
43-
44-
location, resource_group_name, server_name = generate_missing_parameters(cmd, location, resource_group_name, server_name)
4531
try:
46-
# The server name already exists in the resource group
47-
server_result = client.get(resource_group_name, server_name)
48-
logger.warning('Found existing MySQL Server \'%s\' in group \'%s\'',
49-
server_name, resource_group_name)
32+
db_context = DbContext(
33+
azure_sdk=mysql, cf_firewall=cf_mysql_flexible_firewall_rules, cf_db=cf_mysql_flexible_db, logging_name='MySQL', command_group='mysql', server_client=client)
34+
35+
# Raise error when user passes values for both parameters
36+
if subnet_arm_resource_id is not None and public_access is not None:
37+
raise CLIError("Incorrect usage : A combination of the parameters --subnet "
38+
"and --public_access is invalid. Use either one of them.")
39+
server_result = firewall_id = subnet_id = None
40+
41+
# Populate desired parameters
42+
location, resource_group_name, server_name = generate_missing_parameters(cmd, location, resource_group_name, server_name)
43+
44+
# Get list of servers in the current sub
45+
server_list = _server_list_custom_func(client)
46+
47+
# Ensure that the server name is not in the rg and in the subscription
48+
for key in server_list:
49+
if server_name == key.name and key.id.find(resource_group_name) != -1:
50+
logger.warning('Found existing MySQL server \'%s\' in group \'%s\'',
51+
server_name, resource_group_name)
52+
server_result = client.get(resource_group_name, server_name)
53+
elif server_name == key.name:
54+
raise CLIError("The server name '{}' exists in this subscription.Please re-run command with a "
55+
"valid server name.".format(server_name))
5056

51-
except CloudError:
5257
administrator_login_password = generate_password(administrator_login_password)
53-
if public_access is None and subnet_arm_resource_id is None:
54-
subnet_id = create_vnet(cmd, server_name, location, resource_group_name, "Microsoft.DBforMySQL/flexibleServers")
55-
delegated_subnet_arguments=mysql.flexibleservers.models.DelegatedSubnetArguments(
56-
subnet_arm_resource_id=subnet_id
57-
)
58-
59-
# Create mysql server
60-
# Note : passing public_access has no effect as the accepted values are 'Enabled' and 'Disabled'. So the value ends up being ignored.
61-
server_result = _create_server(
62-
db_context, cmd, resource_group_name, server_name, location, backup_retention, sku_name, storage_mb,
63-
administrator_login, administrator_login_password, version, tags, public_access, assign_identity,
64-
tier, high_availability, zone, delegated_subnet_arguments)
65-
66-
if public_access is not None:
67-
if public_access == 'on':
68-
start_ip, end_ip = '0.0.0.0', '255.255.255.255'
58+
if server_result is None:
59+
# If subnet is provided, use that subnet to create the server, else create subnet if public access is not enabled.
60+
if subnet_arm_resource_id is not None:
61+
subnet_id = subnet_arm_resource_id # set the subnet id to be the one passed in
62+
delegated_subnet_arguments = mysql.flexibleservers.models.DelegatedSubnetArguments(
63+
subnet_arm_resource_id=subnet_id)
64+
elif public_access is None and subnet_arm_resource_id is None:
65+
subnet_id = create_vnet(cmd, server_name, location, resource_group_name,
66+
"Microsoft.DBforPostgreSQL/flexibleServers")
67+
delegated_subnet_arguments = mysql.flexibleservers.models.DelegatedSubnetArguments(
68+
subnet_arm_resource_id=subnet_id)
6969
else:
70-
start_ip, end_ip = parse_public_access_input(public_access)
71-
firewall_id = create_firewall_rule(db_context, cmd, resource_group_name, server_name, start_ip, end_ip)
72-
73-
# Create mysql database if it does not exist
74-
if database_name is None:
75-
database_name = DEFAULT_DB_NAME
76-
_create_database(db_context, cmd, resource_group_name, server_name, database_name)
77-
78-
user = server_result.administrator_login
79-
id = server_result.id
80-
loc = server_result.location
81-
version = server_result.version
82-
sku = server_result.sku.name
83-
84-
# This is a workaround for getting the hostname right .
85-
# Without Vnet, the hostname returned by the API os <servername>.postgres.database.azure.com
86-
# with Vnet enabled, the hostname returned by the API is <servername>.<servername>.postgres.database.azure.com
87-
if len(server_result.fully_qualified_domain_name.split('.')) != 6:
70+
delegated_subnet_arguments = None
71+
72+
# Create mysql server
73+
# Note : passing public_access has no effect as the accepted values are 'Enabled' and 'Disabled'. So the value ends up being ignored.
74+
server_result = _create_server(db_context, cmd, resource_group_name, server_name, location, backup_retention,
75+
sku_name, tier, storage_mb, administrator_login, administrator_login_password,
76+
version, tags, delegated_subnet_arguments, assign_identity, public_access,
77+
high_availability, zone)
78+
79+
# Adding firewall rule
80+
if public_access is not None and str(public_access).lower() != 'none':
81+
if str(public_access).lower() == 'all':
82+
start_ip, end_ip = '0.0.0.0', '255.255.255.255'
83+
else:
84+
start_ip, end_ip = parse_public_access_input(public_access)
85+
firewall_id = create_firewall_rule(db_context, cmd, resource_group_name, server_name, start_ip, end_ip)
86+
87+
# Create mysql database if it does not exist
88+
if database_name is None:
89+
database_name = DEFAULT_DB_NAME
90+
_create_database(db_context, cmd, resource_group_name, server_name, database_name)
91+
92+
user = server_result.administrator_login
93+
id = server_result.id
94+
loc = server_result.location
95+
version = server_result.version
96+
sku = server_result.sku.name
8897
host = server_result.fully_qualified_domain_name
89-
else:
90-
host = server_result.fully_qualified_domain_name[(server_result.fully_qualified_domain_name.index('.')) + 1:]
9198

92-
logger.warning('Make a note of your password. If you forget, you would have to' \
93-
' reset your password with \'az mysql flexible-server update -n %s -g %s -p <new-password>\'.', server_name, resource_group_name)
99+
logger.warning('Make a note of your password. If you forget, you would have to' \
100+
' reset your password with \'az mysql flexible-server update -n %s -g %s -p <new-password>\'.',
101+
server_name, resource_group_name)
94102

95-
_update_local_contexts(cmd, server_name, resource_group_name, location)
103+
_update_local_contexts(cmd, server_name, resource_group_name, location, user)
96104

97-
return _form_response(user, sku, loc, id, host, version,
98-
administrator_login_password if administrator_login_password is not None else '*****',
99-
_create_mysql_connection_string(host, database_name, user, administrator_login_password), database_name, firewall_id, subnet_id
100-
)
105+
return _form_response(user, sku, loc, id, host, version,
106+
administrator_login_password if administrator_login_password is not None else '*****',
107+
_create_mysql_connection_string(host, database_name, user, administrator_login_password),
108+
database_name, firewall_id, subnet_id)
109+
110+
except Exception as ex: # pylint: disable=broad-except
111+
logger.error(ex)
101112

102113

103114
def _flexible_server_restore(cmd, client, resource_group_name, server_name, source_server, restore_point_in_time, location=None, no_wait=False):
@@ -297,9 +308,9 @@ def _flexible_list_skus(client, location):
297308
return client.list(location)
298309

299310

300-
def _create_server(db_context, cmd, resource_group_name, server_name, location, backup_retention, sku_name,
301-
storage_mb, administrator_login, administrator_login_password, version, tags, public_network_access,
302-
assign_identity, tier, ha_enabled, availability_zone, delegated_subnet_arguments):
311+
def _create_server(db_context, cmd, resource_group_name, server_name, location, backup_retention, sku_name, tier,
312+
storage_mb, administrator_login, administrator_login_password, version, tags, delegated_subnet_arguments,
313+
assign_identity, public_network_access, ha_enabled, availability_zone):
303314

304315
logging_name, azure_sdk, server_client = db_context.logging_name, db_context.azure_sdk, db_context.server_client
305316
logger.warning('Creating %s Server \'%s\' in group \'%s\'...', logging_name, server_name, resource_group_name)
@@ -355,7 +366,7 @@ def _create_mysql_connection_strings(host, user, password, database):
355366
"spring.datasource.password={password}",
356367
'node.js': "var conn = mysql.createConnection({{host: '{host}', user: '{user}', "
357368
"password: {password}, database: {database}, port: 3306}});",
358-
'php': "host={host} port=5432 dbname={database} user={user} password={password}",
369+
'php': "host={host} port=3306 dbname={database} user={user} password={password}",
359370
'python': "cnx = mysql.connector.connect(user='{user}', password='{password}', host='{host}', "
360371
"port=3306, database='{database}')",
361372
'ruby': "client = Mysql2::Client.new(username: '{user}', password: '{password}', "
@@ -393,13 +404,15 @@ def _form_response(username, sku, location, id, host, version, password, connect
393404
return output
394405

395406

396-
def _update_local_contexts(cmd, server_name, resource_group_name, location):
407+
def _update_local_contexts(cmd, server_name, resource_group_name, location, user):
397408
if cmd.cli_ctx.local_context.is_on:
398409
cmd.cli_ctx.local_context.set(['mysql flexible-server'], 'server_name',
399410
server_name) # Setting the server name in the local context
400411
cmd.cli_ctx.local_context.set([ALL], 'location',
401412
location) # Setting the location in the local context
402413
cmd.cli_ctx.local_context.set([ALL], 'resource_group_name', resource_group_name)
414+
cmd.cli_ctx.local_context.set(['mysql flexible-server'], 'administrator_login',
415+
user) # Setting the server name in the local context
403416

404417

405418
def _create_database(db_context, cmd, resource_group_name, server_name, database_name):

0 commit comments

Comments
 (0)