def build_output_deployment_resource(key, property_name, property_provider, property_type, parent_name=None, output_type='object', path=None): from azure.cli.core.util import random_string output_tb = ArmTemplateBuilder() output_tb.add_output(key, property_name, property_provider, property_type, output_type=output_type, path=path) output_template = output_tb.build() deployment_name = '{}_{}'.format(property_name, random_string(16)) deployment = { 'name': deployment_name, 'type': 'Microsoft.Resources/deployments', 'apiVersion': '2015-01-01', 'properties': { 'mode': 'Incremental', 'template': output_template, } } deployment['dependsOn'] = [] if not parent_name \ else ['Microsoft.Resources/deployments/{}'.format(parent_name)] return deployment
def deploy_arm_template_at_resource_group(cmd, resource_group_name=None, template_file=None, template_uri=None, parameters=None, no_wait=False): from azure.cli.core.util import random_string from azure.cli.command_modules.resource.custom import ( # pylint: disable=unused-import deploy_arm_template_at_resource_group as _deploy_arm_template, get_deployment_at_resource_group) deployment_name = random_string(length=14, force_lower=True) deployment_poller = _deploy_arm_template(cmd, resource_group_name, template_file, template_uri, parameters, deployment_name, mode='incremental', no_wait=no_wait) deployment = LongRunningOperation( cmd.cli_ctx, start_msg='Deploying ARM template', finish_msg='Finished deploying ARM template')(deployment_poller) properties = getattr(deployment, 'properties', None) # provisioning_state = getattr(properties, 'provisioning_state', None) outputs = getattr(properties, 'outputs', None) return outputs
def deploy_arm_template_at_resource_group(cmd, resource_group_name=None, template_file=None, template_uri=None, parameters=None, no_wait=False): from azure.cli.core.util import random_string from azure.cli.command_modules.resource.custom import ( # pylint: disable=unused-import deploy_arm_template_at_resource_group as _deploy_arm_template, get_deployment_at_resource_group) for try_number in range(TRIES): try: deployment_name = random_string(length=14, force_lower=True) deployment_poller = _deploy_arm_template(cmd, resource_group_name, template_file, template_uri, parameters, deployment_name, mode='incremental', no_wait=no_wait) deployment = LongRunningOperation( cmd.cli_ctx, start_msg='Deploying ARM template', finish_msg='Finished deploying ARM template')( deployment_poller) properties = getattr(deployment, 'properties', None) outputs = getattr(properties, 'outputs', None) return outputs except CLIError as err: if try_number == TRIES - 1: raise err try: import json response = getattr(err, 'response', None) message = json.loads( response.text)['error']['details'][0]['message'] if '(ServiceUnavailable)' not in message: raise err except: raise err import time time.sleep(5) continue
def deploy_arm_template_at_resource_group(cmd, resource_group_name=None, template_file=None, template_uri=None, parameters=None, no_wait=False): from azure.cli.core.util import random_string, sdk_no_wait from azure.cli.command_modules.resource.custom import _prepare_deployment_properties_unmodified from ._client_factory import resource_client_factory properties = _prepare_deployment_properties_unmodified(cmd.cli_ctx, template_file=template_file, template_uri=template_uri, parameters=parameters, mode='Incremental') client = resource_client_factory(cmd.cli_ctx).deployments for try_number in range(TRIES): try: deployment_name = random_string(length=14, force_lower=True) + str(try_number) if cmd.supported_api_version(min_api='2019-10-01', resource_type=ResourceType.MGMT_RESOURCE_RESOURCES): Deployment = cmd.get_models( 'Deployment', resource_type=ResourceType.MGMT_RESOURCE_RESOURCES) deployment = Deployment(properties=properties) deploy_poll = sdk_no_wait(no_wait, client.create_or_update, resource_group_name, deployment_name, deployment) else: deploy_poll = sdk_no_wait(no_wait, client.create_or_update, resource_group_name, deployment_name, properties) result = LongRunningOperation(cmd.cli_ctx, start_msg='Deploying ARM template', finish_msg='Finished deploying ARM template')(deploy_poll) props = getattr(result, 'properties', None) return getattr(props, 'outputs', None) except CLIError as err: if try_number == TRIES - 1: raise err try: response = getattr(err, 'response', None) import json message = json.loads(response.text)['error']['details'][0]['message'] if '(ServiceUnavailable)' not in message: raise err except: raise err import time time.sleep(5) continue
def build_output_deployment_resource(key, property_name, property_provider, property_type, parent_name=None, output_type='object', path=None): from azure.cli.core.util import random_string output_tb = ArmTemplateBuilder() output_tb.add_output(key, property_name, property_provider, property_type, output_type=output_type, path=path) output_template = output_tb.build() deployment_name = '{}_{}'.format(property_name, random_string(16)) deployment = { 'name': deployment_name, 'type': 'Microsoft.Resources/deployments', 'apiVersion': '2015-01-01', 'properties': { 'mode': 'Incremental', 'template': output_template, } } deployment['dependsOn'] = [] if not parent_name \ else ['Microsoft.Resources/deployments/{}'.format(parent_name)] return deployment
def _run_test(length, force_lower): import random # test a bunch of random strings for collisions test_values = [] for x in range(100): rand_len = random.randint(50, 100) test_values.append(random_string(rand_len)) # test each value against eachother to verify hashing properties equal_count = 0 for val1 in test_values: result1 = hash_string(val1, length, force_lower) # test against the remaining values and against itself, but not those which have # come before... test_values2 = test_values[test_values.index(val1):] for val2 in test_values2: result2 = hash_string(val2, length, force_lower) if val1 == val2: self.assertEqual(result1, result2) equal_count += 1 else: self.assertNotEqual(result1, result2) self.assertEqual(equal_count, len(test_values))
def _run_test(length, force_lower): import random # test a bunch of random strings for collisions test_values = [] for x in range(100): rand_len = random.randint(50, 100) test_values.append(random_string(rand_len)) # test each value against eachother to verify hashing properties equal_count = 0 for val1 in test_values: result1 = hash_string(val1, length, force_lower) # test against the remaining values and against itself, but not those which have # come before... test_values2 = test_values[test_values.index(val1):] for val2 in test_values2: result2 = hash_string(val2, length, force_lower) if val1 == val2: self.assertEqual(result1, result2) equal_count += 1 else: self.assertNotEqual(result1, result2) self.assertEqual(equal_count, len(test_values))
def _get_unique_deployment_name(prefix): return prefix + random_string(16)
def generate_random_tag(cls): return '_{}_'.format(random_string(4, force_lower=True))
def generate_account_name(cls): return 'vcrstorage{}'.format(random_string(12, digits_only=True))
def generate_random_tag(cls): return '_{}_'.format(random_string(4, force_lower=True))
def generate_account_name(cls): return 'vcrstorage{}'.format(random_string(12, digits_only=True))
def create_domain( cmd, resource_group_name, hostname, contact_info, privacy=True, auto_renew=True, # pylint: disable=too-many-locals accept_terms=False, tags=None, dryrun=False, no_wait=False): from azure.cli.core.commands.arm import ArmTemplateBuilder from azure.cli.command_modules.appservice._template_builder import ( build_dns_zone, build_domain) from datetime import datetime import socket import json tags = tags or {} if not accept_terms and not dryrun: raise CLIError( "To purchase and create your custom domain '{}', you must view the terms and conditions " "using the command `az appservice domain show-terms`, and accept these terms and " "conditions using the --accept-terms flag".format(hostname)) try: contact_info = json.loads(contact_info) except Exception: raise CLIError( 'Unable to load contact info. Please verify the path to your contact info file, ' 'and that the format matches the sample found at the following link: ' 'https://github.com/AzureAppServiceCLI/appservice_domains_templates' '/blob/master/contact_info.json') contact_info = verify_contact_info_and_format(contact_info) current_time = str(datetime.utcnow()).replace('+00:00', 'Z') local_ip_address = '' try: local_ip_address = socket.gethostbyname(socket.gethostname()) except: raise CLIError("Unable to get IP address") web_client = web_client_factory(cmd.cli_ctx) hostname_availability = web_client.domains.check_availability( name=hostname) if dryrun: logger.warning( "Custom domain will be purchased with the below configuration. Re-run command " "without the --dryrun flag to purchase & create the custom domain") dry_run_params = contact_info.copy() dry_run_params.update({ "hostname": hostname, "resource_group_name": resource_group_name, "privacy": bool(privacy), "auto_renew": bool(auto_renew), "accept_terms": bool(accept_terms), "hostname_available": bool(hostname_availability.available), "price": "$11.99 USD" if hostname_availability.available else "N/A" }) dry_run_str = r""" { "hostname" : "%(hostname)s", "resource_group" : "%(resource_group_name)s", "contact_info": { "address1": "%(address1)s", "address2": "%(address2)s", "city": "%(city)s", "country": "%(country)s", "postal_code": "%(postal_code)s", "state": "%(state)s", "email": "%(email)s", "fax": "%(fax)s", "job_title": "%(job_title)s", "name_first": "%(name_first)s", "name_last": "%(name_last)s", "name_middle": "%(name_middle)s", "organization": "%(organization)s", "phone": "%(phone)s" }, "privacy": "%(privacy)s", "auto_renew": "%(auto_renew)s", "accepted_hostname_purchase_terms": "%(accept_terms)s", "hostname_available": "%(hostname_available)s", "price": "%(price)s" } """ % dry_run_params return json.loads(dry_run_str) if not hostname_availability.available: raise CLIError( "Custom domain name '{}' is not available. Please try again " "with a new hostname.".format(hostname)) tld = '.'.join(hostname.split('.')[1:]) agreements = web_client.top_level_domains.list_agreements( name=tld, include_privacy=privacy) agreement_keys = [agreement.agreement_key for agreement in agreements] dns_zone_id = "[resourceId('Microsoft.Network/dnszones', '{}')]".format( hostname) master_template = ArmTemplateBuilder() dns_zone_resource = build_dns_zone(hostname) domain_resource = build_domain(domain_name=hostname, local_ip_address=local_ip_address, current_time=current_time, address1=contact_info['address1'], address2=contact_info['address2'], city=contact_info['city'], country=contact_info['country'], postal_code=contact_info['postal_code'], state=contact_info['state'], email=contact_info['email'], fax=contact_info['fax'], job_title=contact_info['job_title'], name_first=contact_info['name_first'], name_last=contact_info['name_last'], name_middle=contact_info['name_middle'], organization=contact_info['organization'], phone=contact_info['phone'], dns_zone_id=dns_zone_id, privacy=privacy, auto_renew=auto_renew, agreement_keys=agreement_keys, tags=tags, dependencies=[dns_zone_id]) master_template.add_resource(dns_zone_resource) master_template.add_resource(domain_resource) template = master_template.build() # deploy ARM template deployment_name = 'domain_deploy_' + random_string(32) client = get_mgmt_service_client( cmd.cli_ctx, ResourceType.MGMT_RESOURCE_RESOURCES).deployments DeploymentProperties = cmd.get_models( 'DeploymentProperties', resource_type=ResourceType.MGMT_RESOURCE_RESOURCES) properties = DeploymentProperties(template=template, parameters={}, mode='incremental') if cmd.supported_api_version( min_api='2019-10-01', resource_type=ResourceType.MGMT_RESOURCE_RESOURCES): Deployment = cmd.get_models( 'Deployment', resource_type=ResourceType.MGMT_RESOURCE_RESOURCES) deployment = Deployment(properties=properties) deployment_result = DeploymentOutputLongRunningOperation(cmd.cli_ctx)( sdk_no_wait(no_wait, client.create_or_update, resource_group_name, deployment_name, deployment)) else: deployment_result = DeploymentOutputLongRunningOperation(cmd.cli_ctx)( sdk_no_wait(no_wait, client.create_or_update, resource_group_name, deployment_name, properties)) return deployment_result
def validate_nsg_name(namespace): namespace.network_security_group_name = namespace.network_security_group_name \ or '{}_NSG_{}'.format(namespace.vm_name, random_string(8))
def _get_unique_deployment_name(prefix): from azure.cli.core.util import random_string return prefix + random_string(16)
def validate_nsg_name(namespace): namespace.network_security_group_name = namespace.network_security_group_name \ or '{}_NSG_{}'.format(namespace.vm_name, random_string(8))