示例#1
0
 def verify(self):
     client = WebSiteManagementClient(credentials=self.platform.get_credentials(),
                                      subscription_id=self.platform.subscription_id)
     app_name = self.platform.get_test_name()
     assert client.check_name_availability(app_name, 'Site').name_available
     site = az_models.Site(location='Central US')
     client.web_apps.create_or_update(self.platform.resource_group_name, app_name, site)
     try:
         assert not client.check_name_availability(app_name, 'Site').name_available
         app = client.web_apps.get(self.platform.resource_group_name, app_name)
         assert app.state == 'Running'
     finally:
         client.web_apps.delete(self.platform.resource_group_name, app_name)
     assert client.check_name_availability(app_name, 'Site').name_available
示例#2
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']))
示例#3
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()
示例#4
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()
class PublishingUser(ResourceSDK):
    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 set_or_update(self):
        self.logger.info("Setting/Updating deployment user...")
        user = self.client.update_publishing_user(self.user_details)
        return user
示例#6
0
文件: app.py 项目: Podolyan98/Azure
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')
示例#7
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)
示例#9
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']))
示例#10
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))
示例#11
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
示例#12
0
class PublishingUser(AzureResource):

    def __init__(self, azure_config, logger,
                 api_version=constants.API_VER_APP_SERVICE):
        super(PublishingUser, self).__init__(azure_config)
        self.logger = logger
        self.client = WebSiteManagementClient(self.credentials,
                                              self.subscription_id)

    def set_or_update(self, user_details):
        self.logger.info("Set/Updating publishing_user...")
        publishing_user = self.client.update_publishing_user(
            user_details=user_details
        ).as_dict()
        self.logger.info(
            'Set/Update publishing_user result: {0}'.format(
                utils.secure_logging_content(publishing_user)))
        return publishing_user
示例#13
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)
示例#14
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)
示例#16
0
def azure_connect_service(service, credentials, region_name=None):
    try:
        if service == 'storageaccounts':
            return StorageManagementClient(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:
            print_exception('Service %s not supported' % service)
            return None

    except Exception as e:
        print_exception(e)
        return None
def _get_clients(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)
        resource_client = wrapper.resource_client
    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)
        resource_client = ResourceManagementClient(credentials,
                                                   handler.serviceaccount)

    set_progress("Connection to Azure established")

    return web_client, resource_client
示例#18
0
 def setUp(self):
     self.mock_logger = mock.MagicMock()
     self.mock_cmd = mock.MagicMock()
     self.mock_cmd.cli_ctx = mock.MagicMock()
     self.client = WebSiteManagementClient(mock.MagicMock(), '123455678')
from azure.common.credentials import ServicePrincipalCredentials
from azure.mgmt.web import WebSiteManagementClient
import os, datetime

import plotly.offline as pyo
import plotly.graph_objs as go
import numpy as np

tenant_id = os.environ.get('TENANT')
application_id = os.environ.get('CLIENT_ID_JENKINS')
application_secret = os.environ.get('CLIENT_SECRET_JENKINS')
subscription_id = os.environ.get('SUBSCRIPTION_ID')

credentials = ServicePrincipalCredentials(
    client_id=application_id,
    secret=application_secret,
    tenant=tenant_id,
)

web_client = WebSiteManagementClient(credentials, subscription_id)

web_apps = web_client.web_apps.list()

for app in web_apps:
    if app.slot_swap_status:
        print(app.name, app.slot_swap_status.timestamp_utc)
 def setUp(self):
     self.mock_logger = mock.MagicMock()
     self.mock_cmd = mock.MagicMock()
     self.mock_cmd.cli_ctx = mock.MagicMock()
     self.client = WebSiteManagementClient(
         AdalAuthentication(lambda: ('bearer', 'secretToken')), '123455678')
 def setUp(self):
     self.client = WebSiteManagementClient(mock.MagicMock(), '123455678')
示例#22
0
def _get_resource_iterator(record_type, credentials,
                           sub_index, sub, tenant):
    """Return an appropriate iterator for ``record_type``.

    Arguments:
        record_type (str): Record type.
        credentials (ServicePrincipalCredentials): Credentials.
        sub_index (int): Subscription index (for logging only).
        sub (Subscription): Subscription object.
        tenant (str): Tenant ID (for logging only).

    Returns:
        msrest.paging.Paged: An Azure paging container for iterating
            over a list of Azure resource objects.

    """
    sub_id = sub.get('subscription_id')

    if record_type == 'virtual_machine':
        client = ComputeManagementClient(credentials, sub_id)
        return client.virtual_machines.list_all()

    if record_type == 'app_gateway':
        client = NetworkManagementClient(credentials, sub_id)
        return client.application_gateways.list_all()

    if record_type == 'lb':
        client = NetworkManagementClient(credentials, sub_id)
        return client.load_balancers.list_all()

    if record_type == 'nic':
        client = NetworkManagementClient(credentials, sub_id)
        return client.network_interfaces.list_all()

    if record_type == 'nsg':
        client = NetworkManagementClient(credentials, sub_id)
        return client.network_security_groups.list_all()

    if record_type == 'public_ip':
        client = NetworkManagementClient(credentials, sub_id)
        return client.public_ip_addresses.list_all()

    if record_type == 'storage_account':
        client = StorageManagementClient(credentials, sub_id)
        return client.storage_accounts.list()

    if record_type == 'resource_group':
        client = ResourceManagementClient(credentials, sub_id)
        return client.resource_groups.list()

    if record_type == 'mysql_server':
        client = MySQLManagementClient(credentials, sub_id)
        return client.servers.list()

    if record_type == 'web_apps':
        client = WebSiteManagementClient(credentials, sub_id)
        return client.web_apps.list()

    # If control reaches here, there is a bug in this plugin. It means
    # there is a value in record_types variable in _get_subscriptions
    # that is not handled in the above if-statements.
    _log.warning('Unrecognized record_type: %s; %s', record_type,
                 util.outline_az_sub(sub_index, sub, tenant))
    return None
示例#23
0
 def get_client(self, subscription_id: str):
     return WebSiteManagementClient(self.credentials.get_credentials('arm'),
                                    subscription_id=subscription_id)
示例#24
0
 def __init__(self, azure_config, logger,
              api_version=constants.API_VER_APP_SERVICE):
     super(PublishingUser, self).__init__(azure_config)
     self.logger = logger
     self.client = WebSiteManagementClient(self.credentials,
                                           self.subscription_id)
示例#25
0
 def verify_denied(self, error_text):
     with world.assert_raises(az_exceptions.ClientException, error_text):
         client = WebSiteManagementClient(credentials=self.platform.get_credentials(),
                                          subscription_id=self.platform.subscription_id)
         client.check_name_availability('some_name', 'Site')
示例#26
0
def run_sizer():
    total_number_sql_servers = 0
    total_number_vms = 0
    total_number_functions = 0
    try:
        for sub in sub_client.subscriptions.list():
            print("\n"),
            print(
                Fore.CYAN +
                "================================================================================================"
            )
            print(Fore.WHITE + 'Subscription found:', sub.subscription_id,
                  sub.display_name)
            print(
                Fore.CYAN +
                "================================================================================================"
            )
            resource_client = ResourceManagementClient(credentials,
                                                       sub.subscription_id)
            resource_client.providers.register('Microsoft.Sql')
            sql_client = SqlManagementClient(credentials, sub.subscription_id)
            compute_client = ComputeManagementClient(credentials,
                                                     sub.subscription_id)
            web_client = WebSiteManagementClient(credentials,
                                                 sub.subscription_id)
            sub_total_number_sql_servers = 0
            sub_total_number_vms = 0
            sub_total_number_functions = 0
            print(
                Fore.WHITE +
                "================================================================================================"
            )
            print(Fore.YELLOW + "{:20} {:20} {:20}".format(
                "SQL Server Name",
                "||",
                "Azure Region",
            ))
            print(
                Fore.WHITE +
                "================================================================================================"
            )
            for item in sql_client.servers.list():
                print("{:20} {:20} {:20}".format(item.name, "||",
                                                 item.location))
                sub_total_number_sql_servers = sub_total_number_sql_servers + 1
            print("\n")
            print(
                Fore.WHITE +
                "================================================================================================"
            )
            print(Fore.YELLOW + "{:20} {:20} {:20} {:20} {:20}".format(
                "Virtual machine name", "||", "Instance Size", "||",
                "Azure Region"))
            print(
                Fore.WHITE +
                "================================================================================================"
            )
            for vm in compute_client.virtual_machines.list_all():
                print("{:20} {:20} {:20} {:20} {:20}".format(
                    vm.name, "||", vm.hardware_profile.vm_size, "||",
                    vm.location))
                if vm.hardware_profile.vm_size not in ("Standard_A0",
                                                       "Standard_D0",
                                                       "Basic_A0", "Basic_D0"):
                    sub_total_number_vms = sub_total_number_vms + 1
            print("\n")
            print(
                Fore.WHITE +
                "================================================================================================"
            )
            print(Fore.YELLOW + "{:20} {:20} {:20}".format(
                "Function name", "||", "Azure Region"))
            print(
                Fore.WHITE +
                "================================================================================================"
            )
            for resource_group in resource_client.resource_groups.list():
                rg_name = resource_group.name
                apps_list = web_client.web_apps.list_by_resource_group(rg_name)
                for a in apps_list:
                    appkind = a.kind
                    if "functionapp" in appkind:
                        sub_total_number_functions += 1
                        print("{:20} {:20} {:20}".format(
                            a.name, "||", a.location))
            total_number_sql_servers = total_number_sql_servers + sub_total_number_sql_servers
            total_number_vms = total_number_vms + sub_total_number_vms
            total_number_functions = total_number_functions + sub_total_number_functions
            print("\n")
            print("Total number of billable SQL Servers in subscription",
                  sub.display_name, ":", sub_total_number_sql_servers)
            print("Total number of billable virtual machines in subscription",
                  sub.display_name, ":", sub_total_number_vms)
            print("Total number of billable functions in subscription",
                  sub.display_name, ":", sub_total_number_functions)
    except HttpResponseError as e:
        print(e)
    print("\n")
    print(
        Fore.GREEN +
        "================================================================================================"
    )
    print("CloudGuard Azure Sizer - Report Summary")
    print(
        "================================================================================================"
    )
    print("\n")
    print("Total number of billable SQL Servers in Azure AD tenant", az_tenant,
          ":", total_number_sql_servers)
    print("Total number of billable virtual machines in Azure AD tenant",
          az_tenant, ":", total_number_vms)
    print("Total number of billable functions in Azure AD tenant", az_tenant,
          ":", total_number_functions)
    print("\n")
    total_number_functions_licenses = total_number_functions // 6
    print(
        "Total number of CloudGuard billable assets licenses is :",
        total_number_sql_servers + total_number_vms +
        total_number_functions_licenses)
    print
示例#27
0
 def get_client(self, subscription_id: str):
     client = WebSiteManagementClient(self.credentials.get_credentials('arm'),
                                    subscription_id=subscription_id)
     client._client.config.add_user_agent(get_user_agent())
     return client
示例#28
0
def main():

    SUBSCRIPTION_ID = os.environ.get("SUBSCRIPTION_ID", None)
    GROUP_NAME = "testgroupxx"
    WEB_APP_SLOT = "webappslotxxyyzzx"
    APP_SERVICE_PLAN = "appserviceplanx"
    WEB_APP = "webappxxxx"

    # 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"})

    # - init depended resources -
    # Create app service plan
    plan = web_client.app_service_plans.begin_create_or_update(
        GROUP_NAME, APP_SERVICE_PLAN, {
            "location": "eastus",
            "sku": {
                "name": "B1",
                "tier": "BASIC",
                "capacity": "1"
            },
            "per_site_scaling": False,
            "is_xenon": False
        }).result()

    # Create web app
    web_app = web_client.web_apps.begin_create_or_update(
        GROUP_NAME, WEB_APP, {
            "location": "eastus",
            "server_farm_id": plan.id,
            "reserved": False,
            "is_xenon": False,
            "hyper_v": False,
            "site_config": {
                "net_framework_version":
                "v4.6",
                "app_settings": [{
                    "name": "WEBSITE_NODE_DEFAULT_VERSION",
                    "value": "10.14"
                }],
                "local_my_sql_enabled":
                False,
                "http20_enabled":
                True
            },
            "scm_site_also_stopped": False,
            "https_only": False
        }).result()
    print("Create web app:\n{}".format(web_app))
    # - end -

    # Create web app slot
    web_app_slot = web_client.web_apps.begin_create_or_update_slot(
        GROUP_NAME, WEB_APP, WEB_APP_SLOT, {
            "location": "eastus",
            "reserved": False
        }).result()
    print("Create web app slot:\n{}".format(web_app_slot))

    # Get web app slot
    web_app_slot = web_client.web_apps.get_slot(GROUP_NAME, WEB_APP,
                                                WEB_APP_SLOT)
    print("Get web app slot:\n{}".format(web_app_slot))

    # Update web app slot
    web_app_slot = web_client.web_apps.update_slot(
        GROUP_NAME, WEB_APP, WEB_APP_SLOT, {
            "location": "eastus",
            "properties": {
                "server_farm_id": plan.id,
                "reserved": False,
                "is_xenon": False,
                "hyper_v": False,
                "site_config": {
                    "net_framework_version": "v4.6",
                    "local_my_sql_enabled": False,
                    "http20_enabled": True
                },
                "scm_site_also_stopped": False
            }
        })
    print("Update web app slot:\n{}".format(web_app_slot))

    # Delete web app slot
    web_app_slot = web_client.web_apps.delete_slot(GROUP_NAME, WEB_APP_SLOT)
    print("Delete web app slot.\n")

    # Delete Group
    resource_client.resource_groups.begin_delete(GROUP_NAME).result()
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()
示例#30
0
 def __init__(self, credentials, subscription_id, resource_group, website):
     self._wsc = WebSiteManagementClient(credentials, subscription_id)
     self._resource_group = resource_group
     self._website = website
     self._api_url = None
     self._api_auth = None
 def setUp(self):
     self.client = WebSiteManagementClient(
         AdalAuthentication(lambda: ('bearer', 'secretToken')), '123455678')
示例#32
0
        return credentials
    except TypeError:
        print('\nERROR: Kindly Export the below Environmental vairables to continue ..')
        print('\nAZURE_CLIENT_ID, AZURE_CLIENT_SECRET, AZURE_TENANT_ID & AZURE_SUBSCRIPTION_ID')
        sys.exit(1)
    

credentials = get_credential()

compute_client = ComputeManagementClient(credentials,subscriptionId)
network_client = NetworkManagementClient(credentials,subscriptionId)
storage_client = StorageManagementClient(credentials,subscriptionId)
resource_client = ResourceManagementClient(credentials, subscriptionId)
auth_client = AuthorizationManagementClient(credentials, subscriptionId)
kv_client = KeyVaultManagementClient(credentials,subscriptionId)
funcapp_client = WebSiteManagementClient(credentials,subscriptionId)


def banner():
    size = int(os.popen('tput cols').read().strip())
    print('\n')
    print('#' * size)
    #print(comment.center(size))
    #print('#' * size,'\n')

def run_script(script_location):
    #args = shlex.split(command)
    output = subprocess.call([script_location])
    return output
        
def get_storage_account_keys(resource_group,storage_account):