Esempio n. 1
0
def ftpfsMapWebApps(self):

	web_client = WebSiteManagementClient(credentials, subscription_id)

	for site in web_client.web_apps.list_by_resource_group(group_name):
		name = format(site.name)
		publishXML = parseString(list(web_client.web_apps.list_publishing_profile_xml_with_secrets(group_name,site.name))[0])
		publishProfiles = publishXML.getElementsByTagName('publishProfile')
		for publishProfile in publishProfiles:
			publishMethod = publishProfile.getAttribute('publishMethod')
			if(publishMethod == "FTP"):
				PublishURL = str(publishProfile.getAttribute('publishUrl'))
				PublishUser = str(publishProfile.getAttribute('userName'))
				PublishPass = str(publishProfile.getAttribute('userPWD'))
				ProfileName = str(publishProfile.getAttribute('profileName')).replace(" - FTP","")

				ftpUsername = PublishUser.split("\\")[0].replace("$","") + "\\" + subscription_ftp_username
				ftpPassword = subscription_ftp_password
				ftpHost = PublishURL.replace("ftp://","")
				ftpMount = "/mnt/"+ProfileName

				print "\033[92m" + "Mounting " + ProfileName + "\033[0m" 
				os.system("mkdir " + ftpMount + " > /dev/null 2>&1")
				os.system("umount " + ftpMount + " > /dev/null 2>&1")
				os.system("curlftpfs " + "'" + ftpUsername + "':" + ftpPassword + "@" + ftpHost + " " + ftpMount + " > /dev/null 2>&1")

				if len(os.listdir(ftpMount))==0:
					print "\033[91m" + "Mounting Failed" + "\033[0m"
				else:
					print "\033[92m" + "Mounted Successfully" + "\033[0m"
Esempio n. 2
0
    def _get_web_app_configs(self, app_index, app, sub_index, sub):
        """Get web app records with config details.

        Arguments:
            app_index (int): Web app index (for logging only).
            app (dict): Raw web app record.
            sub_index (int): Subscription index (for logging only).
            sub (Subscription): Azure subscription object.

        Yields:
            dict: An Azure web app record with config details.

        """
        app_name = app.get('name')
        _log.info('Working on web app #%d: %s; %s', app_index, app_name,
                  util.outline_az_sub(sub_index, sub, self._tenant))
        try:
            creds = self._credentials
            sub_id = sub.get('subscription_id')
            web_client = WebSiteManagementClient(creds, sub_id)
            app_id = app.get('id')
            rg_name = tools.parse_resource_id(app_id)['resource_group']
            app_config = web_client.web_apps.get_configuration(
                rg_name, app_name)
            app_config = app_config.as_dict()
            yield _process_app_config(app_index, app, app_config, sub_index,
                                      sub, self._tenant)
        except Exception as e:
            _log.error(
                'Failed to fetch app_config for web app #%d: '
                '%s; %s; error: %s: %s', app_index, app_name,
                util.outline_az_sub(sub_index, sub, self._tenant),
                type(e).__name__, e)
def generate_options_for_service_plans(Server=None,
                                       form_prefix=None,
                                       form_data=None,
                                       **kwargs):
    results = []
    azure = AzureARMHandler.objects.first()
    subscription_id = azure.serviceaccount
    credentials = ServicePrincipalCredentials(client_id=azure.client_id,
                                              secret=azure.secret,
                                              tenant=azure.tenant_id)
    web_client = WebSiteManagementClient(credentials, subscription_id)
    service_plan = CustomField.objects.filter(
        name__startswith='service_plan').first()
    resource_group = None
    if service_plan:
        control = service_plan.get_control_values_from_form_data(
            form_prefix, form_data)
        if control:
            keys = control.keys()
            for k in keys:
                if 'resource_group' in k:
                    resource_group = control[k][0]
    if resource_group:
        try:
            for sp in web_client.app_service_plans.list_by_resource_group(
                    resource_group_name=resource_group):
                results.append(sp.name)
        except:
            pass
    return results
Esempio n. 4
0
def azure_connect_service(service, credentials, region_name=None):
    try:
        if service == 'storageaccounts':
            return StorageManagementClient(credentials.credentials, credentials.subscription_id)
        elif service == 'monitor':
            return MonitorManagementClient(credentials.credentials, credentials.subscription_id)
        elif service == 'sqldatabase':
            return SqlManagementClient(credentials.credentials, credentials.subscription_id)
        elif service == 'keyvault':
            return KeyVaultManagementClient(credentials.credentials, credentials.subscription_id)
        elif service == 'appgateway':
            return NetworkManagementClient(credentials.credentials, credentials.subscription_id)
        elif service == 'network':
            return NetworkManagementClient(credentials.credentials, credentials.subscription_id)
        elif service == 'rediscache':
            return RedisManagementClient(credentials.credentials, credentials.subscription_id)
        elif service == 'securitycenter':
            return SecurityCenter(credentials.credentials, credentials.subscription_id, '')
        elif service == 'appservice':
            return WebSiteManagementClient(credentials.credentials, credentials.subscription_id)
        elif service == 'loadbalancer':
            return NetworkManagementClient(credentials.credentials, credentials.subscription_id)
        else:
            printException('Service %s not supported' % service)
            return None

    except Exception as e:
        printException(e)
        return None
Esempio n. 5
0
def get_all_webapps(credentials, rgs):
    all_webapps = []
    for sub, groups in rgs.items():
        web_client = WebSiteManagementClient(credentials, sub)
        monitor_client = MonitorManagementClient(credentials, sub)
        for rg in groups:
            for site in web_client.web_apps.list_by_resource_group(rg):
                get_config = web_client.web_apps.get_configuration(
                    rg, site.name)
                resource_id = f"/subscriptions/{sub}/resourceGroups/{rg}/providers/Microsoft.Web/sites/{site.name}"
                AuditLogs = "No Audit Logs"
                try:
                    monitor_client.diagnostic_settings.get(
                        resource_id,
                        "diagnostic-log-name",  # Place the name of your diagnostic log here!
                    )
                    AuditLogs = True
                except ClientException as ex:
                    pass

                webapp_data = dict({
                    "Subscription": sub,
                    "Resource Group": rg,
                    "App Service Name": site.name,
                    "HTTPS_ONLY": site.https_only,
                    "FTPS": get_config.ftps_state,
                    "TLS": get_config.min_tls_version,
                    "Always-On": get_config.always_on,
                    "Audit Logs": AuditLogs,
                    "Kind": site.kind,
                    "Location": site.location,
                })
                all_webapps.append(webapp_data)
    return json.dumps(all_webapps)
def _get_client(handler):
    """
    Get the clients using newer methods from the CloudBolt main repo if this CB is running
    a version greater than 9.2. These internal methods implicitly take care of much of the other
    features in CloudBolt such as proxy and ssl verification.
    Otherwise, manually instantiate clients without support for those other CloudBolt settings.
    :param handler:
    :return:
    """
    import settings
    from common.methods import is_version_newer

    set_progress("Connecting To Azure...")

    cb_version = settings.VERSION_INFO["VERSION"]
    if is_version_newer(cb_version, "9.2"):
        from resourcehandlers.azure_arm.azure_wrapper import configure_arm_client

        wrapper = handler.get_api_wrapper()
        web_client = configure_arm_client(wrapper, WebSiteManagementClient)
    else:
        # TODO: Remove once versions <= 9.2 are no longer supported.
        credentials = ServicePrincipalCredentials(
            client_id=handler.client_id,
            secret=handler.secret,
            tenant=handler.tenant_id,
        )
        web_client = WebSiteManagementClient(credentials,
                                             handler.serviceaccount)

    set_progress("Connection to Azure established")

    return web_client
Esempio n. 7
0
 def __init__(self,
              azure_config,
              logger,
              api_version=constants.API_VER_APP_SERVICE):
     super(WebApp, self).__init__(azure_config)
     self.logger = logger
     self.client = WebSiteManagementClient(self.credentials,
                                           self.subscription_id)
Esempio n. 8
0
def __init_client(secrets, configuration):
    with auth(secrets) as cred:
        subscription_id = configuration['azure']['subscription_id']
        client = WebSiteManagementClient(
            credentials=cred,
            subscription_id=subscription_id)

        return client
Esempio n. 9
0
 def webapp_client(self):
     self.log('Getting webapp client')
     if not self._webapp_client:
         self._webapp_client = WebSiteManagementClient(
             self.azure_credentials,
             self.subscription_id,
             base_url=self._cloud_environment.endpoints.resource_manager)
         self._register('Microsoft.Web/sites')
     return self._webapp_client
 def __init__(self, logger, credentials, user_details):
     self.logger = logger
     self.user_details = user_details
     self.resource_verify = bool(credentials.get('endpoint_verify', True))
     super(PublishingUser, self).__init__(credentials)
     self.client = WebSiteManagementClient(
         self.credentials, str(credentials['subscription_id']))
     self.logger.info("Use subscription: {}"
                      .format(credentials['subscription_id']))
def list_deploymentslots():
    ''' List Azure Web App deployment slots '''
    credentials, subscription_id = credential_helper.get_credentials()
    resource_group = CONFIG['resource_group']

    web_client = WebSiteManagementClient(credentials, subscription_id)
    for webapp in web_client.web_apps.list_by_resource_group(resource_group):
        if any(web_client.web_apps.list_slots(resource_group, webapp.name)):
            return True
    return False
Esempio n. 12
0
def createWebClient(this_subscription_id, this_client_id, this_secret,
                    this_tenant):

    credentials = ServicePrincipalCredentials(client_id=this_client_id,
                                              secret=this_secret,
                                              tenant=this_tenant)

    web_client = WebSiteManagementClient(credentials, this_subscription_id)

    return web_client
def list_webapps():
    ''' List Azure Web Apps '''
    credentials, subscription_id = credential_helper.get_credentials()
    resource_group = CONFIG['resource_group']

    web_client = WebSiteManagementClient(credentials, subscription_id)
    for webapp in web_client.web_apps.list_by_resource_group(resource_group):
        print(webapp.name)

    return any(web_client.web_apps.list_by_resource_group(resource_group))
Esempio n. 14
0
def init() -> WebSiteManagementClient:
    secrets = load_secrets()
    subscription_id = load_subscription_id()
    base_url = secrets.get('cloud').endpoints.resource_manager

    with auth(secrets) as authentication:
        client = WebSiteManagementClient(credential=authentication,
                                         subscription_id=subscription_id,
                                         base_url=base_url)

        return client
Esempio n. 15
0
 def web_client(self):
     self.log('Getting web client')
     if not self._web_client:
         self.check_client_version(
             'web', web_client_version,
             AZURE_EXPECTED_VERSIONS['web_client_version'])
         self._web_client = WebSiteManagementClient(
             credentials=self.azure_credentials,
             subscription_id=self.subscription_id,
             base_url=self.base_url)
     return self._web_client
Esempio n. 16
0
def setup_azure(secrets):
    log.info("Setting up credentials")
    credentials = ServicePrincipalCredentials(
        client_id=secrets["azure"]["clientId"],
        secret=secrets["azure"]["secret"],
        tenant=secrets["azure"]["tenantId"],
    )

    log.info("Initializing Azure clients")
    subscription_id = secrets["azure"]["subscriptionId"]
    web_client = WebSiteManagementClient(credentials, subscription_id)
    cosmosdb_client = CosmosDB(credentials, subscription_id)
    return web_client, cosmosdb_client
Esempio n. 17
0
def main(mytimer: func.TimerRequest) -> None:

    utc_timestamp = datetime.datetime.utcnow().replace(
        tzinfo=datetime.timezone.utc).isoformat()

    logging.info('[%s] - Key Rotation Function triggered', utc_timestamp)

    credential = DefaultAzureCredential()

    cosmos_connection_string_secret = "cosmosdb"
    function_app_setting_value = "cosmosdb"

    cosmosdb_client = CosmosDBManagementClient(credential=credential,
                                               subscription_id=SUBSCRIPTION_ID)

    logging.info('[%s] - Get new Cosmos DB connection string', utc_timestamp)
    key_type = get_key_types()
    keys = cosmosdb_client.database_accounts.list_connection_strings(
        RESOURCE_GROUP_NAME, COSMOS_DB_ACCOUNT)
    new_connection_string = keys.connection_strings[
        key_type['key_to_get']].connection_string

    logging.info('[%s] - Update Key Vault', utc_timestamp)
    keyvault_client = SecretClient(vault_url=KEY_VAULT_URL,
                                   credential=credential)
    keyvault_client.set_secret(cosmos_connection_string_secret,
                               new_connection_string)

    new_secret_id = keyvault_client.get_secret(cosmos_connection_string_secret)
    new_secret_kv_reference = "@Microsoft.KeyVault(SecretUri={0}/secrets/{1}/{2})".format(
        KEY_VAULT_URL, cosmos_connection_string_secret,
        new_secret_id.properties.version)

    logging.info('[%s] - Update Function Configuration Reference',
                 utc_timestamp)
    web_client = WebSiteManagementClient(credential=credential,
                                         subscription_id=SUBSCRIPTION_ID)
    app_settings = web_client.web_apps.list_application_settings(
        RESOURCE_GROUP_NAME, FUNCTION_ACCOUNT)
    app_settings.properties.update(
        {function_app_setting_value: new_secret_kv_reference})
    web_client.web_apps.update_application_settings(RESOURCE_GROUP_NAME,
                                                    FUNCTION_ACCOUNT,
                                                    app_settings=app_settings)

    logging.info('[%s] - Update Cosmos DB %s key', utc_timestamp,
                 key_type['key_to_rotate'])
    cosmosdb_client.database_accounts.begin_regenerate_key(
        RESOURCE_GROUP_NAME, COSMOS_DB_ACCOUNT,
        DatabaseAccountRegenerateKeyParameters(
            key_kind=key_type['key_to_rotate']))
Esempio n. 18
0
def main():

    SUBSCRIPTION_ID = os.environ.get("SUBSCRIPTION_ID", None)
    GITHUB_TOKEN = os.environ.get("GITHUB_TOKEN", None)
    GROUP_NAME = "testgroupxx"
    STATIC_SITE = "staticsitexxyyzz"

    # Create client
    # # For other authentication approaches, please see: https://pypi.org/project/azure-identity/
    resource_client = ResourceManagementClient(
        credential=DefaultAzureCredential(), subscription_id=SUBSCRIPTION_ID)
    web_client = WebSiteManagementClient(credential=DefaultAzureCredential(),
                                         subscription_id=SUBSCRIPTION_ID)

    # Create resource group
    resource_client.resource_groups.create_or_update(GROUP_NAME,
                                                     {"location": "eastus2"})

    # Create static site
    static_site = web_client.static_sites.create_or_update_static_site(
        GROUP_NAME, STATIC_SITE, {
            "location": "eastus2",
            "sku": {
                "name": "Free",
            },
            "repository_url":
            "https://github.com/00Kai0/html-docs-hello-world",
            "branch": "master",
            "repository_token": GITHUB_TOKEN,
            "build_properties": {
                "app_location": "app",
                "api_location": "api",
                "app_artifact_location": "build"
            }
        })
    print("Create static site:\n{}".format(static_site))

    # Get static site
    static_site = web_client.static_sites.get_static_site(
        GROUP_NAME, STATIC_SITE)
    print("Get static site:\n{}".format(static_site))

    # Delete static site
    static_site = web_client.static_sites.delete_static_site(
        GROUP_NAME, STATIC_SITE)
    print("Delete static site.\n")

    # Delete Group
    resource_client.resource_groups.begin_delete(GROUP_NAME).result()
Esempio n. 19
0
def main():

    SUBSCRIPTION_ID = os.environ.get("SUBSCRIPTION_ID", None)
    GROUP_NAME = "testgroupx"
    APP_SERVICE_PLAN = "appserviceplanxxyyzz"

    # Create client
    # # For other authentication approaches, please see: https://pypi.org/project/azure-identity/
    resource_client = ResourceManagementClient(
        credential=DefaultAzureCredential(), subscription_id=SUBSCRIPTION_ID)
    web_client = WebSiteManagementClient(credential=DefaultAzureCredential(),
                                         subscription_id=SUBSCRIPTION_ID)

    # Create resource group
    resource_client.resource_groups.create_or_update(GROUP_NAME,
                                                     {"location": "eastus"})

    # Create app service plan
    app_service_plan = web_client.app_service_plans.begin_create_or_update(
        GROUP_NAME, APP_SERVICE_PLAN, {
            "kind": "app",
            "location": "eastus",
            "sku": {
                "name": "P1",
                "tier": "Premium",
                "size": "P1",
                "family": "P",
                "capacity": "1"
            }
        }).result()
    print("Create app service plan:\n{}".format(app_service_plan))

    # Get app service plan
    app_service_plan = web_client.app_service_plans.get(
        GROUP_NAME, APP_SERVICE_PLAN)
    print("Get app service plan:\n{}".format(app_service_plan))

    # Update app service plan
    app_service_plan = web_client.app_service_plans.update(
        GROUP_NAME, APP_SERVICE_PLAN, {"kind": "app"})
    print("Update app service plan:\n{}".format(app_service_plan))

    # Delete app service plan
    app_service_plan = web_client.app_service_plans.delete(
        GROUP_NAME, APP_SERVICE_PLAN)
    print("Delete app service plan.\n")

    # Delete Group
    resource_client.resource_groups.begin_delete(GROUP_NAME).result()
Esempio n. 20
0
def restart_app():
    """элементы службы для аутентификации"""
    subscription_id = ""
    client_id = ""
    secret = ""
    tenant = ""
    """аутентификация клиента"""
    credentials = ServicePrincipalCredentials(client_id=client_id,
                                              secret=secret,
                                              tenant=tenant)

    web_client = WebSiteManagementClient(credentials, subscription_id)
    """название группы ресурсов и приложения"""
    web_client.web_apps.restart("<resourceGroup_name>", "<web_app_name>")
    return render_template('faq.html')
Esempio n. 21
0
 def __init__(self,
              logger,
              credentials,
              group_name,
              app_name,
              app_config=None):
     self.group_name = group_name
     self.app_name = app_name
     self.logger = logger
     self.app_config = app_config
     self.resource_verify = bool(credentials.get('endpoint_verify', True))
     super(WebApp, self).__init__(credentials)
     self.client = WebSiteManagementClient(
         self.credentials, str(credentials['subscription_id']))
     self.logger.info("Use subscription: {}".format(
         credentials['subscription_id']))
def run(job, **kwargs):
    resource = kwargs.get('resource')

    # Connect to Azure Management Service
    set_progress("Connecting To Azure Management Service...")
    azure = AzureARMHandler.objects.first()
    subscription_id = azure.serviceaccount
    credentials = ServicePrincipalCredentials(client_id=azure.client_id,
                                              secret=azure.secret,
                                              tenant=azure.tenant_id)
    web_client = WebSiteManagementClient(credentials, subscription_id)
    set_progress("Successfully Connected To Azure Management Service!")

    # Restart Web App
    web_client.web_apps.restart(
        resource_group_name=resource.resource_group_name, name=resource.name)
Esempio n. 23
0
def list_asps():
    ''' List Azure App Service Plans '''
    credentials, subscription_id = credential_helper.get_credentials()
    resource_group = CONFIG['resource_group']

    resource_client = ResourceManagementClient(credentials, subscription_id)
    for item in resource_client.resources.list_by_resource_group(
            resource_group):
        print(item.name)

    web_client = WebSiteManagementClient(credentials, subscription_id)
    for asp in web_client.app_service_plans.list_by_resource_group(
            resource_group):
        print(asp.name)

    return any(
        web_client.app_service_plans.list_by_resource_group(resource_group))
Esempio n. 24
0
    def __init__(self,
                 logger,
                 credentials,
                 group_name,
                 plan_name,
                 plan_details={}):
        self.group_name = group_name
        self.plan_name = plan_name
        self.logger = logger
        self.plan_details = plan_details
        self.resource_verify = bool(credentials.get('endpoint_verify', True))
        super(ServicePlan, self).__init__(credentials)
        self.client = WebSiteManagementClient(
            self.credentials, str(credentials['subscription_id']))

        self.logger.info("Use subscription: {}".format(
            credentials['subscription_id']))
Esempio n. 25
0
def init_website_management_client(
        experiment_secrets: Secrets,
        experiment_configuration: Configuration) -> WebSiteManagementClient:
    """
    Initializes Website management client for webapp resource under Azure
    Resource manager.
    """
    secrets = load_secrets(experiment_secrets)
    configuration = load_configuration(experiment_configuration)
    with auth(secrets) as authentication:
        base_url = secrets.get('cloud').endpoints.resource_manager
        client = WebSiteManagementClient(
            credentials=authentication,
            subscription_id=configuration.get('subscription_id'),
            base_url=base_url)

        return client
Esempio n. 26
0
    def _get_subscription_apps(self, sub_index, sub):
        """Get web apps from a single subscrption.

        Yields:
            tuple: A tuple which when unpacked forms valid arguments for
                :meth:` _get_web_app_configs`.

        """
        try:
            tenant = self._tenant
            creds = self._credentials
            sub_id = sub.get('subscription_id')

            web_client = WebSiteManagementClient(creds, sub_id)
            web_list = web_client.web_apps.list()

            for app_index, app in enumerate(web_list):
                app = app.as_dict()

                _log.info('Found web app #%d: %s; %s', app_index,
                          app.get('name'),
                          util.outline_az_sub(sub_index, sub, tenant))

                # Each app is a unit of work.
                yield (app_index, app, sub_index, sub)

                # Break after pulling data for self._max_recs number
                # of web apps for a subscriber. Note that if
                # self._max_recs is 0 or less, then the following
                # condition never evaluates to True.
                if app_index + 1 == self._max_recs:
                    _log.info(
                        'Stopping web app fetch due '
                        'to _max_recs: %d; %s', self._max_recs,
                        util.outline_az_sub(sub_index, sub, tenant))
                    break
        except Exception as e:
            _log.error('Failed to fetch web apps; %s; error: %s: %s',
                       util.outline_az_sub(sub_index, sub, tenant),
                       type(e).__name__, e)
Esempio n. 27
0
def hello_world():
    
    #define credentials for authentication
auth = {
    'tenant_id': 'XXXXXXXXXXXXXXXXX',
    'client_id': 'XXXXXXXXXXXXXXXXX',
    'key': 'XXXXXXXXXXXXXXX',
}

#define which subscription ID we are doing the actions
subscription_id = 'XXXXXXXXXXXXXXXXXXXXXX';

#create a credentials object
credentials = ServicePrincipalCredentials(client_id=auth['client_id'], secret=auth['key'], tenant=auth['tenant_id']);

#instantiate the management client for WebApp
webSiteManagementClient = WebSiteManagementClient(credentials, subscription_id);

#creates a hostname in the given WebApp Slot
hostNameBinding = webSiteManagementClient.web_apps.create_or_update_host_name_binding_slot(resource_group_name='botdoc-api-front', name='botdoc-api-front', slot='sandbox', host_name='testingggg.botdoc.io', host_name_binding={});


  return 'Hello, World!'
def run(job, **kwargs):
    resource = kwargs.get('resource')

    # Connect to Azure Management Service
    set_progress("Connecting To Azure Management Service...")
    azure = AzureARMHandler.objects.first()
    subscription_id = azure.serviceaccount
    credentials = ServicePrincipalCredentials(client_id=azure.client_id,
                                              secret=azure.secret,
                                              tenant=azure.tenant_id)
    web_client = WebSiteManagementClient(credentials, subscription_id)
    set_progress("Successfully Connected To Azure Management Service!")

    # Create Resource Group if Needed
    resource_group = '{{ resource_groups }}'

    # Create App Service Plan if Needed
    service_plan = '{{ service_plans }}'
    service_plan_obj = web_client.app_service_plans.get(
        resource_group_name=resource_group, name=service_plan)

    # Create Web App
    site_async_operation = web_client.web_apps.create_or_update(
        resource_group, resource.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.set_value_for_custom_field(cf_name='web_app_id', value=site.id)
    resource.set_value_for_custom_field(cf_name='resource_group_name',
                                        value=resource_group)
    resource.set_value_for_custom_field(cf_name='web_app_location',
                                        value=service_plan_obj.location)
    resource.set_value_for_custom_field(cf_name='web_app_default_host_name',
                                        value=site.default_host_name)
 def setUp(self):
     self.client = WebSiteManagementClient(
         AdalAuthentication(lambda: ('bearer', 'secretToken')), '123455678')
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()