Python azure.mgmt.resource.ResourceManagementClient() Examples

The following are 23 code examples of azure.mgmt.resource.ResourceManagementClient(). 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.mgmt.resource , 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: 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 #3
Source File: account_setup.py    From aztk with MIT License 6 votes vote down vote up
def create_resource_group(credentials, subscription_id, **kwargs):
    """
        Create a resource group
        :param credentials: msrestazure.azure_active_directory.AdalAuthentication
        :param subscription_id: str
        :param **resource_group: str
        :param **region: str
    """
    resource_client = ResourceManagementClient(credentials, subscription_id)
    resource_client.resource_groups.list()
    for i in range(3):
        try:
            resource_group = resource_client.resource_groups.create_or_update(
                resource_group_name=kwargs.get("resource_group", DefaultSettings.resource_group),
                parameters={
                    'location': kwargs.get("region", DefaultSettings.region),
                })
        except CloudError as e:
            if i == 2:
                raise AccountSetupError("Unable to create resource group in region {}".format(
                    kwargs.get("region", DefaultSettings.region)))
            print(e.message)
            print("Please try again.")
            kwargs["resource_group"] = prompt_with_default("Azure Region", DefaultSettings.region)
    return resource_group.id 
Example #4
Source File: test_utils.py    From azure-event-hubs-python with MIT License 6 votes vote down vote up
def create_mgmt_client(credentials, subscription, location='westus'):
    from azure.mgmt.resource import ResourceManagementClient
    from azure.mgmt.eventhub import EventHubManagementClient

    resource_client = ResourceManagementClient(credentials, subscription)
    rg_name = 'pytest-{}'.format(uuid.uuid4())
    resource_group = resource_client.resource_groups.create_or_update(
                rg_name, {'location': location})

    eh_client = EventHubManagementClient(credentials, subscription)
    namespace = 'pytest-{}'.format(uuid.uuid4())
    creator = eh_client.namespaces.create_or_update(
        resource_group.name,
        namespace)
    create.wait()
    return resource_group, eh_client 
Example #5
Source File: msazure.py    From wrapanapi with MIT License 5 votes vote down vote up
def resource_client(self):
        return ResourceManagementClient(self.credentials, self.subscription_id) 
Example #6
Source File: sync.py    From cloudbolt-forge with Apache License 2.0 5 votes vote down vote up
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.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.
    :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.1"):
        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.1 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 
Example #7
Source File: monitor.py    From pan-fca with Apache License 2.0 5 votes vote down vote up
def __init__(self, cred, subs_id, my_storage_rg, vmss_rg_name, vmss_name, storage, pan_handle, logger=None):
        self.credentials = cred
        self.subscription_id = subs_id
        self.logger = logger
        self.hub_name = vmss_rg_name
        self.storage_name = storage
        self.panorama_handler = pan_handle
        self.vmss_table_name = re.sub(self.ALPHANUM, '', vmss_name + 'vmsstable')
        self.vmss_rg_name = vmss_rg_name

        try:
            self.resource_client = ResourceManagementClient(cred, subs_id)
            self.compute_client = ComputeManagementClient(cred, subs_id)
            self.network_client = NetworkManagementClient(cred, subs_id)
            self.store_client = StorageManagementClient(cred, subs_id)
            store_keys = self.store_client.storage_accounts.list_keys(my_storage_rg, storage).keys[0].value
            self.table_service = TableService(account_name=storage,
                                              account_key=store_keys)
        except Exception as e:
            self.logger.error("Getting Azure Infra handlers failed %s" % str(e))
            raise e


        rg_list = self.resource_client.resource_groups.list()
        self.managed_spokes = []
        self.managed_spokes.append(vmss_rg_name)
        self.new_spokes = [] 
Example #8
Source File: self_destruct.py    From azure-cli-extension-noelbundick with MIT License 5 votes vote down vote up
def resource_client_factory(cli_ctx, **_):
    from azure.cli.core.commands.client_factory import get_mgmt_service_client
    from azure.mgmt.resource import ResourceManagementClient

    return get_mgmt_service_client(cli_ctx, ResourceManagementClient) 
Example #9
Source File: azure.py    From parsl with Apache License 2.0 5 votes vote down vote up
def get_clients(self):
        """
        Set up access to Azure API clients
        """
        credentials, subscription_id = self.get_credentials()
        self.resource_client = ResourceManagementClient(
            credentials, subscription_id)
        self.compute_client = ComputeManagementClient(credentials,
                                                      subscription_id)
        self.network_client = NetworkManagementClient(credentials,
                                                      subscription_id) 
Example #10
Source File: azure_api.py    From kubernetes-ec2-autoscaler with MIT License 5 votes vote down vote up
def __init__(self, compute_client: ComputeManagementClient, monitor_client: MonitorClient, resource_client: ResourceManagementClient) -> None:
        self._compute_client = compute_client
        self._monitor_client = monitor_client
        self._resource_client = resource_client 
Example #11
Source File: manager.py    From laniakea with Mozilla Public License 2.0 5 votes vote down vote up
def connect(self):
        if self.settings is None:
            raise AzureManagerException('No configuration attached.')

        credentials = ServicePrincipalCredentials(
            client_id=self.settings['keys']['client_id'],
            secret=self.settings['keys']['client_secret'],
            tenant=self.settings['keys']['tenant_id']
        )

        try:
            self.client = ResourceManagementClient(credentials, self.settings['keys']['subscription_id'])
        except Exception as msg:
            raise AzureManagerException(msg) 
Example #12
Source File: node_provider.py    From ray with Apache License 2.0 5 votes vote down vote up
def __init__(self, provider_config, cluster_name):
        NodeProvider.__init__(self, provider_config, cluster_name)
        kwargs = {}
        if "subscription_id" in provider_config:
            kwargs["subscription_id"] = provider_config["subscription_id"]
        try:
            self.compute_client = get_client_from_cli_profile(
                client_class=ComputeManagementClient, **kwargs)
            self.network_client = get_client_from_cli_profile(
                client_class=NetworkManagementClient, **kwargs)
            self.resource_client = get_client_from_cli_profile(
                client_class=ResourceManagementClient, **kwargs)
        except CLIError as e:
            if str(e) != "Please run 'az login' to setup account.":
                raise
            else:
                logger.info("CLI profile authentication failed. Trying MSI")

                credentials = MSIAuthentication()
                self.compute_client = ComputeManagementClient(
                    credentials=credentials, **kwargs)
                self.network_client = NetworkManagementClient(
                    credentials=credentials, **kwargs)
                self.resource_client = ResourceManagementClient(
                    credentials=credentials, **kwargs)

        self.lock = RLock()

        # cache node objects
        self.cached_nodes = {} 
Example #13
Source File: azure_driver.py    From powerfulseal with Apache License 2.0 5 votes vote down vote up
def create_connection_from_config():
    """ Creates a new Azure api connection """
    resource_client = None
    compute_client = None
    network_client = None
    try:
        os.environ['AZURE_AUTH_LOCATION']
    except KeyError:
        try:
            subscription_id = os.environ['AZURE_SUBSCRIPTION_ID']
            credentials = ServicePrincipalCredentials(
                client_id=os.environ['AZURE_CLIENT_ID'],
                secret=os.environ['AZURE_CLIENT_SECRET'],
                tenant=os.environ['AZURE_TENANT_ID']
            )
        except KeyError:
            sys.exit("No Azure Connection Defined")
        else:
           resource_client = ResourceManagementClient(credentials, subscription_id)
           compute_client = ComputeManagementClient(credentials, subscription_id)
           network_client = NetworkManagementClient(credentials, subscription_id)
    else:
        resource_client = get_client_from_auth_file(ResourceManagementClient)
        compute_client = get_client_from_auth_file(ComputeManagementClient)
        network_client = get_client_from_auth_file(NetworkManagementClient)

    return resource_client, compute_client, network_client 
Example #14
Source File: Azure.py    From im with GNU General Public License v3.0 5 votes vote down vote up
def get_rg(group_name, credentials, subscription_id):
        """
        Get the RG named group_name, if it not exists return None
        """
        try:
            resource_client = ResourceManagementClient(credentials, subscription_id)
            return resource_client.resource_groups.get(group_name)
        except CloudError as cex:
            if cex.status_code == 404:
                return None
            else:
                raise cex 
Example #15
Source File: azure_resource.py    From Particle-Cloud-Framework with Apache License 2.0 5 votes vote down vote up
def resource_client(self):
        """
        Uses client from cli so that users can use az login to get their credentials

        Returns:
             Resource Client
        """
        if not self.client:
            self.client = get_client_from_cli_profile(ResourceManagementClient)
        return self.client 
Example #16
Source File: resource_group.py    From seismic-deeplearning with MIT License 5 votes vote down vote up
def _get_resource_group_client(profile_credentials, subscription_id):
    return ResourceManagementClient(profile_credentials, subscription_id) 
Example #17
Source File: meta_lib.py    From incubator-dlab with Apache License 2.0 5 votes vote down vote up
def __init__(self):
        os.environ['AZURE_AUTH_LOCATION'] = '/root/azure_auth.json'
        self.compute_client = get_client_from_auth_file(ComputeManagementClient)
        self.resource_client = get_client_from_auth_file(ResourceManagementClient)
        self.network_client = get_client_from_auth_file(NetworkManagementClient)
        self.storage_client = get_client_from_auth_file(StorageManagementClient)
        self.datalake_client = get_client_from_auth_file(DataLakeStoreAccountManagementClient)
        self.authorization_client = get_client_from_auth_file(AuthorizationManagementClient)
        self.sp_creds = json.loads(open(os.environ['AZURE_AUTH_LOCATION']).read())
        self.dl_filesystem_creds = lib.auth(tenant_id=json.dumps(self.sp_creds['tenantId']).replace('"', ''),
                                            client_secret=json.dumps(self.sp_creds['clientSecret']).replace('"', ''),
                                            client_id=json.dumps(self.sp_creds['clientId']).replace('"', ''),
                                            resource='https://datalake.azure.net/') 
Example #18
Source File: actions_lib.py    From incubator-dlab with Apache License 2.0 5 votes vote down vote up
def __init__(self):
        os.environ['AZURE_AUTH_LOCATION'] = '/root/azure_auth.json'
        self.compute_client = get_client_from_auth_file(ComputeManagementClient)
        self.resource_client = get_client_from_auth_file(ResourceManagementClient)
        self.network_client = get_client_from_auth_file(NetworkManagementClient)
        self.storage_client = get_client_from_auth_file(StorageManagementClient)
        self.datalake_client = get_client_from_auth_file(DataLakeStoreAccountManagementClient)
        self.authorization_client = get_client_from_auth_file(AuthorizationManagementClient)
        self.sp_creds = json.loads(open(os.environ['AZURE_AUTH_LOCATION']).read())
        self.dl_filesystem_creds = lib.auth(tenant_id=json.dumps(self.sp_creds['tenantId']).replace('"', ''),
                                            client_secret=json.dumps(self.sp_creds['clientSecret']).replace('"', ''),
                                            client_id=json.dumps(self.sp_creds['clientId']).replace('"', ''),
                                            resource='https://datalake.azure.net/') 
Example #19
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 #20
Source File: tests_client.py    From koku with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_resource_client(self, _):
        """Test the resource_client 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.resource_client, ResourceManagementClient)) 
Example #21
Source File: client.py    From koku with GNU Affero General Public License v3.0 5 votes vote down vote up
def resource_client(self):
        """Return a resource client."""
        return ResourceManagementClient(self.credentials, self.subscription_id) 
Example #22
Source File: Azure.py    From im with GNU General Public License v3.0 5 votes vote down vote up
def finalize(self, vm, last, auth_data):
        credentials, subscription_id = self.get_credentials(auth_data)

        try:
            resource_client = ResourceManagementClient(credentials, subscription_id)

            if vm.id:
                self.log_info("Terminate VM: %s" % vm.id)
                group_name = vm.id.split('/')[0]

                # Delete Resource group and everything in it
                if self.get_rg(group_name, credentials, subscription_id):
                    deleted, msg = self.delete_resource_group(group_name, resource_client)
                    if not deleted:
                        return False, "Error terminating the VM: %s" % msg
                else:
                    self.log_info("RG: %s does not exist. Do not remove." % group_name)
            else:
                self.log_warn("No VM ID. Ignoring")

            # if it is the last VM delete the RG of the Inf
            if last:
                if self.get_rg("rg-%s" % vm.inf.id, credentials, subscription_id):
                    deleted, msg = self.delete_resource_group("rg-%s" % vm.inf.id, resource_client)
                    if not deleted:
                        return False, "Error terminating the VM: %s" % msg
                else:
                    self.log_info("RG: %s does not exist. Do not remove." % "rg-%s" % vm.inf.id)

        except Exception as ex:
            self.log_exception("Error terminating the VM")
            return False, "Error terminating the VM: " + str(ex)

        return True, "" 
Example #23
Source File: config.py    From ray with Apache License 2.0 4 votes vote down vote up
def _configure_resource_group(config):
    # TODO: look at availability sets
    # https://docs.microsoft.com/en-us/azure/virtual-machines/windows/tutorial-availability-sets
    resource_client = _get_client(ResourceManagementClient, config)

    subscription_id = resource_client.config.subscription_id
    logger.info("Using subscription id: %s", subscription_id)
    config["provider"]["subscription_id"] = subscription_id

    assert "resource_group" in config["provider"], (
        "Provider config must include resource_group field")
    resource_group = config["provider"]["resource_group"]

    assert "location" in config["provider"], (
        "Provider config must include location field")
    params = {"location": config["provider"]["location"]}

    if "tags" in config["provider"]:
        params["tags"] = config["provider"]["tags"]

    logger.info("Creating/Updating Resource Group: %s", resource_group)
    resource_client.resource_groups.create_or_update(
        resource_group_name=resource_group, parameters=params)

    # load the template file
    current_path = os.path.dirname(os.path.abspath(__file__))
    template_path = os.path.join(current_path, "azure-config-template.json")
    with open(template_path, "r") as template_fp:
        template = json.load(template_fp)

    # choose a random subnet, skipping most common value of 0
    random.seed(resource_group)
    subnet_mask = "10.{}.0.0/16".format(random.randint(1, 254))

    parameters = {
        "properties": {
            "mode": DeploymentMode.incremental,
            "template": template,
            "parameters": {
                "subnet": {
                    "value": subnet_mask
                }
            }
        }
    }

    resource_client.deployments.create_or_update(
        resource_group_name=resource_group,
        deployment_name="ray-config",
        parameters=parameters).wait()

    return config