Python azure.common.credentials.ServicePrincipalCredentials() Examples

The following are 30 code examples of azure.common.credentials.ServicePrincipalCredentials(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module azure.common.credentials , or try the search function .
Example #1
Source File: infra.py    From whoville with Apache License 2.0 8 votes vote down vote up
def create_azure_session(token, service):
    assert service in ['compute', 'network', 'security', 'storage', 'resource']
    assert isinstance(token, ServicePrincipalCredentials)
    platform = config.profile.get('platform')
    if 'subscription' in platform and platform['subscription']:
        sub_id = platform['subscription']
    else:
        raise ValueError("Subscription ID not in Azure Platform Definition")
    if service == 'compute':
        from azure.mgmt.compute import ComputeManagementClient
        return ComputeManagementClient(token, sub_id)
    if service == 'network':
        from azure.mgmt.network import NetworkManagementClient
        return NetworkManagementClient(token, sub_id)
    if service == 'storage':
        from azure.mgmt.storage import StorageManagementClient
        return StorageManagementClient(token, sub_id)
    if service == 'resource':
        from azure.mgmt.resource import ResourceManagementClient
        return ResourceManagementClient(token, sub_id) 
Example #2
Source File: reserved_vm_collector.py    From azure-cost-mon with MIT License 6 votes vote down vote up
def __init__(self, application_id, application_secret, tenant_id, metric_name):
        """
        Constructor. Access is granted to what Microsoft calls a service principal / Azure Active Directory
        Application / app registration. Read more about this topic at
        https://docs.microsoft.com/en-us/azure/azure-resource-manager/resource-group-create-service-principal-portal.
        This page will guide you how to obtain an application_id, and application_secret, and the tenant_id of
        your Azure Active Directory.
        
        In addition, the application requires "Reader" permissions on _each individual_ reservation _order_ to be
        able to retrieve the information of the actual reservations within the reservation orders.
        
        :param application_id: The application ID that is created during the Azure app registration.
        :param application_secret: The application secret that is created during the Azure app registration.
        :param tenant_id: The ID of your Azure Active Directory instance
        :param metric_name: Name of the timeseries
        """
        self._metric_name = metric_name
        self._credentials = ServicePrincipalCredentials(client_id=application_id,
                                                        secret=application_secret,
                                                        tenant=tenant_id) 
Example #3
Source File: deployer.py    From resource-manager-python-template-deployment with MIT License 6 votes vote down vote up
def __init__(self, subscription_id, resource_group, pub_ssh_key_path='~/.ssh/id_rsa.pub'):
        self.subscription_id = subscription_id
        self.resource_group = resource_group
        self.dns_label_prefix = self.name_generator.haikunate()

        pub_ssh_key_path = os.path.expanduser(pub_ssh_key_path)
        # Will raise if file not exists or not enough permission
        with open(pub_ssh_key_path, 'r') as pub_ssh_file_fd:
            self.pub_ssh_key = pub_ssh_file_fd.read()

        self.credentials = ServicePrincipalCredentials(
            client_id=os.environ['AZURE_CLIENT_ID'],
            secret=os.environ['AZURE_CLIENT_SECRET'],
            tenant=os.environ['AZURE_TENANT_ID']
        )
        self.client = ResourceManagementClient(
            self.credentials, self.subscription_id) 
Example #4
Source File: create.py    From cloudbolt-forge with Apache License 2.0 6 votes vote down vote up
def _get_client(handler):
    """
    Get the client using newer methods from the CloudBolt main repo if this CB is running
    a version greater than 9.2.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.
    """
    set_progress("Connecting to Azure...")

    if CB_VERSION_93_PLUS:
        from resourcehandlers.azure_arm.azure_wrapper import configure_arm_client

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

    set_progress("Connection to Azure established")

    return mysql_client 
Example #5
Source File: create.py    From cloudbolt-forge with Apache License 2.0 6 votes vote down vote up
def _get_client(handler):
    """
    Get the client 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.
    """
    if CB_VERSION_93_PLUS:
        from resourcehandlers.azure_arm.azure_wrapper import configure_arm_client

        wrapper = handler.get_api_wrapper()
        cosmosdb_client = configure_arm_client(wrapper, cosmosdb.CosmosDB)
    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
        )
        cosmosdb_client = cosmosdb.CosmosDB(credentials, handler.serviceaccount)

    set_progress("Connection to Azure established")

    return cosmosdb_client 
Example #6
Source File: create.py    From cloudbolt-forge with Apache License 2.0 6 votes vote down vote up
def _get_client(handler):
    """
    Get the client using newer methods from the CloudBolt main repo if this CB is running
    a version greater than 9.2.1. 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.
    """
    if CB_VERSION_93_PLUS:
        from resourcehandlers.azure_arm.azure_wrapper import configure_arm_client

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

    set_progress("Connection to Azure established")

    return sql_client 
Example #7
Source File: delete.py    From cloudbolt-forge with Apache License 2.0 6 votes vote down vote up
def run(job, **kwargs):
    resource = kwargs.pop("resources").first()

    server_name = resource.attributes.get(field__name="azure_server_name").value
    database_name = resource.attributes.get(field__name="azure_database_name").value
    resource_group = resource.attributes.get(field__name="resource_group_name").value
    rh_id = resource.attributes.get(field__name="azure_rh_id").value
    rh = AzureARMHandler.objects.get(id=rh_id)

    set_progress("Connecting To Azure...")
    credentials = ServicePrincipalCredentials(
        client_id=rh.client_id, secret=rh.secret, tenant=rh.tenant_id
    )
    client = postgresql.PostgreSQLManagementClient(credentials, rh.serviceaccount)
    set_progress("Connection to Azure established")

    set_progress("Deleting database %s from %s..." % (server_name, database_name))
    client.databases.delete(resource_group, server_name, database_name).wait()

    set_progress("Deleting server %s..." % server_name)
    client.servers.delete(resource_group, server_name).wait()

    return "", "", "" 
Example #8
Source File: delete.py    From cloudbolt-forge with Apache License 2.0 6 votes vote down vote up
def run(job, **kwargs):
    resource = kwargs.pop("resources").first()

    server_name = resource.attributes.get(field__name="azure_server_name").value
    database_name = resource.attributes.get(field__name="azure_database_name").value
    resource_group = resource.attributes.get(field__name="resource_group_name").value
    rh_id = resource.attributes.get(field__name="azure_rh_id").value
    rh = AzureARMHandler.objects.get(id=rh_id)

    set_progress("Connecting To Azure...")
    credentials = ServicePrincipalCredentials(
        client_id=rh.client_id, secret=rh.secret, tenant=rh.tenant_id
    )
    client = mariadb.MariaDBManagementClient(credentials, rh.serviceaccount)
    set_progress("Connection to Azure established")

    set_progress("Deleting database %s from %s..." % (server_name, database_name))
    client.databases.delete(resource_group, server_name, database_name).wait()

    set_progress("Deleting server %s..." % server_name)
    client.servers.delete(resource_group, server_name).wait()

    return "", "", "" 
Example #9
Source File: aks.py    From kqueen with MIT License 6 votes vote down vote up
def engine_status(cls, **kwargs):
        try:
            credentials = ServicePrincipalCredentials(client_id=kwargs.get('client_id'),
                                                      secret=kwargs.get('secret'),
                                                      tenant=kwargs.get('tenant'))
        except AuthenticationError:
            logger.exception('Invalid credentials for {} Azure Provisioner'.format(cls.name))
            return config.get('PROVISIONER_ERROR_STATE')
        except Exception:
            logger.exception('{} Azure Provisioner validation failed.'.format(cls.name))
            return config.get('PROVISIONER_UNKNOWN_STATE')
        client = ContainerServiceClient(credentials, kwargs.get('subscription_id'))
        try:
            list(client.managed_clusters.list_by_resource_group(kwargs.get('resource_group_name')))
        except CloudError as e:
            logger.exception('Invalid parameters for {} Azure Provisioner: {}'.format(cls.name, e.message))
            return config.get('PROVISIONER_ERROR_STATE')
        except Exception:
            logger.exception('{} Azure Provisioner validation failed.'.format(cls.name))
            return config.get('PROVISIONER_UNKNOWN_STATE')
        return config.get('PROVISIONER_OK_STATE') 
Example #10
Source File: allocated_vm_collector.py    From azure-cost-mon with MIT License 6 votes vote down vote up
def __init__(self, application_id, application_secret, tenant_id, subscription_ids, metric_name):
        """
        Constructor. Access is granted to what Microsoft calls a service principal / Azure Active Directory
        Application / app registration. Read more about this topic at
        https://docs.microsoft.com/en-us/azure/azure-resource-manager/resource-group-create-service-principal-portal.
        This page will guide you how to obtain an application_id, and application_secret, and the tenant_id of
        your Azure Active Directory. Please do not forget to grant "Reader" permissions to the app for all
        subscriptions that you want to monitor.
        
        :param application_id: The application ID that is created during the Azure app registration.
        :param application_secret: The application secret that is created during the Azure app registration.
        :param tenant_id: The ID of your Azure Active Directory instance
        :param subscription_ids: A _sequence_ of subscription IDs that shall be monitored. The application_id
                                 required "Reader" permissions on each subscription.
        :param metric_name: Name of the timeseries
        """
        self._metric_name = metric_name
        self._subscription_ids = subscription_ids
        self._credentials = ServicePrincipalCredentials(
            client_id=application_id,
            secret=application_secret,
            tenant=tenant_id) 
Example #11
Source File: msazure.py    From wrapanapi with MIT License 6 votes vote down vote up
def __init__(self, **kwargs):
        super(AzureSystem, self).__init__(**kwargs)
        self.client_id = kwargs.get("username")
        self.client_secret = kwargs.get("password")
        self.tenant = kwargs.get("tenant_id")
        self.subscription_id = kwargs.get("subscription_id")
        self.resource_group = kwargs['provisioning']['resource_group']  # default resource group
        self.storage_account = kwargs.get("storage_account")
        self.storage_key = kwargs.get("storage_key")
        self.template_container = kwargs['provisioning']['template_container']
        self.orphaned_discs_path = 'Microsoft.Compute/Images/templates/'
        self.region = kwargs["provisioning"]["region_api"].replace(' ', '').lower()

        self.credentials = ServicePrincipalCredentials(client_id=self.client_id,
                                                       secret=self.client_secret,
                                                       tenant=self.tenant) 
Example #12
Source File: example.py    From storage-python-manage with MIT License 6 votes vote down vote up
def get_credentials():
    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']
    )
    return credentials, subscription_id

# This script expects that the following environment vars are set:
#
# AZURE_TENANT_ID: with your Azure Active Directory tenant id or domain
# AZURE_CLIENT_ID: with your Azure Active Directory Application Client ID
# AZURE_CLIENT_SECRET: with your Azure Active Directory Application Secret
# AZURE_SUBSCRIPTION_ID: with your Azure Subscription Id
# 
Example #13
Source File: azure_client.py    From cloudbridge with MIT License 6 votes vote down vote up
def __init__(self, config):
        self._config = config
        self.subscription_id = str(config.get('azure_subscription_id'))
        self._credentials = ServicePrincipalCredentials(
            client_id=config.get('azure_client_id'),
            secret=config.get('azure_secret'),
            tenant=config.get('azure_tenant')
        )

        self._access_token = config.get('azure_access_token')
        self._resource_client = None
        self._storage_client = None
        self._network_management_client = None
        self._subscription_client = None
        self._compute_client = None
        self._access_key_result = None
        self._block_blob_service = None
        self._table_service = None
        self._storage_account = None

        log.debug("azure subscription : %s", self.subscription_id) 
Example #14
Source File: create.py    From cloudbolt-forge with Apache License 2.0 5 votes vote down vote up
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.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.
    """
    import settings
    from common.methods import is_version_newer

    cb_version = settings.VERSION_INFO["VERSION"]
    if is_version_newer(cb_version, "9.2.2"):
        wrapper = handler.get_api_wrapper()
        storage_client = wrapper.storage_client
    else:
        # TODO: Remove once versions <= 9.2.2 are no longer supported.
        credentials = ServicePrincipalCredentials(
            client_id=handler.client_id, secret=handler.secret, tenant=handler.tenant_id
        )
        storage_client = storage.StorageManagementClient(
            credentials, handler.serviceaccount
        )

    set_progress("Connection to Azure established")

    return storage_client 
Example #15
Source File: azure_container_instance.py    From airflow with Apache License 2.0 5 votes vote down vote up
def get_conn(self):
        conn = self.get_connection(self.conn_id)
        key_path = conn.extra_dejson.get('key_path', False)
        if key_path:
            if key_path.endswith('.json'):
                self.log.info('Getting connection using a JSON key file.')
                return get_client_from_auth_file(ContainerInstanceManagementClient,
                                                 key_path)
            else:
                raise AirflowException('Unrecognised extension for key file.')

        if os.environ.get('AZURE_AUTH_LOCATION'):
            key_path = os.environ.get('AZURE_AUTH_LOCATION')
            if key_path.endswith('.json'):
                self.log.info('Getting connection using a JSON key file.')
                return get_client_from_auth_file(ContainerInstanceManagementClient,
                                                 key_path)
            else:
                raise AirflowException('Unrecognised extension for key file.')

        credentials = ServicePrincipalCredentials(
            client_id=conn.login,
            secret=conn.password,
            tenant=conn.extra_dejson['tenantId']
        )

        subscription_id = conn.extra_dejson['subscriptionId']
        return ContainerInstanceManagementClient(credentials, str(subscription_id)) 
Example #16
Source File: create.py    From cloudbolt-forge with Apache License 2.0 5 votes vote down vote up
def generate_options_for_storage_account(server=None, **kwargs):
    discovered_az_stores = []
    for handler in AzureARMHandler.objects.all():
        set_progress('Connecting to Azure Storage \
        for handler: {}'.format(handler))
        credentials = ServicePrincipalCredentials(
            client_id=handler.client_id,
            secret=handler.secret,
            tenant=handler.tenant_id
        )
        azure_client = storage.StorageManagementClient(credentials, handler.serviceaccount)
        set_progress("Connection to Azure established")
        for st in azure_client.storage_accounts.list():
            discovered_az_stores.append(st.name)
    return discovered_az_stores 
Example #17
Source File: sync.py    From cloudbolt-forge with Apache License 2.0 5 votes vote down vote up
def discover_resources(**kwargs):
    discovered_azure_sql = []
    for handler in AzureARMHandler.objects.all():
        set_progress('Connecting to Azure storage \
        files for handler: {}'.format(handler))
        credentials = ServicePrincipalCredentials(
            client_id=handler.client_id,
            secret=handler.secret,
            tenant=handler.tenant_id
        )
        azure_client = storage.StorageManagementClient(
            credentials, handler.serviceaccount)
        azure_resources_client = resources.ResourceManagementClient(
            credentials, handler.serviceaccount)

        for resource_group in azure_resources_client.resource_groups.list():
            try:
                for st in azure_client.storage_accounts.list_by_resource_group(resource_group.name)._get_next().json()['value']:
                    res = azure_client.storage_accounts.list_keys(
                        resource_group.name, st['name'])
                    keys = res.keys
                    file_service = FileService(
                        account_name=st['name'], account_key=keys[1].value)
                    for share in file_service.list_shares():
                        for file in file_service.list_directories_and_files(share_name=share.name).items:
                            if type(file) is File:
                                discovered_azure_sql.append(
                                    {
                                        'name': share.name + '-' + file.name,
                                        'azure_storage_file_name': file.name,
                                        'azure_storage_file_share_name': share.name,
                                        'azure_storage_account_name': st['name'],
                                        'azure_account_key': keys[0].value,
                                        'azure_account_key_fallback': keys[1].value
                                    }
                                )
            except:
                continue

    return discovered_azure_sql 
Example #18
Source File: delete.py    From cloudbolt-forge with Apache License 2.0 5 votes vote down vote up
def _get_client(handler):
    """
    Get the client using newer methods from the CloudBolt main repo if this CB is running
    a version greater than 9.2.1. 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.
    """
    import settings
    from common.methods import is_version_newer

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

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

    set_progress("Connection to Azure established")

    return sql_client 
Example #19
Source File: azure_data.py    From msticpy with MIT License 5 votes vote down vote up
def connect(self, client_id: str = None, tenant_id: str = None, secret: str = None):
        """Authenticate with the SDK."""
        # Use details of msticpyyaml if not provided
        if client_id is None and tenant_id is None and secret is None:
            data_provs = get_provider_settings(config_section="DataProviders")
            az_cli_config = data_provs.get("AzureCLI")
            # az_cli_config = config.settings.get("AzureCLI")
            if not az_cli_config:
                raise MsticpyAzureConfigError(
                    "No AzureCLI section found in configuration settings.",
                    title="no AzureCLI settings available.",
                )
            config_items = az_cli_config.args
            try:
                client_id = config_items["clientId"]
                tenant_id = config_items["tenantId"]
                secret = config_items["clientSecret"]
            except KeyError as key_err:
                key_name = key_err.args[0]
                raise MsticpyAzureConfigError(
                    f"{key_name} is missing from AzureCLI section in your",
                    "configuration.",
                    title="missing f{key_name} settings for AzureCLI.",
                )
        # Create credentials and connect to the subscription client to validate
        self.credentials = ServicePrincipalCredentials(
            client_id=client_id, secret=secret, tenant=tenant_id
        )
        if not self.credentials:
            raise CloudError("Could not obtain credentials.")
        self.sub_client = SubscriptionClient(self.credentials)
        if not self.sub_client:
            raise CloudError("Could not create a Subscription client.")
        self.connected = True 
Example #20
Source File: sync.py    From cloudbolt-forge with Apache License 2.0 5 votes vote down vote up
def _get_client(handler):
    """
    Get the client using newer methods from the CloudBolt main repo if this CB is running
    a version greater than 9.2.1. 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.
    """
    import settings
    from common.methods import is_version_newer

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

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

    set_progress("Connection to Azure established")

    return sql_client 
Example #21
Source File: delete.py    From cloudbolt-forge with Apache License 2.0 5 votes vote down vote up
def _get_client(handler):
    """
    Get the client 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.
    """
    import settings
    from common.methods import is_version_newer

    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()
        cosmosdb_client = configure_arm_client(wrapper, cosmosdb.CosmosDB)
    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
        )
        cosmosdb_client = cosmosdb.CosmosDB(credentials, handler.serviceaccount)

    set_progress("Connection to Azure established")

    return cosmosdb_client 
Example #22
Source File: azure_data.py    From msticpy with MIT License 5 votes vote down vote up
def __init__(self, connect: bool = False):
        """Initialize connector for Azure Python SDK."""
        self.connected = False
        self.credentials: Optional[ServicePrincipalCredentials] = None
        self.sub_client: Optional[SubscriptionClient] = None
        self.resource_client: Optional[ResourceManagementClient] = None
        self.network_client: Optional[NetworkManagementClient] = None
        self.monitoring_client: Optional[MonitorManagementClient] = None
        self.compute_client: Optional[ComputeManagementClient] = None
        if connect is True:
            self.connect() 
Example #23
Source File: delete.py    From cloudbolt-forge with Apache License 2.0 5 votes vote down vote up
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.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.
    """
    import settings
    from common.methods import is_version_newer

    cb_version = settings.VERSION_INFO["VERSION"]
    if is_version_newer(cb_version, "9.2.2"):
        wrapper = handler.get_api_wrapper()
        storage_client = wrapper.storage_client
    else:
        # TODO: Remove once versions <= 9.2.2 are no longer supported.
        credentials = ServicePrincipalCredentials(
            client_id=handler.client_id, secret=handler.secret, tenant=handler.tenant_id
        )
        storage_client = storage.StorageManagementClient(
            credentials, handler.serviceaccount
        )

    set_progress("Connection to Azure established")

    return storage_client 
Example #24
Source File: azuredns.py    From octodns with MIT License 5 votes vote down vote up
def __init__(self, id, client_id, key, directory_id, sub_id,
                 resource_group, *args, **kwargs):
        self.log = logging.getLogger('AzureProvider[{}]'.format(id))
        self.log.debug('__init__: id=%s, client_id=%s, '
                       'key=***, directory_id:%s', id, client_id, directory_id)
        super(AzureProvider, self).__init__(id, *args, **kwargs)

        credentials = ServicePrincipalCredentials(
            client_id, secret=key, tenant=directory_id
        )
        self._dns_client = DnsManagementClient(credentials, sub_id)
        self._resource_group = resource_group
        self._azure_zones = set() 
Example #25
Source File: sync.py    From cloudbolt-forge with Apache License 2.0 5 votes vote down vote up
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.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.
    """
    import settings
    from common.methods import is_version_newer

    cb_version = settings.VERSION_INFO["VERSION"]
    if is_version_newer(cb_version, "9.2.2"):
        wrapper = handler.get_api_wrapper()
        storage_client = wrapper.storage_client
    else:
        # TODO: Remove once versions <= 9.2.2 are no longer supported.
        credentials = ServicePrincipalCredentials(
            client_id=handler.client_id, secret=handler.secret, tenant=handler.tenant_id
        )
        storage_client = storage.StorageManagementClient(
            credentials, handler.serviceaccount
        )

    set_progress("Connection to Azure established")

    return storage_client 
Example #26
Source File: delete.py    From cloudbolt-forge with Apache License 2.0 5 votes vote down vote up
def _get_client(handler):
    """
    Get the client using newer methods from the CloudBolt main repo if this CB is running
    a version greater than 9.2.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.
    """
    set_progress("Connecting to Azure...")

    import settings
    from common.methods import is_version_newer

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

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

    set_progress("Connection to Azure established")

    return mysql_client 
Example #27
Source File: tests_client.py    From koku with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_credentials(self, _):
        """Test the credentials property."""
        obj = AzureClientFactory(
            subscription_id=FAKE.uuid4(),
            tenant_id=FAKE.uuid4(),
            client_id=FAKE.uuid4(),
            client_secret=FAKE.word(),
            cloud=random.choice(self.clouds),
        )
        self.assertTrue(isinstance(obj._credentials, ServicePrincipalCredentials)) 
Example #28
Source File: create.py    From cloudbolt-forge with Apache License 2.0 5 votes vote down vote up
def get_azure_storage_client(handler) -> StorageManagementClient:
    """Return an Azure storage client with the Resource Handler details."""
    credentials = ServicePrincipalCredentials(
        client_id=handler.client_id, secret=handler.secret, tenant=handler.tenant_id,
    )
    client = storage.StorageManagementClient(credentials, handler.serviceaccount)
    return client 
Example #29
Source File: delete.py    From cloudbolt-forge with Apache License 2.0 5 votes vote down vote up
def run(job, **kwargs):
    resource = kwargs.pop("resources").first()

    azure_network_security_group = resource.attributes.get(
        field__name="azure_network_security_group"
    ).value
    resource_group = resource.attributes.get(field__name="resource_group_name").value
    rh_id = resource.attributes.get(field__name="azure_rh_id").value
    rh = AzureARMHandler.objects.get(id=rh_id)

    set_progress("Connecting To Azure networking...")
    credentials = ServicePrincipalCredentials(
        client_id=rh.client_id, secret=rh.secret, tenant=rh.tenant_id
    )

    network_client = NetworkManagementClient(credentials, rh.serviceaccount)
    set_progress("Connection to Azure networking established")

    set_progress(
        "Deleting network security group %s..." % (azure_network_security_group)
    )

    try:
        network_client.network_security_groups.delete(
            resource_group_name=resource_group,
            network_security_group_name=azure_network_security_group,
        )
    except CloudError as e:
        set_progress("Azure Clouderror: {}".format(e))
        return "FAILURE", "Network security group could not be deleted", ""

    return "SUCCESS", "The network security group has been succesfully deleted", "" 
Example #30
Source File: sync.py    From cloudbolt-forge with Apache License 2.0 5 votes vote down vote up
def discover_resources(**kwargs):
    discovered_virtual_nets = []
    for handler in AzureARMHandler.objects.all():
        set_progress(
            "Connecting to Azure networks \
        for handler: {}".format(
                handler
            )
        )
        credentials = ServicePrincipalCredentials(
            client_id=handler.client_id, secret=handler.secret, tenant=handler.tenant_id
        )
        network_client = NetworkManagementClient(credentials, handler.serviceaccount)

        azure_resources_client = resources.ResourceManagementClient(
            credentials, handler.serviceaccount
        )

        for resource_group in azure_resources_client.resource_groups.list():
            try:
                for security_group in network_client.network_security_groups.list(
                    resource_group_name=resource_group.name
                ):
                    discovered_virtual_nets.append(
                        {
                            "name": "Azure NSG - " + security_group.as_dict()["name"],
                            "azure_network_security_group": security_group.as_dict()[
                                "name"
                            ],
                            "azure_location": security_group.as_dict()["location"],
                            "azure_rh_id": handler.id,
                            "resource_group_name": resource_group.name,
                        }
                    )
            except CloudError as e:
                set_progress("Azure Clouderror: {}".format(e))
                continue

    return discovered_virtual_nets