def _provision(self, params): rg_unit = ResourceGroupUnit() rg_unit.provision_if_not_exists({'name': params['resource_group_name'], 'location': params['location']}) plan_params = AppServicePlan( app_service_plan_name=params['name'], location=params['location'], sku=SkuDescription( name=params['sku_name'], capacity=1, tier=params['sku_tier']), kind='linux', target_worker_size_id=0, reserved=True) plan = self.client.app_service_plans.begin_create_or_update(params['resource_group_name'], params['name'], plan_params).result() # Deploy default autoscale rule for dedicated plans if required by the policy autoscale_params = copy.deepcopy(params.get('auto_scale', {})) if bool(autoscale_params.get('enabled')) and \ not StringUtils.equal(plan.sku, 'dynamic'): autoscale_params['name'] = 'autoscale' autoscale_params['resource_group_name'] = params['resource_group_name'] autoscale_params['service_plan_id'] = plan.id autoscale_params['location'] = plan.location ac_unit = AutoScaleUnit() ac_unit.provision(autoscale_params) return plan
def create_app_service_plan(self): ''' Creates app service plan :return: deserialized app service plan dictionary ''' self.log("Create App Service Plan {0}".format(self.plan['name'])) try: # normalize sku sku = _normalize_sku(self.plan['sku']) sku_def = SkuDescription(tier=get_sku_name(sku), name=sku, capacity=(self.plan.get( 'number_of_workers', None))) plan_def = AppServicePlan(location=self.plan['location'], app_service_plan_name=self.plan['name'], sku=sku_def, reserved=(self.plan.get( 'is_linux', None))) poller = self.web_client.app_service_plans.create_or_update( self.plan['resource_group'], self.plan['name'], plan_def) if isinstance(poller, AzureOperationPoller): response = self.get_poller_result(poller) self.log("Response : {0}".format(response)) return response.as_dict() except CloudError as ex: self.fail( "Failed to create app service plan {0} in resource group {1}: {2}" .format(self.plan['name'], self.plan['resource_group'], str(ex)))
def create_or_update_plan(self): ''' Creates app service plan :return: deserialized app service plan dictionary ''' self.log("Create App Service Plan {0}".format(self.name)) try: # normalize sku sku = _normalize_sku(self.sku) sku_def = SkuDescription(tier=get_sku_name( sku), name=sku, capacity=self.number_of_workers) plan_def = AppServicePlan( location=self.location, app_service_plan_name=self.name, sku=sku_def, reserved=self.is_linux, tags=self.tags if self.tags else None) response = self.web_client.app_service_plans.create_or_update(self.resource_group, self.name, plan_def) if isinstance(response, LROPoller) or isinstance(response, AzureOperationPoller): response = self.get_poller_result(response) self.log("Response : {0}".format(response)) return appserviceplan_to_dict(response) except CloudError as ex: self.fail("Failed to create app service plan {0} in resource group {1}: {2}".format(self.name, self.resource_group, str(ex)))
def _contruct_static_site_object(rg, app_name, location, source, branch, token): from azure.mgmt.web.models import StaticSiteARMResource, SkuDescription app = StaticSiteARMResource(location=location, repository_url=source, branch=branch, repository_token=token, sku=SkuDescription(name='Free', tier='Free')) app.name = app_name app.id = \ "/subscriptions/sub/resourceGroups/{}/providers/Microsoft.Web/staticSites/{}".format(rg, app_name) return app
def create_app_service_plan(resource_group_name, name, is_linux, sku='B1', number_of_workers=None, location=None): client = web_client_factory() sku = _normalize_sku(sku) if location is None: location = _get_location_from_resource_group(resource_group_name) #the api is odd on parameter naming, have to live with it for now sku_def = SkuDescription(tier=_get_sku_name(sku), name=sku, capacity=number_of_workers) plan_def = AppServicePlan(location, app_service_plan_name=name, sku=sku_def, reserved=(is_linux or None)) poller = client.app_service_plans.create_or_update(resource_group_name, name, plan_def) return AppServiceLongRunningOperation(creating_plan=True)(poller)
def app_service_plan(): # The next two lines will create errors. Research pdb if uncertain how to proceed (e.g. help(pdb) # If you wish to proceed with troubleshooting, comment out the next two lines. # import pdb # pdb.set_trace() # Create an App Service Plan global service_plan # RESOURCEGROUPNAME variable has not been defined. Uncomment the line below to fix this error. RESOURCEGROUPNAME = resourcegroupname service_plan_async_operation = web_client.app_service_plans.create_or_update( RESOURCEGROUPNAME, serverfarmname, AppServicePlan(app_service_plan_name=serverfarmname, location=location, sku=SkuDescription(name='F1', capacity=10, tier='Free'))) service_plan = service_plan_async_operation.result()
def _provision(self, params): rg_unit = ResourceGroupUnit() rg_unit.provision_if_not_exists({ 'name': params['resource_group_name'], 'location': params['location'] }) plan = AppServicePlan(app_service_plan_name=params['name'], location=params['location'], sku=SkuDescription(name=params['sku_name'], capacity=1, tier=params['sku_tier']), kind='linux', target_worker_size_id=0, reserved=True) return self.client.app_service_plans.create_or_update( params['resource_group_name'], params['name'], plan).result()
def create_app_service_plan(resource_group, name, tier=None, number_of_workers=None, location=None): client = web_client_factory() if location is None: location = _get_location_from_resource_group(resource_group) sku_name = _get_sku_name(tier) #the api is odd on parameter naming, have to live with it for now sku = SkuDescription(name=tier, tier=sku_name, capacity=number_of_workers) plan_def = ServerFarmWithRichSku(location, server_farm_with_rich_sku_name=name, sku=sku) #TODO: handle bad error on creating too many F1 plans: # Operation failed with status: 'Conflict'. Details: 409 Client Error: Conflict for url: return client.server_farms.create_or_update_server_farm( resource_group, name, plan_def)
def create_app_service_plan(resource_group_name, name, sku, number_of_workers=None, location=None): client = web_client_factory() sku = _normalize_sku(sku) if location is None: location = _get_location_from_resource_group(resource_group_name) #the api is odd on parameter naming, have to live with it for now sku_def = SkuDescription(tier=_get_sku_name(sku), name=sku, capacity=number_of_workers) plan_def = ServerFarmWithRichSku(location, server_farm_with_rich_sku_name=name, sku=sku_def) poller = client.server_farms.create_or_update_server_farm( resource_group_name, name, plan_def) return AppServiceLongRunningOperation()(poller)
logging.basicConfig(level=logging.INFO, format=FORMAT) log = logging.getLogger("deploy") from copy import deepcopy from azure.common.credentials import ServicePrincipalCredentials from azure.mgmt.cosmosdb import CosmosDB from azure.mgmt.cosmosdb.models import DatabaseAccountKind, DatabaseAccountCreateUpdateParameters, Location, DatabaseAccountOfferType from azure.mgmt.web import WebSiteManagementClient from azure.mgmt.web.models import AppServicePlan, SkuDescription, SkuName, Site, SiteConfig, ScmType, NameValuePair from cosmosdb import configure_collections from config import Mongo, Azure SKU_D1_SHARED = SkuDescription(name="D1", capacity=1, tier=SkuName.shared.value) SKU_B1_BASIC = SkuDescription(name="B1", capacity=1, tier=SkuName.basic.value) async def main(): log.info("Loading secrets") secrets = load_secrets() web_client, cosmosdb_client = setup_azure(secrets) db, keys, connection_string = setup_cosmosdb(cosmosdb_client, Azure.cosmosdb_name) configure_collections(Mongo.database_name, Mongo.collections, keys.primary_master_key, db.document_endpoint)
def run_example(): """Web Site management example.""" # # Create the Resource Manager Client with an Application (service principal) token provider # subscription_id = os.environ.get( 'AZURE_SUBSCRIPTION_ID', '11111111-1111-1111-1111-111111111111') # your Azure Subscription Id credentials = ServicePrincipalCredentials( client_id=os.environ['AZURE_CLIENT_ID'], secret=os.environ['AZURE_CLIENT_SECRET'], tenant=os.environ['AZURE_TENANT_ID'] ) resource_client = ResourceManagementClient(credentials, subscription_id) web_client = WebSiteManagementClient(credentials, subscription_id) # 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)) # # Create a Server Farm for your WebApp # print('Create a Server Farm for your WebApp') server_farm_async_operation = web_client.server_farms.create_or_update_server_farm( GROUP_NAME, SERVER_FARM_NAME, ServerFarmWithRichSku( location=WEST_US, sku=SkuDescription( name='S1', capacity=1, tier='Standard' ) ) ) server_farm = server_farm_async_operation.result() print_item(server_farm) # # Create a Site to be hosted in the Server Farm # print('Create a Site to be hosted in the Server Farm') site_async_operation = web_client.sites.create_or_update_site( GROUP_NAME, SITE_NAME, Site( location=WEST_US, server_farm_id=server_farm.id ) ) site = site_async_operation.result() print_item(site) # # List Sites by Resource Group # print('List Sites by Resource Group') for site in web_client.sites.get_sites(GROUP_NAME).value: print_item(site) # # Get a single Site # print('Get a single Site') site = web_client.sites.get_site(GROUP_NAME, SITE_NAME) print_item(site) print("Your site and server farm have been created. " \ "You can now go and visit at http://{}/".format(site.default_host_name)) input("Press enter to delete the site and server farm.") # # Delete a Site # print('Deleting the Site') web_client.sites.delete_site(GROUP_NAME, SITE_NAME) # # Delete the Resource Group # print('Deleting the resource group') delete_async_operation = resource_client.resource_groups.delete(GROUP_NAME) delete_async_operation.wait()
def create_deploy_container_app(cmd, name, source_location=None, docker_custom_image_name=None, dryrun=False, registry_rg=None, registry_name=None): # pylint: disable=too-many-statements import os import json if not source_location: # the dockerfile is expected to be in the current directory the command is running from source_location = os.getcwd() client = web_client_factory(cmd.cli_ctx) _create_new_rg = True _create_new_asp = True _create_new_app = True _create_acr_img = True if docker_custom_image_name: logger.warning('Image will be pulled from DockerHub') img_name = docker_custom_image_name _create_acr_img = False else: logger.warning( 'Source code will be uploaded and built in Azure Container Registry' ) if not registry_name: raise CLIError("--registry-name not specified") if not registry_rg: raise CLIError("--registry-rg not specified") img_name = generate_img_name(source_location) sku = 'P1V2' full_sku = get_sku_name(sku) location = 'Central US' loc_name = 'centralus' asp = "appsvc_asp_linux_{}".format(loc_name) rg_name = "appsvc_rg_linux_{}".format(loc_name) # Resource group: check if default RG is set _create_new_rg = should_create_new_rg(cmd, rg_name, True) rg_str = "{}".format(rg_name) dry_run_str = r""" { "name" : "%s", "serverfarm" : "%s", "resourcegroup" : "%s", "sku": "%s", "location" : "%s" } """ % (name, asp, rg_str, full_sku, location) create_json = json.loads(dry_run_str) if dryrun: logger.warning( "Web app will be created with the below configuration,re-run command " "without the --dryrun flag to create & deploy a new app") return create_json if _create_acr_img: logger.warning("Starting ACR build") queue_acr_build(cmd, registry_rg, registry_name, img_name, source_location) logger.warning("ACR build done. Deploying web app.") # create RG if the RG doesn't already exist if _create_new_rg: logger.warning("Creating Resource group '%s' ...", rg_name) create_resource_group(cmd, rg_name, location) logger.warning("Resource group creation complete") _create_new_asp = True else: logger.warning("Resource group '%s' already exists.", rg_name) _create_new_asp = _should_create_new_asp(cmd, rg_name, asp, location) # create new ASP if an existing one cannot be used if _create_new_asp: logger.warning("Creating App service plan '%s' ...", asp) sku_def = SkuDescription(tier=full_sku, name=sku, capacity=1) plan_def = AppServicePlan(location=loc_name, app_service_plan_name=asp, sku=sku_def, reserved=True) client.app_service_plans.create_or_update(rg_name, asp, plan_def) logger.warning("App service plan creation complete") _create_new_app = True else: logger.warning("App service plan '%s' already exists.", asp) _create_new_app = should_create_new_app(cmd, rg_name, name) # create the app if _create_new_app: logger.warning("Creating app '%s' ....", name) # TODO: Deploy without container params and update separately instead? # deployment_container_image_name=docker_custom_image_name) create_webapp(cmd, rg_name, name, asp, deployment_container_image_name=img_name) logger.warning("Webapp creation complete") else: logger.warning("App '%s' already exists", name) # Set up the container if _create_acr_img: logger.warning("Configuring ACR container settings.") registry_url = 'https://' + registry_name + '.azurecr.io' acr_img_name = registry_name + '.azurecr.io/' + img_name update_container_settings(cmd, rg_name, name, registry_url, acr_img_name) logger.warning("All done.") return create_json
activity_create_rg = ARMClient.resource_groups.create_or_update( resource_group_name=rg_name, parameters={"location": rg_location}) print("Resource Group ID: {}".format(activity_create_rg.id)) # Create an App Service Plan web_client = WebSiteManagementClient(credentials, subscription_id) service_plan_async_operation = web_client.app_service_plans.create_or_update( resource_group_name=rg_name, name=app_svc_plan_name, app_service_plan=AppServicePlan( kind="linux", location=rg_location, reserved= True, # Without this set, it acts like a Windows App Service Plan sku=SkuDescription(name='P1v2', capacity=1, tier='Standard'))) service_plan = service_plan_async_operation.result() print("Service Plan ID: {}".format(service_plan.id)) # Create a Python Web App site_async_operation = web_client.web_apps.create_or_update( resource_group_name=rg_name, name=site_name, site_envelope=Site(location=rg_location, server_farm_id=service_plan.id, site_config=SiteConfig( python_version="3.7", linux_fx_version="PYTHON|3.7", app_command_line="startup.txt", scm_type="LocalGit"))) site = site_async_operation.result()
def run_example(): """Web Site management example.""" # # Create the Resource Manager Client with an Application (service principal) token provider # subscription_id = os.environ['AZURE_SUBSCRIPTION_ID'] credentials = ServicePrincipalCredentials( client_id=os.environ['AZURE_CLIENT_ID'], secret=os.environ['AZURE_CLIENT_SECRET'], tenant=os.environ['AZURE_TENANT_ID']) resource_client = ResourceManagementClient(credentials, subscription_id) web_client = WebSiteManagementClient(credentials, subscription_id) # Register for required namespace resource_client.providers.register('Microsoft.Web') # 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)) # # Create an App Service plan for your WebApp # print('Create an App Service plan for your WebApp') service_plan_async_operation = web_client.app_service_plans.create_or_update( GROUP_NAME, SERVER_FARM_NAME, AppServicePlan(location=WEST_US, sku=SkuDescription(name='S1', capacity=1, tier='Standard'))) service_plan = service_plan_async_operation.result() print_item(service_plan) # # Create a Site to be hosted on the App Service plan # print('Create a Site to be hosted on the App Service plan') site_async_operation = web_client.web_apps.create_or_update( GROUP_NAME, SITE_NAME, Site(location=WEST_US, server_farm_id=service_plan.id)) site = site_async_operation.result() print_item(site) # # List Sites by Resource Group # print('List Sites by Resource Group') for site in web_client.web_apps.list_by_resource_group(GROUP_NAME): print_item(site) # # Get a single Site # print('Get a single Site') site = web_client.web_apps.get(GROUP_NAME, SITE_NAME) print_item(site) print("Your site and server farm have been created. " \ "You can now go and visit at http://{}/".format(site.default_host_name)) input("Press enter to delete the site and server farm.") # # Delete a Site # print('Deleting the Site') web_client.web_apps.delete(GROUP_NAME, SITE_NAME) # # Delete the Resource Group # print('Deleting the resource group') delete_async_operation = resource_client.resource_groups.delete(GROUP_NAME) delete_async_operation.wait()
def create_deploy_webapp(cmd, name, location=None, dryrun=False): import os import json client = web_client_factory(cmd.cli_ctx) sku = "S1" os_val = "Linux" language = "node" full_sku = _get_sku_name(sku) if location is None: locs = client.list_geo_regions(sku, True) available_locs = [] for loc in locs: available_locs.append(loc.geo_region_name) location = available_locs[0] # Remove spaces from the location string, incase the GeoRegion string is used loc_name = location.replace(" ", "") asp = "appsvc_asp_{}_{}".format(os_val, loc_name) rg_name = "appsvc_rg_{}_{}".format(os_val, loc_name) # the code to deploy is expected to be the current directory the command is running from src_dir = os.getcwd() # if dir is empty, show a message in dry run do_deployment = False if os.listdir(src_dir) == [] else True package_json_path = is_node_application(src_dir) str_no_contents_warn = "" if not do_deployment: str_no_contents_warn = "[Empty directory, no deployment will be triggered]" if package_json_path == '': node_version = "[No package.json file found in root directory, not a Node app?]" version_used_create = "8.0" else: with open(package_json_path) as data_file: data = json.load(data_file) node_version = data['version'] version_used_create = get_node_runtime_version_toSet() # Resource group: check if default RG is set default_rg = cmd.cli_ctx.config.get('defaults', 'group', fallback=None) if default_rg and check_resource_group_supports_linux( cmd, default_rg, location): rg_name = default_rg rg_mssg = "[Using default Resource group]" else: rg_mssg = "" runtime_version = "{}|{}".format(language, version_used_create) src_path = "{} {}".format(src_dir.replace("\\", "\\\\"), str_no_contents_warn) rg_str = "{} {}".format(rg_name, rg_mssg) dry_run_str = r""" { "name" : "%s", "serverfarm" : "%s", "resourcegroup" : "%s", "sku": "%s", "os": "%s", "location" : "%s", "src_path" : "%s", "version_detected": "%s", "version_to_create": "%s" } """ % (name, asp, rg_str, full_sku, os_val, location, src_path, node_version, runtime_version) create_json = json.dumps(json.loads(dry_run_str), indent=4, sort_keys=True) if dryrun: logger.warning( "Web app will be created with the below configuration,re-run command " "without the --dryrun flag to create & deploy a new app") logger.warning(create_json) return None # create RG if the RG doesn't already exist if not check_resource_group_exists(cmd, rg_name): logger.warning("Creating Resource group '%s' ...", rg_name) create_resource_group(cmd, rg_name, location) logger.warning("Resource group creation complete") else: logger.warning("Resource group '%s' already exists.", rg_name) # create asp if not check_if_asp_exists(cmd, rg_name, asp): logger.warning("Creating App service plan '%s' ...", asp) sku_def = SkuDescription(tier=full_sku, name=sku, capacity=1) plan_def = AppServicePlan(loc_name, app_service_plan_name=asp, sku=sku_def, reserved=True) client.app_service_plans.create_or_update(rg_name, asp, plan_def) logger.warning("App service plan creation complete") else: logger.warning("App service plan '%s' already exists.", asp) # create the Linux app if not check_app_exists(cmd, rg_name, name): logger.warning("Creating app '%s' ....", name) create_webapp(cmd, rg_name, name, asp, runtime_version) logger.warning("Webapp creation complete") else: logger.warning("App '%s' already exists", name) # setting to build after deployment logger.warning("Updating app settings to enable build after deployment") update_app_settings(cmd, rg_name, name, ["SCM_DO_BUILD_DURING_DEPLOYMENT=true"]) # work around until the timeout limits issue for linux is investigated & fixed # wakeup kudu, by making an SCM call import requests # work around until the timeout limits issue for linux is investigated & fixed user_name, password = _get_site_credential(cmd.cli_ctx, rg_name, name) scm_url = _get_scm_url(cmd, rg_name, name) import urllib3 authorization = urllib3.util.make_headers( basic_auth='{0}:{1}'.format(user_name, password)) requests.get(scm_url + '/api/settings', headers=authorization) if package_json_path != '': logger.warning("Creating zip with contents of dir %s ...", src_dir) # zip contents & deploy zip_file_path = zip_contents_from_dir(src_dir) logger.warning("Deploying and building contents to app." "This operation can take some time to finish...") enable_zip_deploy(cmd, rg_name, name, zip_file_path) else: logger.warning( "No package.json found, skipping zip and deploy process") logger.warning("All done. %s", create_json) return None
def create_deploy_webapp(cmd, name, location=None, dryrun=False): import os import json client = web_client_factory(cmd.cli_ctx) # the code to deploy is expected to be the current directory the command is running from src_dir = os.getcwd() # if dir is empty, show a message in dry run do_deployment = False if os.listdir(src_dir) == [] else True # determine the details for app to be created from src contents lang_details = get_lang_from_content(src_dir) # we support E2E create and deploy for Node & dotnetcore, any other stack, set defaults for os & runtime # and skip deployment if lang_details['language'] is None: do_deployment = False sku = 'F1' os_val = OS_DEFAULT detected_version = '-' runtime_version = '-' else: sku = lang_details.get("default_sku") language = lang_details.get("language") os_val = "Linux" if language.lower( ) == NODE_RUNTIME_NAME else OS_DEFAULT # detect the version data = get_runtime_version_details(lang_details.get('file_loc'), language) version_used_create = data.get('to_create') detected_version = data.get('detected') runtime_version = "{}|{}".format(language, version_used_create) if location is None: locs = client.list_geo_regions(sku, True) available_locs = [] for loc in locs: available_locs.append(loc.geo_region_name) location = available_locs[0] # Remove spaces from the location string, incase the GeoRegion string is used loc_name = location.replace(" ", "") full_sku = _get_sku_name(sku) is_linux = True if os_val == 'Linux' else False asp = "appsvc_asp_{}_{}".format(os_val, loc_name) rg_name = "appsvc_rg_{}_{}".format(os_val, loc_name) str_no_contents_warn = "" if not do_deployment: str_no_contents_warn = "[Empty directory, no deployment will be triggered]" # Resource group: check if default RG is set default_rg = cmd.cli_ctx.config.get('defaults', 'group', fallback=None) if default_rg and check_resource_group_supports_os(cmd, default_rg, location, is_linux): rg_name = default_rg rg_mssg = "[Using default Resource group]" else: rg_mssg = "" src_path = "{} {}".format(src_dir.replace("\\", "\\\\"), str_no_contents_warn) rg_str = "{} {}".format(rg_name, rg_mssg) dry_run_str = r""" { "name" : "%s", "serverfarm" : "%s", "resourcegroup" : "%s", "sku": "%s", "os": "%s", "location" : "%s", "src_path" : "%s", "version_detected": "%s", "version_to_create": "%s" } """ % (name, asp, rg_str, full_sku, os_val, location, src_path, detected_version, runtime_version) create_json = json.dumps(json.loads(dry_run_str), indent=4, sort_keys=True) if dryrun: logger.warning( "Web app will be created with the below configuration,re-run command " "without the --dryrun flag to create & deploy a new app") logger.warning(create_json) return None # create RG if the RG doesn't already exist if not check_resource_group_exists(cmd, rg_name): logger.warning("Creating Resource group '%s' ...", rg_name) create_resource_group(cmd, rg_name, location) logger.warning("Resource group creation complete") else: logger.warning("Resource group '%s' already exists.", rg_name) # create asp if not check_if_asp_exists(cmd, rg_name, asp): logger.warning("Creating App service plan '%s' ...", asp) sku_def = SkuDescription(tier=full_sku, name=sku, capacity=(1 if is_linux else None)) plan_def = AppServicePlan(loc_name, app_service_plan_name=asp, sku=sku_def, reserved=(is_linux or None)) client.app_service_plans.create_or_update(rg_name, asp, plan_def) logger.warning("App service plan creation complete") else: logger.warning("App service plan '%s' already exists.", asp) # create the app if not check_app_exists(cmd, rg_name, name): logger.warning("Creating app '%s' ....", name) create_webapp(cmd, rg_name, name, asp, runtime_version if is_linux else None) logger.warning("Webapp creation complete") else: logger.warning("App '%s' already exists", name) if do_deployment: # setting to build after deployment logger.warning( "Updating app settings to enable build after deployment") update_app_settings(cmd, rg_name, name, ["SCM_DO_BUILD_DURING_DEPLOYMENT=true"]) # work around until the timeout limits issue for linux is investigated & fixed # wakeup kudu, by making an SCM call import requests # work around until the timeout limits issue for linux is investigated & fixed user_name, password = _get_site_credential(cmd.cli_ctx, rg_name, name) scm_url = _get_scm_url(cmd, rg_name, name) import urllib3 authorization = urllib3.util.make_headers( basic_auth='{0}:{1}'.format(user_name, password)) requests.get(scm_url + '/api/settings', headers=authorization) logger.warning("Creating zip with contents of dir %s ...", src_dir) # zip contents & deploy zip_file_path = zip_contents_from_dir(src_dir, language) logger.warning("Deploying and building contents to app." "This operation can take some time to finish...") enable_zip_deploy(cmd, rg_name, name, zip_file_path) else: logger.warning( "No 'NODE' or 'DOTNETCORE' package detected, skipping zip and deploy process" ) logger.warning("All done. %s", create_json) return None
filename, filename, ) file_service.create_file_from_path( sharename, '', filename, filename, ) # Create an App Service Plan service_plan_async_operation = web_client.app_service_plans.create_or_update( resourcegroupname, serverfarmname, AppServicePlan(app_service_plan_name=serverfarmname, location=location, sku=SkuDescription(name='F1', capacity=10, tier='Free'))) service_plan = service_plan_async_operation.result() # Create Web-Site site_async_operation = web_client.web_apps.create_or_update( resourcegroupname, websitename, Site(location=location, server_farm_id=service_plan.id)) website = site_async_operation.result() if website.state == 'Running': print("Website http://" + website.default_host_name + " has deployed successfully.") else: print("Website not deployed successfully.") # View the new web-site before proceeding with the following steps. # Get Profile Information to Extract FTP Credentials
def create_deploy_webapp(cmd, name, location=None, dryrun=False): import os client = web_client_factory(cmd.cli_ctx) # the code to deploy is expected to be the current directory the command is running from src_dir = os.getcwd() # if dir is empty, show a message in dry run do_deployment = False if os.listdir(src_dir) == [] else True # determine the details for app to be created from src contents lang_details = get_lang_from_content(src_dir) # we support E2E create and deploy for Node & dotnetcore, any other stack, set defaults for os & runtime # and skip deployment if lang_details['language'] is None: do_deployment = False sku = 'F1' os_val = OS_DEFAULT detected_version = '-' runtime_version = '-' else: sku = lang_details.get("default_sku") language = lang_details.get("language") is_skip_build = language.lower() == STATIC_RUNTIME_NAME os_val = "Linux" if language.lower( ) == NODE_RUNTIME_NAME else OS_DEFAULT # detect the version data = get_runtime_version_details(lang_details.get('file_loc'), language) version_used_create = data.get('to_create') detected_version = data.get('detected') runtime_version = "{}|{}".format(language, version_used_create) if \ version_used_create != "-" else version_used_create if location is None: locs = client.list_geo_regions(sku, True) available_locs = [] for loc in locs: available_locs.append(loc.geo_region_name) location = available_locs[0] # Remove spaces from the location string, incase the GeoRegion string is used loc_name = location.replace(" ", "") full_sku = get_sku_name(sku) is_linux = True if os_val == 'Linux' else False asp = "appsvc_asp_{}_{}".format(os_val, loc_name) rg_name = "appsvc_rg_{}_{}".format(os_val, loc_name) str_no_contents_warn = "" if not do_deployment: str_no_contents_warn = "[Empty directory, no deployment will be triggered]" # Resource group: check if default RG is set default_rg = cmd.cli_ctx.config.get('defaults', 'group', fallback=None) if default_rg and check_resource_group_exists(cmd, default_rg) and \ check_resource_group_supports_os(cmd, default_rg, location, is_linux): rg_name = default_rg rg_mssg = "[Using default Resource group]" else: rg_mssg = "" src_path = "{} {}".format(src_dir.replace("\\", "\\\\"), str_no_contents_warn) rg_str = "{} {}".format(rg_name, rg_mssg) dry_run_str = r""" { "name" : "%s", "serverfarm" : "%s", "resourcegroup" : "%s", "sku": "%s", "os": "%s", "location" : "%s", "src_path" : "%s", "version_detected": "%s", "version_to_create": "%s" } """ % (name, asp, rg_str, full_sku, os_val, location, src_path, detected_version, runtime_version) create_json = json.loads(dry_run_str) if dryrun: logger.warning( "Web app will be created with the below configuration,re-run command " "without the --dryrun flag to create & deploy a new app") return create_json # create RG if the RG doesn't already exist if not check_resource_group_exists(cmd, rg_name): logger.warning("Creating Resource group '%s' ...", rg_name) create_resource_group(cmd, rg_name, location) logger.warning("Resource group creation complete") else: logger.warning("Resource group '%s' already exists.", rg_name) # create asp if not check_if_asp_exists(cmd, rg_name, asp): logger.warning("Creating App service plan '%s' ...", asp) sku_def = SkuDescription(tier=full_sku, name=sku, capacity=(1 if is_linux else None)) plan_def = AppServicePlan(loc_name, app_service_plan_name=asp, sku=sku_def, reserved=(is_linux or None)) client.app_service_plans.create_or_update(rg_name, asp, plan_def) logger.warning("App service plan creation complete") else: logger.warning("App service plan '%s' already exists.", asp) # create the app if not check_app_exists(cmd, rg_name, name): logger.warning("Creating app '%s' ....", name) create_webapp(cmd, rg_name, name, asp, runtime_version if is_linux else None) logger.warning("Webapp creation complete") else: logger.warning("App '%s' already exists", name) # update create_json to include the app_url url = _get_app_url( cmd, rg_name, name) # picks the custom domain URL incase a domain is assigned if do_deployment: if not is_skip_build: # setting to build after deployment logger.warning( "Updating app settings to enable build after deployment") update_app_settings(cmd, rg_name, name, ["SCM_DO_BUILD_DURING_DEPLOYMENT=true"]) # work around until the timeout limits issue for linux is investigated & fixed # wakeup kudu, by making an SCM call _ping_scm_site(cmd, rg_name, name) logger.warning("Creating zip with contents of dir %s ...", src_dir) # zip contents & deploy zip_file_path = zip_contents_from_dir(src_dir, language) logger.warning("Preparing to deploy %s contents to app.", '' if is_skip_build else 'and build') enable_zip_deploy(cmd, rg_name, name, zip_file_path) # Remove the file afer deployment, handling exception if user removed the file manually try: os.remove(zip_file_path) except OSError: pass else: logger.warning( 'No known package (Node, ASP.NET, .NETCORE, or Static Html) ' 'found skipping zip and deploy process') create_json.update({'app_url': url}) logger.warning("All done.") return create_json
def run(job, **kwargs): resource = kwargs.get("resource") create_custom_fields_as_needed() env_id = "{{ azure_env }}" resource_group = "{{ resource_group }}" web_app_name = "{{ web_app_name }}" service_plan_name = "{{ service_plan_name }}" set_progress( f"Environment {env_id} ResourceId {resource_group} And KWARGS {kwargs}" ) env = Environment.objects.get(id=env_id) rh = env.resource_handler.cast() # Clean Resource name to Azure acceptable web-app name web_app_name = web_app_name.replace(" ", "-") web_app_name = web_app_name.replace("(", "-") web_app_name = web_app_name.replace(")", "") # Connect to Azure Management Service set_progress("Connecting To Azure Management Service...") web_client = _get_client(rh) set_progress("Successfully Connected To Azure Management Service!") if service_plan_name: # User selected a pre-existing service plan, so just get it. service_plan_obj = web_client.app_service_plans.get( resource_group_name=resource_group, name=service_plan_name) else: # Auto-create a new service plan. # Use the web_app_name and append 5 random digits to have a decent probability of uniqueness. service_plan_name = web_app_name + "-{}".format( random.randint(10000, 99999)) set_progress(f"Environment {env_id}") env = Environment.objects.get(id=env_id) service_plan_async_operation = web_client.app_service_plans.create_or_update( resource_group_name=resource_group, name=service_plan_name, app_service_plan=AppServicePlan( location=env.node_location, app_service_plan_name=service_plan_name, sku=SkuDescription(name="S1", capacity=1, tier="Standard"), ), ) service_plan_async_operation.result() service_plan_obj = web_client.app_service_plans.get( resource_group_name=resource_group, name=service_plan_name) # Create Web App site_async_operation = web_client.web_apps.create_or_update( resource_group, web_app_name, Site(location=service_plan_obj.location, server_farm_id=service_plan_obj.id), ) site = site_async_operation.result() # Store Web App metadata on the resource as parameters for teardown resource.azure_web_app_name = web_app_name resource.name = web_app_name resource.azure_web_app_id = site.id resource.azure_web_app_default_host_name = site.default_host_name resource.resource_group_name = resource_group resource.azure_location = site.location resource.save() return "SUCCESS", "", ""