Python azure.mgmt.compute.ComputeManagementClient() Examples

The following are 25 code examples of azure.mgmt.compute.ComputeManagementClient(). 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.compute , 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: Azure.py    From im with GNU General Public License v3.0 6 votes vote down vote up
def get_instance_type(self, system, credentials, subscription_id):
        """
        Get the name of the instance type to launch to Azure

        Arguments:
           - radl(str): RADL document with the requirements of the VM to get the instance type
        Returns: a str with the name of the instance type to launch to Azure
        """
        instance_type_name = system.getValue('instance_type')

        location = self.DEFAULT_LOCATION
        if system.getValue('availability_zone'):
            location = system.getValue('availability_zone')

        (cpu, cpu_op, memory, memory_op, disk_free, disk_free_op) = self.get_instance_selectors(system)

        compute_client = ComputeManagementClient(credentials, subscription_id)
        instace_types = list(compute_client.virtual_machine_sizes.list(location))
        instace_types.sort(key=lambda x: (x.number_of_cores, x.memory_in_mb, x.resource_disk_size_in_mb))

        default = None
        for instace_type in instace_types:
            if instace_type.name == self.INSTANCE_TYPE:
                default = instace_type

            comparison = cpu_op(instace_type.number_of_cores, cpu)
            comparison = comparison and memory_op(instace_type.memory_in_mb, memory)
            comparison = comparison and disk_free_op(instace_type.resource_disk_size_in_mb, disk_free)

            if comparison:
                if not instance_type_name or instace_type.name == instance_type_name:
                    return instace_type

        return default 
Example #3
Source File: Azure.py    From im with GNU General Public License v3.0 6 votes vote down vote up
def vm_action(self, vm, action, auth_data):
        try:
            group_name = vm.id.split('/')[0]
            vm_name = vm.id.split('/')[1]
            credentials, subscription_id = self.get_credentials(auth_data)
            compute_client = ComputeManagementClient(credentials, subscription_id)
            if action == 'stop':
                compute_client.virtual_machines.power_off(group_name, vm_name)
            elif action == 'start':
                compute_client.virtual_machines.start(group_name, vm_name)
            elif action == 'reboot':
                compute_client.virtual_machines.restart(group_name, vm_name)
        except Exception as ex:
            self.log_exception("Error restarting the VM")
            return False, "Error restarting the VM: " + str(ex)

        return True, "" 
Example #4
Source File: allocated_vm_collector.py    From azure-cost-mon with MIT License 6 votes vote down vote up
def _collect_allocated_vms(self, allocated_vms):
        rows = []

        for subscription_id in self._subscription_ids:
            compute_client = ComputeManagementClient(self._credentials, str(subscription_id))
            for vm in compute_client.virtual_machines.list_all():
                rows.append([
                    subscription_id,
                    vm.location,
                    _extract_resource_group(vm.id),
                    vm.hardware_profile.vm_size,
                    1])

        df = DataFrame(data=rows, columns=_ALL_COLUMNS)

        groups = df.groupby(_BASE_COLUMNS).sum()

        for labels, value in groups.iterrows():
            allocated_vms.add_metric(labels, int(value.total)) 
Example #5
Source File: azure.py    From fluo-muchos with Apache License 2.0 5 votes vote down vote up
def status(self):
        config = self.config
        azure_vars_dict = dict(config.items("azure"))
        compute_client = get_client_from_cli_profile(ComputeManagementClient)
        vmss_status = compute_client.virtual_machine_scale_sets.get(
            azure_vars_dict["resource_group"], self.config.cluster_name
        )
        print(
            "name:",
            vmss_status.name,
            "\nprovisioning_state:",
            vmss_status.provisioning_state,
        ) 
Example #6
Source File: Azure.py    From im with GNU General Public License v3.0 5 votes vote down vote up
def get_instance_type_by_name(instance_name, location, credentials, subscription_id):
        compute_client = ComputeManagementClient(credentials, subscription_id)
        instace_types = compute_client.virtual_machine_sizes.list(location)

        for instace_type in list(instace_types):
            if instace_type.name == instance_name:
                return instace_type

        return None 
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: azure_utils.py    From ocs-ci with MIT License 5 votes vote down vote up
def compute_client(self):
        """ Property for Azure vm resource

        Returns:
            ComputeManagementClient instance for managing Azure vm resource
        """
        if not self._compute_client:
            self._compute_client = ComputeManagementClient(*self.credentials)
        return self._compute_client 
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: azure_vm.py    From SnowAlert with Apache License 2.0 5 votes vote down vote up
def get_vms(options):
    cli = get_client_from_json_dict(ComputeManagementClient, options)
    vms = [vm.as_dict() for vm in cli.virtual_machines.list_all()]
    for vm in vms:
        vm['subscription_id'] = options['subscriptionId']
    return vms 
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_rm.py    From Learning_DevOps with MIT License 5 votes vote down vote up
def compute_client(self):
        self.log('Getting compute client')
        if not self._compute_client:
            self._compute_client = self.get_mgmt_svc_client(ComputeManagementClient,
                                                            self._cloud_environment.endpoints.resource_manager,
                                                            '2017-03-30')
            self._register('Microsoft.Compute')
        return self._compute_client 
Example #14
Source File: azure_rm.py    From f5-azure-saca with MIT License 5 votes vote down vote up
def compute_client(self):
        self.log('Getting compute client')
        if not self._compute_client:
            self._compute_client = ComputeManagementClient(
                self.azure_credentials,
                self.subscription_id,
                base_url=self._cloud_environment.endpoints.resource_manager,
                api_version='2017-03-30'
            )
            self._register('Microsoft.Compute')
        return self._compute_client 
Example #15
Source File: azure_rm.py    From Ansible-2-Cloud-Automation-Cookbook with MIT License 5 votes vote down vote up
def compute_client(self):
        self.log('Getting compute client')
        if not self._compute_client:
            self._compute_client = ComputeManagementClient(
                self.azure_credentials,
                self.subscription_id,
                base_url=self._cloud_environment.endpoints.resource_manager,
                api_version='2017-03-30'
            )
            self._register('Microsoft.Compute')
        return self._compute_client 
Example #16
Source File: azure_enable_bootDiagnostics.py    From blueprints with MIT License 5 votes vote down vote up
def set_bootDiagnostics():
    credentials, subscription_id = get_credentials()
    compute_client = ComputeManagementClient(credentials, subscription_id)

    # Set Boot diagnostics for the virtual machine
    az_storage_uri = 'https://{}.blob.core.windows.net/'.format(az_storage_account_name)
    
    async_vm_update = compute_client.virtual_machines.create_or_update(
        az_resource_group_name,
        az_vm_name,
        {
            'location': az_location,
            'diagnostics_profile': {
                'boot_diagnostics': {
                    'enabled': True,
                    'additional_properties': {},
                    'storage_uri': az_storage_uri
                }
            }
        }
    )
    print('\nConfiguring Boot diagnostics. Please wait...')
    async_vm_update.wait()
    
    # Get the virtual machine by name
    print('\nBoot diagnostics status')
    virtual_machine = compute_client.virtual_machines.get(
        az_resource_group_name,
        az_vm_name,
        expand='instanceview'
    )

    return virtual_machine.diagnostics_profile.boot_diagnostics
# endregion

# region execute function 
Example #17
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 #18
Source File: azure_resource.py    From Particle-Cloud-Framework with Apache License 2.0 5 votes vote down vote up
def compute_client(self):
        """
        Uses client from cli so that users can use az login to get their credentials

        Returns:
             Compute Client
        """
        if not self.client:
            self.client = get_client_from_cli_profile(ComputeManagementClient)
        return self.client 
Example #19
Source File: azure_rm.py    From ansible-hortonworks with Apache License 2.0 5 votes vote down vote up
def compute_client(self):
        self.log('Getting compute client')
        if not self._compute_client:
            self._compute_client = self.get_mgmt_svc_client(ComputeManagementClient,
                                                            self._cloud_environment.endpoints.resource_manager,
                                                            '2017-03-30')
            self._register('Microsoft.Compute')
        return self._compute_client 
Example #20
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 #21
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 #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: virtualmachines.py    From ScoutSuite with GNU General Public License v2.0 5 votes vote down vote up
def get_client(self, subscription_id: str):
        return ComputeManagementClient(self.credentials.get_credentials('arm'),
                                       subscription_id=subscription_id) 
Example #24
Source File: Azure.py    From im with GNU General Public License v3.0 5 votes vote down vote up
def alterVM(self, vm, radl, auth_data):
        try:
            group_name = vm.id.split('/')[0]
            vm_name = vm.id.split('/')[1]
            credentials, subscription_id = self.get_credentials(auth_data)
            compute_client = ComputeManagementClient(credentials, subscription_id)

            # Deallocating the VM (resize prepare)
            async_vm_deallocate = compute_client.virtual_machines.deallocate(group_name, vm_name)
            async_vm_deallocate.wait()

            instance_type = self.get_instance_type(radl.systems[0], credentials, subscription_id)
            vm_parameters = " { 'hardware_profile': { 'vm_size': %s } } " % instance_type.name

            async_vm_update = compute_client.virtual_machines.create_or_update(group_name,
                                                                               vm_name,
                                                                               vm_parameters)
            async_vm_update.wait()

            # Start the VM
            async_vm_start = compute_client.virtual_machines.start(group_name, vm_name)
            async_vm_start.wait()

            return self.updateVMInfo(vm, auth_data)
        except Exception as ex:
            self.log_exception("Error altering the VM")
            return False, "Error altering the VM: " + str(ex)

        return (True, "") 
Example #25
Source File: Azure.py    From im with GNU General Public License v3.0 5 votes vote down vote up
def updateVMInfo(self, vm, auth_data):
        self.log_info("Get the VM info with the id: " + vm.id)
        group_name = vm.id.split('/')[0]
        vm_name = vm.id.split('/')[1]

        credentials, subscription_id = self.get_credentials(auth_data)

        try:
            compute_client = ComputeManagementClient(credentials, subscription_id)
            # Get one the virtual machine by name
            virtual_machine = compute_client.virtual_machines.get(group_name, vm_name, expand='instanceView')
        except Exception as ex:
            self.log_warn("The VM does not exists: %s" % str(ex))
            # check if the RG still exists
            if self.get_rg(group_name, credentials, subscription_id):
                self.log_info("But the RG %s does exits. Return OFF." % group_name)
                vm.state = VirtualMachine.OFF
                return (True, vm)

            self.log_exception("Error getting the VM info: " + vm.id)
            return (False, "Error getting the VM info: " + vm.id + ". " + str(ex))

        self.log_info("VM info: " + vm.id + " obtained.")
        vm.state = self.PROVISION_STATE_MAP.get(virtual_machine.provisioning_state, VirtualMachine.UNKNOWN)

        if (vm.state == VirtualMachine.RUNNING and virtual_machine.instance_view and
                len(virtual_machine.instance_view.statuses) > 1):
            vm.state = self.POWER_STATE_MAP.get(virtual_machine.instance_view.statuses[1].code, VirtualMachine.UNKNOWN)

        self.log_debug("The VM state is: " + vm.state)

        instance_type = self.get_instance_type_by_name(virtual_machine.hardware_profile.vm_size,
                                                       virtual_machine.location, credentials, subscription_id)
        self.update_system_info_from_instance(vm.info.systems[0], instance_type)

        # Update IP info
        self.setIPs(vm, virtual_machine.network_profile, credentials, subscription_id)
        self.add_dns_entries(vm, credentials, subscription_id)
        return (True, vm)