Debian Codegraph @

ansible_collections/azure/azcollection/plugins/module_utils/azure_rm_common.py

raw symbols SCIP
1 # Copyright (c) 2016 Matt Davis, <[email protected]>
2 # Chris Houseknecht, <[email protected]>
3 #
4 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
5
6 from __future__ import absolute_import, division, print_function
7 __metaclass__ = type
8
9
10 import os
11 import re
12 import types
13 import copy
14 import inspect
15 import traceback
16 import json
17
18 from os.path import expanduser
19
20 from ansible.module_utils.basic import \
21 AnsibleModule, missing_required_lib, env_fallback
22
23 try:
24 from ansible.module_utils.ansible_release import __version__ as ANSIBLE_VERSION
25 except Exception:
26 ANSIBLE_VERSION = 'unknown'
27 from ansible.module_utils.six.moves import configparser
28 import ansible.module_utils.six.moves.urllib.parse as urlparse
29
30 AZURE_COMMON_ARGS = dict(
31 auth_source=dict(
32 type='str',
33 choices=['auto', 'cli', 'env', 'credential_file', 'msi'],
34 fallback=(env_fallback, ['ANSIBLE_AZURE_AUTH_SOURCE']),
35 default="auto"
36 ),
37 profile=dict(type='str'),
38 subscription_id=dict(type='str'),
39 client_id=dict(type='str', no_log=True),
40 secret=dict(type='str', no_log=True),
41 tenant=dict(type='str', no_log=True),
42 ad_user=dict(type='str', no_log=True),
43 password=dict(type='str', no_log=True),
44 cloud_environment=dict(type='str', default='AzureCloud'),
45 cert_validation_mode=dict(type='str', choices=['validate', 'ignore']),
46 api_profile=dict(type='str', default='latest'),
47 adfs_authority_url=dict(type='str', default=None),
48 log_mode=dict(type='str', no_log=True),
49 log_path=dict(type='str', no_log=True),
50 x509_certificate_path=dict(type='path', no_log=True),
51 thumbprint=dict(type='str', no_log=True),
52 disable_instance_discovery=dict(type='bool', default=False),
53 oidc_token=dict(type='str', no_log=True), # direct JWT assertion
54 oidc_token_file_path=dict(type='path', no_log=True) # path to JWT assertion file
55 )
56
57 AZURE_CREDENTIAL_ENV_MAPPING = dict(
58 profile='AZURE_PROFILE',
59 subscription_id='AZURE_SUBSCRIPTION_ID',
60 client_id='AZURE_CLIENT_ID',
61 secret='AZURE_SECRET',
62 tenant='AZURE_TENANT',
63 ad_user='AZURE_AD_USER',
64 password='AZURE_PASSWORD',
65 cloud_environment='AZURE_CLOUD_ENVIRONMENT',
66 cert_validation_mode='AZURE_CERT_VALIDATION_MODE',
67 adfs_authority_url='AZURE_ADFS_AUTHORITY_URL',
68 x509_certificate_path='AZURE_X509_CERTIFICATE_PATH',
69 thumbprint='AZURE_THUMBPRINT',
70 disable_instance_discovery='AZURE_DISABLE_INSTANCE_DISCOVERY',
71 oidc_token='AZURE_FEDERATED_TOKEN',
72 oidc_token_file_path='AZURE_FEDERATED_TOKEN_FILE'
73 )
74
75
76 class SDKProfile(object): # pylint: disable=too-few-public-methods
77
78 def __init__(self, default_api_version, profile=None):
79 """Constructor.
80
81 :param str default_api_version: Default API version if not overridden by a profile. Nullable.
82 :param profile: A dict operation group name to API version.
83 :type profile: dict[str, str]
84 """
85 self.profile = profile if profile is not None else {}
86 self.profile[None] = default_api_version
87
88 @property
89 def default_api_version(self):
90 return self.profile[None]
91
92
93 # FUTURE: this should come from the SDK or an external location.
94 # For now, we have to copy from azure-cli
95 AZURE_API_PROFILES = {
96 'latest': {
97 'AuthorizationManagementClient': '2020-04-01-preview',
98 'ContainerInstanceManagementClient': '2018-02-01-preview',
99 'ComputeManagementClient': dict(
100 default_api_version='2018-10-01',
101 resource_skus='2018-10-01',
102 disks='2018-06-01',
103 snapshots='2018-10-01',
104 virtual_machine_run_commands='2018-10-01'
105 ),
106 'ManagementGroupsClient': '2020-05-01',
107 'NetworkManagementClient': '2019-11-01',
108 'ResourceManagementClient': '2019-10-01',
109 'SearchManagementClient': '2020-08-01',
110 'StorageManagementClient': '2021-06-01',
111 'SubscriptionClient': '2019-11-01',
112 'WebSiteManagementClient': '2021-03-01',
113 'PostgreSQLManagementClient': '2017-12-01',
114 'MySQLManagementClient': '2017-12-01',
115 'MariaDBManagementClient': '2019-03-01',
116 'ManagementLockClient': '2016-09-01',
117 'DataLakeStoreAccountManagementClient': '2016-11-01',
118 'NotificationHubsManagementClient': '2016-03-01',
119 'EventHubManagementClient': '2021-11-01',
120 'GenericRestClient': 'latest',
121 'DnsManagementClient': '2018-05-01',
122 'PrivateDnsManagementClient': 'latest',
123 'ContainerServiceClient': '2022-02-01',
124 'SqlManagementClient': 'latest',
125 'ContainerRegistryManagementClient': '2021-09-01',
126 'MarketplaceOrderingAgreements': 'latest',
127 'TrafficManagerManagementClient': 'latest',
128 'MonitorManagementClient': '2016-03-01',
129 'LogAnalyticsManagementClient': 'latest',
130 'ServiceBusManagementClient': 'latest',
131 'AutomationClient': 'latest',
132 'IotHubClient': 'latest',
133 'RecoveryServicesBackupClient': 'latest',
134 'DataFactoryManagementClient': 'latest',
135 'KeyVaultManagementClient': '2026-02-01',
136 'HDInsightManagementClient': 'latest',
137 'DevTestLabsClient': 'latest',
138 'CosmosDBManagementClient': 'latest',
139 'CdnManagementClient': '2017-04-02',
140 'BatchManagementClient': 'latest',
141 'EventGridManagementClient': '2025-02-15',
142 'AppConfigurationManagementClient': '2024-05-01',
143 'HybridComputeManagementClient': 'latest'
144 },
145 '2019-03-01-hybrid': {
146 'StorageManagementClient': '2017-10-01',
147 'NetworkManagementClient': '2017-10-01',
148 'ComputeManagementClient': SDKProfile('2017-12-01', {
149 'resource_skus': '2017-09-01',
150 'disks': '2017-03-30',
151 'snapshots': '2017-03-30'
152 }),
153 'ManagementLinkClient': '2016-09-01',
154 'ManagementLockClient': '2016-09-01',
155 'PolicyClient': '2016-12-01',
156 'ResourceManagementClient': '2018-05-01',
157 'EventHubManagementClient': '2018-05-04',
158 'SubscriptionClient': '2016-06-01',
159 'DnsManagementClient': '2016-04-01',
160 'KeyVaultManagementClient': '2016-10-01',
161 'AuthorizationManagementClient': SDKProfile('2015-07-01', {
162 'classic_administrators': '2015-06-01',
163 'policy_assignments': '2016-12-01',
164 'policy_definitions': '2016-12-01'
165 }),
166 'KeyVaultClient': '2016-10-01',
167 'azure.multiapi.storage': '2017-11-09',
168 'azure.multiapi.cosmosdb': '2017-04-17'
169 },
170 '2018-03-01-hybrid': {
171 'StorageManagementClient': '2016-01-01',
172 'NetworkManagementClient': '2017-10-01',
173 'ComputeManagementClient': SDKProfile('2017-03-30'),
174 'ManagementLinkClient': '2016-09-01',
175 'ManagementLockClient': '2016-09-01',
176 'PolicyClient': '2016-12-01',
177 'ResourceManagementClient': '2018-02-01',
178 'SubscriptionClient': '2016-06-01',
179 'DnsManagementClient': '2016-04-01',
180 'KeyVaultManagementClient': '2016-10-01',
181 'AuthorizationManagementClient': SDKProfile('2015-07-01', {
182 'classic_administrators': '2015-06-01'
183 }),
184 'KeyVaultClient': '2016-10-01',
185 'azure.multiapi.storage': '2017-04-17',
186 'azure.multiapi.cosmosdb': '2017-04-17'
187 },
188 '2017-03-09-profile': {
189 'StorageManagementClient': '2016-01-01',
190 'NetworkManagementClient': '2015-06-15',
191 'ComputeManagementClient': SDKProfile('2016-03-30'),
192 'ManagementLinkClient': '2016-09-01',
193 'ManagementLockClient': '2015-01-01',
194 'PolicyClient': '2015-10-01-preview',
195 'ResourceManagementClient': '2016-02-01',
196 'SubscriptionClient': '2016-06-01',
197 'DnsManagementClient': '2016-04-01',
198 'KeyVaultManagementClient': '2016-10-01',
199 'AuthorizationManagementClient': SDKProfile('2015-07-01', {
200 'classic_administrators': '2015-06-01'
201 }),
202 'KeyVaultClient': '2016-10-01',
203 'azure.multiapi.storage': '2015-04-05'
204 }
205 }
206
207 AZURE_TAG_ARGS = dict(
208 tags=dict(type='dict'),
209 append_tags=dict(type='bool', default=True),
210 )
211
212 AZURE_COMMON_REQUIRED_IF = [
213 ('log_mode', 'file', ['log_path'])
214 ]
215
216 ANSIBLE_USER_AGENT = 'Ansible/{0}'.format(ANSIBLE_VERSION)
217 CLOUDSHELL_USER_AGENT_KEY = 'AZURE_HTTP_USER_AGENT'
218 VSCODEEXT_USER_AGENT_KEY = 'VSCODEEXT_USER_AGENT'
219
220 CIDR_PATTERN = re.compile(r"(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1"
221 r"[0-9]{2}|2[0-4][0-9]|25[0-5])(/([0-9]|[1-2][0-9]|3[0-2]))")
222
223 AZURE_SUCCESS_STATE = "Succeeded"
224
225 AZURE_IMPORT_ERROR = None
226
227
228 try:
229 import importlib
230 except ImportError:
231 # This passes the sanity import test, but does not provide a user friendly error message.
232 # Doing so would require catching Exception for all imports of Azure dependencies in modules and module_utils.
233 importlib = None
234
235 # Imports
236 try:
237 from enum import Enum
238 from azure.mgmt.core.tools import parse_resource_id, resource_id, is_valid_resource_id
239 from azure.mgmt.network import NetworkManagementClient
240 from azure.mgmt.network import models as NetworkModels
241 from azure.mgmt.resource.resources import ResourceManagementClient
242 from azure.mgmt.managementgroups import ManagementGroupsAPI as ManagementGroupsClient
243 from azure.mgmt.resource.subscriptions import SubscriptionClient
244 from azure.mgmt.storage import StorageManagementClient
245 from azure.mgmt.compute import ComputeManagementClient
246 from azure.mgmt.dns import DnsManagementClient
247 from azure.mgmt.privatedns import PrivateDnsManagementClient
248 import azure.mgmt.privatedns.models as PrivateDnsModels
249 from azure.mgmt.monitor import MonitorManagementClient
250 from azure.mgmt.web import WebSiteManagementClient
251 from azure.mgmt.containerservice import ContainerServiceClient
252 from azure.mgmt.marketplaceordering import MarketplaceOrderingAgreements
253 from azure.mgmt.trafficmanager import TrafficManagerManagementClient
254 from azure.storage.blob import BlobServiceClient
255 from azure.mgmt.authorization import AuthorizationManagementClient
256 from azure.mgmt.sql import SqlManagementClient
257 from azure.mgmt.servicebus import ServiceBusManagementClient
258 from azure.mgmt.rdbms.postgresql import PostgreSQLManagementClient
259 from azure.mgmt.postgresqlflexibleservers import PostgreSQLManagementClient as PostgreSQLFlexibleManagementClient
260 from azure.mgmt.rdbms.mysql import MySQLManagementClient
261 from azure.mgmt.mysqlflexibleservers import MySQLManagementClient as MySQLFlexibleManagementClient
262 from azure.mgmt.rdbms.mariadb import MariaDBManagementClient
263 from azure.mgmt.containerregistry import ContainerRegistryManagementClient
264 from azure.mgmt.containerinstance import ContainerInstanceManagementClient
265 from azure.mgmt.loganalytics import LogAnalyticsManagementClient
266 import azure.mgmt.loganalytics.models as LogAnalyticsModels
267 from azure.mgmt.automation import AutomationClient
268 import azure.mgmt.automation.models as AutomationModel
269 from azure.mgmt.iothub import IotHubClient
270 from azure.mgmt.iothub import models as IoTHubModels
271 from azure.mgmt.resource.locks import ManagementLockClient
272 from azure.mgmt.recoveryservicesbackup import RecoveryServicesBackupClient
273 import azure.mgmt.recoveryservicesbackup.activestamp.models as RecoveryServicesBackupModels
274 from azure.mgmt.search import SearchManagementClient
275 from azure.mgmt.notificationhubs import NotificationHubsManagementClient
276 from azure.mgmt.eventhub import EventHubManagementClient
277 from azure.mgmt.datafactory import DataFactoryManagementClient
278 import azure.mgmt.datafactory.models as DataFactoryModel
279 from azure.identity._credentials import client_secret, user_password, certificate, managed_identity
280 from azure.identity import AzureCliCredential, ClientAssertionCredential
281 from kiota_authentication_azure.azure_identity_authentication_provider import AzureIdentityAuthenticationProvider
282 from msgraph_core import GraphClientFactory, NationalClouds
283 from msgraph import GraphRequestAdapter, GraphServiceClient
284 from azure.mgmt.batch import BatchManagementClient
285 from azure.mgmt.batch import models as BatchManagementModel
286 from azure.mgmt.resourcehealth import ResourceHealthMgmtClient
287 from azure.mgmt.cdn import CdnManagementClient
288 from azure.mgmt.hybridcompute import HybridComputeManagementClient
289
290 except ImportError as exc:
291 AZURE_IMPORT_ERROR = traceback.format_exc()
292
293 from base64 import b64encode, b64decode
294 from hashlib import sha256
295 from hmac import HMAC
296 from time import time
297 import subprocess
298
299 try:
300 from urllib import (urlencode, quote_plus)
301 except ImportError:
302 from urllib.parse import (urlencode, quote_plus)
303
304 try:
305 from azure.cli.core.util import CLIError
306 from azure.cli.core import cloud as azure_cloud
307 except ImportError:
308 CLIError = Exception
309
310
311 def azure_id_to_dict(id):
312 pieces = re.sub(r'^\/', '', id).split('/')
313 result = {}
314 index = 0
315 while index < len(pieces) - 1:
316 result[pieces[index]] = pieces[index + 1]
317 index += 1
318 return result
319
320
321 def format_resource_id(val, subscription_id, namespace, types, resource_group):
322 return resource_id(name=val,
323 resource_group=resource_group,
324 namespace=namespace,
325 type=types,
326 subscription=subscription_id) if not is_valid_resource_id(val) else val
327
328
329 def normalize_location_name(name):
330 return name.replace(' ', '').lower()
331
332
333 def _extract_missing_module(import_error):
334 """
335 Extract missing module name from ImportError traceback.
336 Returns None if not detectable.
337 """
338 if not import_error:
339 return None
340
341 match = re.search(r"No module named '([^']+)'", import_error)
342 if match:
343 return match.group(1)
344
345 return None
346
347
348 class AzureRMModuleBase(object):
349 def __init__(self, derived_arg_spec, bypass_checks=False, no_log=False,
350 check_invalid_arguments=None, mutually_exclusive=None, required_together=None,
351 required_one_of=None, add_file_common_args=False, supports_check_mode=False,
352 required_if=None, supports_tags=True, facts_module=False, skip_exec=False,
353 is_ad_resource=False, required_by=None):
354
355 merged_arg_spec = dict()
356 merged_arg_spec.update(AZURE_COMMON_ARGS)
357 if supports_tags:
358 merged_arg_spec.update(AZURE_TAG_ARGS)
359
360 if derived_arg_spec:
361 merged_arg_spec.update(derived_arg_spec)
362
363 merged_required_if = list(AZURE_COMMON_REQUIRED_IF)
364 if required_if:
365 merged_required_if += required_if
366
367 if not required_by:
368 required_by = dict()
369
370 self.module = AnsibleModule(argument_spec=merged_arg_spec,
371 bypass_checks=bypass_checks,
372 no_log=no_log,
373 mutually_exclusive=mutually_exclusive,
374 required_together=required_together,
375 required_one_of=required_one_of,
376 add_file_common_args=add_file_common_args,
377 supports_check_mode=supports_check_mode,
378 required_if=merged_required_if,
379 required_by=required_by)
380
381 if AZURE_IMPORT_ERROR:
382 missing_mod = _extract_missing_module(AZURE_IMPORT_ERROR)
383
384 if missing_mod:
385 msg = (
386 "Failed to import the required Python library ({0}). "
387 "Please install them by running: "
388 "pip install -r requirements.txt. "
389 "If the required library is installed, but Ansible is using the wrong "
390 "Python interpreter, please consult the documentation on "
391 "ansible_python_interpreter."
392 ).format(missing_mod)
393 else:
394 msg = missing_required_lib("Azure SDK dependencies")
395
396 self.fail(msg=msg, exception=AZURE_IMPORT_ERROR)
397
398 self._authorization_client = None
399 self._network_client = None
400 self._storage_client = None
401 self._subscription_client = None
402 self._management_group_client = None
403 self._resource_client = None
404 self._compute_client = None
405 self._disk_client = None
406 self._image_version_client = None
407 self._multi_disk_client = None
408 self._diskencryptionset_client = None
409 self._image_client = None
410 self._dns_client = None
411 self._private_dns_client = None
412 self._web_client = None
413 self._marketplace_client = None
414 self._sql_client = None
415 self._mysql_client = None
416 self._mysql_flexible_client = None
417 self._mariadb_client = None
418 self._postgresql_client = None
419 self._postgresql_flexible_client = None
420 self._containerregistry_client = None
421 self._containerregistrytoken_client = None
422 self._containerinstance_client = None
423 self._containerservice_client = None
424 self._managedcluster_client = None
425 self._traffic_manager_management_client = None
426 self._monitor_autoscale_settings_client = None
427 self._monitor_log_profiles_client = None
428 self._monitor_diagnostic_settings_client = None
429 self._monitor_data_collection_rules_client = None
430 self._monitor_management_client_action_groups = None
431 self._monitor_management_client_activity_log_alerts = None
432 self._monitor_management_client_metric_alerts = None
433 self._monitor_management_client_scheduled_query_rules = None
434 self._resource = None
435 self._log_analytics_client = None
436 self._servicebus_client = None
437 self._automation_client = None
438 self._IoThub_client = None
439 self._lock_client = None
440 self._recovery_services_backup_client = None
441 self._search_client = None
442 self._datalake_store_client = None
443 self._datafactory_client = None
444 self._notification_hub_client = None
445 self._event_hub_client = None
446 self._batch_account_client = None
447 self._resourcehealth_client = None
448 self._cdn_client = None
449 self._hybrid_compute_management_client = None
450
451 self.check_mode = self.module.check_mode
452 self.api_profile = self.module.params.get('api_profile')
453 self.facts_module = facts_module
454 # self.debug = self.module.params.get('debug')
455
456 # delegate auth to AzureRMAuth class (shared with all plugin types)
457 self.azure_auth = AzureRMAuth(fail_impl=self.fail, is_ad_resource=is_ad_resource, **self.module.params)
458
459 # common parameter validation
460 if self.module.params.get('tags'):
461 self.validate_tags(self.module.params['tags'])
462
463 if not skip_exec:
464 res = self.exec_module(**self.module.params)
465 self.module.exit_json(**res)
466
467 def exec_module(self, **kwargs):
468 self.fail("Error: {0} failed to implement exec_module method.".format(self.__class__.__name__))
469
470 def fail(self, msg, **kwargs):
471 '''
472 Shortcut for calling module.fail()
473
474 :param msg: Error message text.
475 :param kwargs: Any key=value pairs
476 :return: None
477 '''
478 self.module.fail_json(msg=msg, **kwargs)
479
480 def deprecate(self, msg, version=None, collection_name='azure.azcollection'):
481 self.module.deprecate(msg, version, collection_name=collection_name)
482
483 def log(self, msg, pretty_print=False):
484 if pretty_print:
485 self.module.debug(json.dumps(msg, indent=4, sort_keys=True))
486 else:
487 self.module.debug(msg)
488
489 def validate_tags(self, tags):
490 '''
491 Check if tags dictionary contains string:string pairs.
492
493 :param tags: dictionary of string:string pairs
494 :return: None
495 '''
496 if not self.facts_module:
497 if not isinstance(tags, dict):
498 self.fail("Tags must be a dictionary of string:string values.")
499 for key, value in tags.items():
500 if not isinstance(value, str):
501 self.fail("Tags values must be strings. Found {0}:{1}".format(str(key), str(value)))
502
503 def update_tags(self, tags):
504 '''
505 Call from the module to update metadata tags. Returns tuple
506 with bool indicating if there was a change and dict of new
507 tags to assign to the object.
508
509 :param tags: metadata tags from the object
510 :return: bool, dict
511 '''
512 tags = tags or dict()
513 new_tags = copy.copy(tags) if isinstance(tags, dict) else dict()
514 param_tags = self.module.params.get('tags') if isinstance(self.module.params.get('tags'), dict) else dict()
515 append_tags = self.module.params.get('append_tags') if self.module.params.get('append_tags') is not None else True
516 changed = False
517 # check add or update
518 for key, value in param_tags.items():
519 if not new_tags.get(key) or new_tags[key] != value:
520 changed = True
521 new_tags[key] = value
522 # check remove
523 if not append_tags:
524 for key, value in tags.items():
525 if not param_tags.get(key):
526 new_tags.pop(key)
527 changed = True
528 return changed, new_tags
529
530 def has_tags(self, obj_tags, tag_list):
531 '''
532 Used in fact modules to compare object tags to list of parameter tags. Return true if list of parameter tags
533 exists in object tags.
534
535 :param obj_tags: dictionary of tags from an Azure object.
536 :param tag_list: list of tag keys or tag key:value pairs
537 :return: bool
538 '''
539
540 if not obj_tags and tag_list:
541 return False
542
543 if not tag_list:
544 return True
545
546 matches = 0
547 result = False
548 for tag in tag_list:
549 tag_key = tag
550 tag_value = None
551 if ':' in tag:
552 tag_key, tag_value = tag.split(':')
553 if tag_value and obj_tags.get(tag_key) == tag_value:
554 matches += 1
555 elif not tag_value and obj_tags.get(tag_key):
556 matches += 1
557 if matches == len(tag_list):
558 result = True
559 return result
560
561 def get_resource_group(self, resource_group):
562 '''
563 Fetch a resource group.
564
565 :param resource_group: name of a resource group
566 :return: resource group object
567 '''
568 try:
569 return self.rm_client.resource_groups.get(resource_group)
570 except Exception as exc:
571 self.fail("Error retrieving resource group {0} - {1}".format(resource_group, str(exc)))
572
573 def parse_resource_to_dict(self, resource):
574 '''
575 Return a dict of the give resource, which contains name and resource group.
576
577 :param resource: It can be a resource name, id or a dict contains name and resource group.
578 '''
579 resource_dict = parse_resource_id(resource) if not isinstance(resource, dict) else resource
580 resource_dict['resource_group'] = resource_dict.get('resource_group', self.resource_group)
581 if 'subscription_id' in resource_dict:
582 resource_dict['subscription_id'] = resource_dict['subscription_id']
583 else:
584 resource_dict['subscription_id'] = resource_dict.get('subscription', self.subscription_id)
585 return resource_dict
586
587 def serialize_obj(self, obj, class_name, enum_modules=None):
588 '''
589 Return a JSON representation of an Azure object.
590
591 :param obj: Azure object
592 :param class_name: Name of the object's class
593 :param enum_modules: List of module names to build enum dependencies from.
594 :return: serialized result
595 '''
596 return obj.as_dict()
597
598 def get_poller_result(self, poller, wait=5):
599 '''
600 Consistent method of waiting on and retrieving results from Azure's long poller
601
602 :param poller Azure poller object
603 :return object resulting from the original request
604 '''
605 try:
606 delay = wait
607 while not poller.done():
608 self.log("Waiting for {0} sec".format(delay))
609 poller.wait(timeout=delay)
610 return poller.result()
611 except Exception as exc:
612 self.log(str(exc))
613 raise
614
615 def get_multiple_pollers_results(self, pollers, wait=0.05):
616 '''
617 Consistent method of waiting on and retrieving results from multiple Azure's long poller
618
619 :param pollers list of Azure poller object
620 :param wait Period of time to wait for the long running operation to complete.
621 :return list of object resulting from the original request
622 '''
623
624 def _continue_polling():
625 return not all(poller.done() for poller in pollers)
626
627 try:
628 while _continue_polling():
629 for poller in pollers:
630 if poller.done():
631 continue
632 self.log("Waiting for {0} sec".format(wait))
633 poller.wait(timeout=wait)
634 return [poller.result() for poller in pollers]
635 except Exception as exc:
636 self.log(str(exc))
637 raise
638
639 def check_provisioning_state(self, azure_object, requested_state='present'):
640 '''
641 Check an Azure object's provisioning state. If something did not complete the provisioning
642 process, then we cannot operate on it.
643
644 :param azure_object An object such as a subnet, storageaccount, etc. Must have provisioning_state
645 and name attributes.
646 :return None
647 '''
648
649 if hasattr(azure_object, 'properties') and hasattr(azure_object.properties, 'provisioning_state') and \
650 hasattr(azure_object, 'name'):
651 # resource group object fits this model
652 if isinstance(azure_object.properties.provisioning_state, Enum):
653 if azure_object.properties.provisioning_state.value != AZURE_SUCCESS_STATE and \
654 requested_state != 'absent':
655 self.fail("Error {0} has a provisioning state of {1}. Expecting state to be {2}.".format(
656 azure_object.name, azure_object.properties.provisioning_state, AZURE_SUCCESS_STATE))
657 return
658 if azure_object.properties.provisioning_state != AZURE_SUCCESS_STATE and \
659 requested_state != 'absent':
660 self.fail("Error {0} has a provisioning state of {1}. Expecting state to be {2}.".format(
661 azure_object.name, azure_object.properties.provisioning_state, AZURE_SUCCESS_STATE))
662 return
663
664 if hasattr(azure_object, 'provisioning_state') or not hasattr(azure_object, 'name'):
665 if isinstance(azure_object.provisioning_state, Enum):
666 if azure_object.provisioning_state.value != AZURE_SUCCESS_STATE and requested_state != 'absent':
667 self.fail("Error {0} has a provisioning state of {1}. Expecting state to be {2}.".format(
668 azure_object.name, azure_object.provisioning_state, AZURE_SUCCESS_STATE))
669 return
670 if azure_object.provisioning_state != AZURE_SUCCESS_STATE and requested_state != 'absent':
671 self.fail("Error {0} has a provisioning state of {1}. Expecting state to be {2}.".format(
672 azure_object.name, azure_object.provisioning_state, AZURE_SUCCESS_STATE))
673
674 def get_blob_service_client(self, resource_group_name, storage_account_name, auth_mode='key'):
675 try:
676 self.log("Getting storage account detail")
677 account = self.storage_client.storage_accounts.get_properties(resource_group_name=resource_group_name, account_name=storage_account_name)
678 if auth_mode == 'login' and self.azure_auth.credentials.get('credentials'):
679 credential = self.azure_auth.credentials['credentials']
680 elif (auth_mode == 'login' and self.azure_auth.credentials.get('tenant')
681 and self.azure_auth.credentials.get('client_id')
682 and self.azure_auth.credentials.get('secret')):
683 credential = client_secret.ClientSecretCredential(tenant_id=self.azure_auth.credentials.get('tenant'),
684 client_id=self.azure_auth.credentials.get('client_id'),
685 client_secret=self.azure_auth.credentials.get('secret'))
686 else:
687 account_keys = self.storage_client.storage_accounts.list_keys(resource_group_name=resource_group_name, account_name=storage_account_name)
688 credential = account_keys.keys[0].value
689 except Exception as exc:
690 self.fail("Error getting storage account detail for {0}: {1}".format(storage_account_name, str(exc)))
691
692 try:
693 self.log("Create blob service client")
694 return BlobServiceClient(
695 account_url=account.primary_endpoints.blob,
696 credential=credential,
697 )
698 except Exception as exc:
699 self.fail("Error creating blob service client for storage account {0} - {1}".format(storage_account_name, str(exc)))
700
701 def create_default_pip(self, resource_group, location, public_ip_name, allocation_method='Dynamic', sku=None):
702 '''
703 Create a default public IP address <public_ip_name> to associate with a network interface.
704 If a PIP address matching <public_ip_name> exists, return it. Otherwise, create one.
705
706 :param resource_group: name of an existing resource group
707 :param location: a valid azure location
708 :param public_ip_name: base name to assign the public IP address
709 :param allocation_method: one of 'Static' or 'Dynamic'
710 :param sku: sku
711 :return: PIP object
712 '''
713 pip = None
714
715 self.log("Starting create_default_pip {0}".format(public_ip_name))
716 self.log("Check to see if public IP {0} exists".format(public_ip_name))
717 try:
718 pip = self.network_client.public_ip_addresses.get(resource_group, public_ip_name)
719 except Exception:
720 pass
721
722 if pip:
723 self.log("Public ip {0} found.".format(public_ip_name))
724 self.check_provisioning_state(pip)
725 return pip
726
727 params = self.network_models.PublicIPAddress(
728 location=location,
729 public_ip_allocation_method=allocation_method,
730 sku=sku
731 )
732 self.log('Creating default public IP {0}'.format(public_ip_name))
733 try:
734 poller = self.network_client.public_ip_addresses.begin_create_or_update(resource_group, public_ip_name, params)
735 except Exception as exc:
736 self.fail("Error creating {0} - {1}".format(public_ip_name, str(exc)))
737
738 return self.get_poller_result(poller)
739
740 def create_default_securitygroup(self, resource_group, location, security_group_name, os_type, open_ports):
741 '''
742 Create a default security group <security_group_name> to associate with a network interface. If a security group matching
743 <security_group_name> exists, return it. Otherwise, create one.
744
745 :param resource_group: Resource group name
746 :param location: azure location name
747 :param security_group_name: base name to use for the security group
748 :param os_type: one of 'Windows' or 'Linux'. Determins any default rules added to the security group.
749 :param ssh_port: for os_type 'Linux' port used in rule allowing SSH access.
750 :param rdp_port: for os_type 'Windows' port used in rule allowing RDP access.
751 :return: security_group object
752 '''
753 group = None
754
755 self.log("Create security group {0}".format(security_group_name))
756 self.log("Check to see if security group {0} exists".format(security_group_name))
757 try:
758 group = self.network_client.network_security_groups.get(resource_group, security_group_name)
759 except Exception:
760 pass
761
762 if group:
763 self.log("Security group {0} found.".format(security_group_name))
764 self.check_provisioning_state(group)
765 return group
766
767 parameters = self.network_models.NetworkSecurityGroup()
768 parameters.location = location
769
770 if not open_ports:
771 # Open default ports based on OS type
772 if os_type == 'Linux':
773 # add an inbound SSH rule
774 parameters.security_rules = [
775 self.network_models.SecurityRule(protocol='Tcp',
776 source_address_prefix='*',
777 destination_address_prefix='*',
778 access='Allow',
779 direction='Inbound',
780 description='Allow SSH Access',
781 source_port_range='*',
782 destination_port_range='22',
783 priority=100,
784 name='SSH')
785 ]
786 parameters.location = location
787 else:
788 # for windows add inbound RDP and WinRM rules
789 parameters.security_rules = [
790 self.network_models.SecurityRule(protocol='Tcp',
791 source_address_prefix='*',
792 destination_address_prefix='*',
793 access='Allow',
794 direction='Inbound',
795 description='Allow RDP port 3389',
796 source_port_range='*',
797 destination_port_range='3389',
798 priority=100,
799 name='RDP01'),
800 self.network_models.SecurityRule(protocol='Tcp',
801 source_address_prefix='*',
802 destination_address_prefix='*',
803 access='Allow',
804 direction='Inbound',
805 description='Allow WinRM HTTPS port 5986',
806 source_port_range='*',
807 destination_port_range='5986',
808 priority=101,
809 name='WinRM01'),
810 ]
811 else:
812 # Open custom ports
813 parameters.security_rules = []
814 priority = 100
815 for port in open_ports:
816 priority += 1
817 rule_name = "Rule_{0}".format(priority)
818 parameters.security_rules.append(
819 self.network_models.SecurityRule(protocol='Tcp',
820 source_address_prefix='*',
821 destination_address_prefix='*',
822 access='Allow',
823 direction='Inbound',
824 source_port_range='*',
825 destination_port_range=str(port),
826 priority=priority,
827 name=rule_name)
828 )
829
830 self.log('Creating default security group {0}'.format(security_group_name))
831 try:
832 poller = self.network_client.network_security_groups.begin_create_or_update(resource_group,
833 security_group_name,
834 parameters)
835 except Exception as exc:
836 self.fail("Error creating default security rule {0} - {1}".format(security_group_name, str(exc)))
837
838 return self.get_poller_result(poller)
839
840 @staticmethod
841 def _validation_ignore_callback(session, global_config, local_config, **kwargs):
842 session.verify = False
843
844 def get_api_profile(self, client_type_name, api_profile_name):
845 profile_all_clients = AZURE_API_PROFILES.get(api_profile_name)
846
847 if not profile_all_clients:
848 raise KeyError("unknown Azure API profile: {0}".format(api_profile_name))
849
850 profile_raw = profile_all_clients.get(client_type_name, None)
851
852 if not profile_raw:
853 self.module.warn("Azure API profile {0} does not define an entry for {1}".format(api_profile_name, client_type_name))
854
855 if isinstance(profile_raw, dict):
856 if not profile_raw.get('default_api_version'):
857 raise KeyError("Azure API profile {0} does not define 'default_api_version'".format(api_profile_name))
858 return profile_raw
859
860 # wrap basic strings in a dict that just defines the default
861 return dict(default_api_version=profile_raw)
862
863 # The graphrbac has deprecated, migrate to msgraph
864 # def get_graphrbac_client(self, tenant_id):
865 # cred = self.azure_auth.azure_credentials
866 # base_url = self.azure_auth._cloud_environment.endpoints.active_directory_graph_resource_id
867 # client = GraphRbacManagementClient(cred, tenant_id, base_url)
868 # return client
869
870 def get_msgraph_client(self):
871 auth_provider = AzureIdentityAuthenticationProvider(self.azure_auth.azure_credential_track2)
872 cloud_mapping = {
873 azure_cloud.AZURE_CHINA_CLOUD: NationalClouds.China,
874 azure_cloud.AZURE_US_GOV_CLOUD: NationalClouds.US_GOV,
875 azure_cloud.AZURE_GERMAN_CLOUD: NationalClouds.Germany
876 }
877 host = cloud_mapping.get(self._cloud_environment, NationalClouds.Global)
878 client = GraphClientFactory.create_with_default_middleware(host=host)
879 request_adapter = GraphRequestAdapter(auth_provider, client=client)
880 return GraphServiceClient(self.azure_auth.azure_credential_track2, request_adapter=request_adapter)
881
882 def get_mgmt_svc_client(self, client_type, base_url=None, api_version=None, suppress_subscription_id=False):
883 self.log('Getting management service client {0}'.format(client_type.__name__))
884
885 client_argspec = inspect.signature(client_type.__init__)
886
887 if not base_url:
888 # most things are resource_manager, don't make everyone specify
889 base_url = self.azure_auth._cloud_environment.endpoints.resource_manager
890
891 # https://github.com/Azure/msrestazure-for-python/pull/169
892 # China's base_url doesn't end in a trailing slash, though others do,
893 # and we need a trailing slash when generating credential_scopes below.
894 if not base_url.endswith("/"):
895 base_url += "/"
896
897 mgmt_subscription_id = self.subscription_id
898
899 # Some management clients do not take a subscription ID as parameters.
900 if suppress_subscription_id:
901 client_kwargs = dict(credential=self.azure_auth.azure_credential_track2, base_url=base_url, credential_scopes=[base_url + ".default"])
902 else:
903 client_kwargs = dict(credential=self.azure_auth.azure_credential_track2,
904 subscription_id=mgmt_subscription_id, base_url=base_url, credential_scopes=[base_url + ".default"])
905
906 api_profile_dict = {}
907
908 if self.api_profile:
909 api_profile_dict = self.get_api_profile(client_type.__name__, self.api_profile)
910
911 # unversioned clients won't accept profile; only send it if necessary
912 # clients without a version specified in the profile will use the default
913 if api_profile_dict and 'profile' in client_argspec.parameters:
914 client_kwargs['profile'] = api_profile_dict
915
916 # If the client doesn't accept api_version, it's unversioned.
917 # If it does, favor explicitly-specified api_version, fall back to api_profile
918 if 'api_version' in client_argspec.parameters:
919 profile_default_version = api_profile_dict.get('default_api_version', None)
920 if api_version or profile_default_version:
921 client_kwargs['api_version'] = api_version or profile_default_version
922 if 'profile' in client_kwargs:
923 # remove profile; only pass API version if specified
924 client_kwargs.pop('profile')
925
926 client = client_type(**client_kwargs)
927
928 # FUTURE: remove this once everything exposes models directly (eg, containerinstance)
929 try:
930 getattr(client, "models")
931 except AttributeError:
932 def _ansible_get_models(self, *arg, **kwarg):
933 return self._ansible_models
934
935 try:
936 setattr(client, '_ansible_models', importlib.import_module(client_type.__module__).models)
937 except AttributeError:
938 if hasattr(importlib.import_module(client_type.__module__), '_modeles'):
939 setattr(client, '_ansible_models', importlib.import_module(client_type.__module__)._models)
940 else:
941 pass
942 client.models = types.MethodType(_ansible_get_models, client)
943
944 client._config.user_agent_policy = self.add_user_agent(client._config.user_agent_policy)
945
946 if self.azure_auth._cert_validation_mode == 'ignore':
947 client._config.session_configuration_callback = self._validation_ignore_callback
948
949 return client
950
951 def add_user_agent(self, config):
952 # Add user agent for Ansible
953 config.add_user_agent(ANSIBLE_USER_AGENT)
954 # Add user agent when running from Cloud Shell
955 if CLOUDSHELL_USER_AGENT_KEY in os.environ:
956 config.add_user_agent(os.environ[CLOUDSHELL_USER_AGENT_KEY])
957 # Add user agent when running from VSCode extension
958 if VSCODEEXT_USER_AGENT_KEY in os.environ:
959 config.add_user_agent(os.environ[VSCODEEXT_USER_AGENT_KEY])
960 return config
961
962 def generate_sas_token(self, **kwags):
963 base_url = kwags.get('base_url', None)
964 expiry = kwags.get('expiry', time() + 3600)
965 key = kwags.get('key', None)
966 policy = kwags.get('policy', None)
967 url = quote_plus(base_url)
968 ttl = int(expiry)
969 sign_key = '{0}\n{1}'.format(url, ttl)
970 signature = b64encode(HMAC(b64decode(key), sign_key.encode('utf-8'), sha256).digest())
971 result = {
972 'sr': url,
973 'sig': signature,
974 'se': str(ttl),
975 }
976 if policy:
977 result['skn'] = policy
978 return 'SharedAccessSignature ' + urlencode(result)
979
980 def get_subnet_detail(self, subnet_id):
981 vnet_detail = subnet_id.split('/Microsoft.Network/virtualNetworks/')[1].split('/subnets/')
982 return dict(
983 resource_group=subnet_id.split('resourceGroups/')[1].split('/')[0],
984 vnet_name=vnet_detail[0],
985 subnet_name=vnet_detail[1],
986 )
987
988 # passthru methods to AzureAuth instance for backcompat
989 @property
990 def credentials(self):
991 return self.azure_auth.credentials
992
993 @property
994 def _cloud_environment(self):
995 return self.azure_auth._cloud_environment
996
997 @property
998 def subscription_id(self):
999 return self.azure_auth.subscription_id
1000
1001 @property
1002 def storage_client(self):
1003 self.log('Getting storage client...')
1004 if not self._storage_client:
1005 self._storage_client = self.get_mgmt_svc_client(StorageManagementClient,
1006 base_url=self._cloud_environment.endpoints.resource_manager,
1007 api_version='2023-05-01')
1008 return self._storage_client
1009
1010 @property
1011 def storage_models(self):
1012 return StorageManagementClient.models("2023-05-01")
1013
1014 @property
1015 def authorization_client(self):
1016 self.log('Getting authorization client...')
1017 if not self._authorization_client:
1018 self._authorization_client = self.get_mgmt_svc_client(AuthorizationManagementClient,
1019 base_url=self._cloud_environment.endpoints.resource_manager,
1020 api_version='2020-04-01-preview')
1021 return self._authorization_client
1022
1023 @property
1024 def authorization_models(self):
1025 return AuthorizationManagementClient.models('2020-04-01-preview')
1026
1027 @property
1028 def subscription_client(self):
1029 self.log('Getting subscription client...')
1030 if not self._subscription_client:
1031 self._subscription_client = self.get_mgmt_svc_client(SubscriptionClient,
1032 base_url=self._cloud_environment.endpoints.resource_manager,
1033 suppress_subscription_id=True,
1034 api_version='2022-12-01')
1035 return self._subscription_client
1036
1037 @property
1038 def subscription_models(self):
1039 return SubscriptionClient.models("2022-12-01")
1040
1041 @property
1042 def management_groups_client(self):
1043 self.log('Getting Management Groups client...')
1044 if not self._management_group_client:
1045 self._management_group_client = self.get_mgmt_svc_client(ManagementGroupsClient,
1046 base_url=self._cloud_environment.endpoints.resource_manager,
1047 suppress_subscription_id=True,
1048 api_version='2020-05-01')
1049 return self._management_group_client
1050
1051 @property
1052 def network_client(self):
1053 self.log('Getting network client')
1054 if not self._network_client:
1055 self._network_client = self.get_mgmt_svc_client(NetworkManagementClient,
1056 base_url=self._cloud_environment.endpoints.resource_manager,
1057 api_version='2024-01-01')
1058 return self._network_client
1059
1060 @property
1061 def network_models(self):
1062 self.log("Getting network models...")
1063 return NetworkModels
1064
1065 @property
1066 def rm_client(self):
1067 self.log('Getting resource manager client')
1068 if not self._resource_client:
1069 self._resource_client = self.get_mgmt_svc_client(ResourceManagementClient,
1070 base_url=self._cloud_environment.endpoints.resource_manager,
1071 api_version='2022-09-01')
1072 return self._resource_client
1073
1074 @property
1075 def rm_models(self):
1076 self.log("Getting resource manager models")
1077 return ResourceManagementClient.models("2022-09-01")
1078
1079 @property
1080 def image_client(self):
1081 self.log('Getting compute image client')
1082 if not self._image_client:
1083 self._image_client = self.get_mgmt_svc_client(ComputeManagementClient,
1084 base_url=self._cloud_environment.endpoints.resource_manager,
1085 api_version='2024-07-01')
1086 return self._image_client
1087
1088 @property
1089 def image_models(self):
1090 self.log("Getting compute image models")
1091 return ComputeManagementClient.models("2024-07-01")
1092
1093 @property
1094 def compute_client(self):
1095 self.log('Getting compute client')
1096 if not self._compute_client:
1097 self._compute_client = self.get_mgmt_svc_client(ComputeManagementClient,
1098 base_url=self._cloud_environment.endpoints.resource_manager,
1099 api_version='2024-07-01')
1100 return self._compute_client
1101
1102 @property
1103 def compute_models(self):
1104 self.log("Getting compute models")
1105 return ComputeManagementClient.models("2024-07-01")
1106
1107 @property
1108 def disk_client(self):
1109 self.log('Getting disk client')
1110 if not self._disk_client:
1111 self._disk_client = self.get_mgmt_svc_client(ComputeManagementClient,
1112 base_url=self._cloud_environment.endpoints.resource_manager,
1113 api_version='2023-04-02')
1114 return self._disk_client
1115
1116 @property
1117 def disk_models(self):
1118 self.log("Getting disk models")
1119 return ComputeManagementClient.models("2023-04-02")
1120
1121 @property
1122 def image_version_client(self):
1123 self.log('Getting gallery image version client')
1124 if not self._image_version_client:
1125 self._image_version_client = self.get_mgmt_svc_client(ComputeManagementClient,
1126 base_url=self._cloud_environment.endpoints.resource_manager,
1127 api_version='2023-07-03')
1128 return self._image_version_client
1129
1130 @property
1131 def image_version_models(self):
1132 self.log("Getting image version models")
1133 return ComputeManagementClient.models("2023-07-03")
1134
1135 @property
1136 def multi_disk_client(self):
1137 self.log('Getting disk client')
1138 if not self._multi_disk_client:
1139 self._multi_disk_client = self.get_mgmt_svc_client(ComputeManagementClient,
1140 base_url=self._cloud_environment.endpoints.resource_manager,
1141 api_version='2021-04-01')
1142 return self._multi_disk_client
1143
1144 @property
1145 def multi_disk_models(self):
1146 self.log("Getting disk models")
1147 return ComputeManagementClient.models("2021-04-01")
1148
1149 @property
1150 def diskencryptionset_client(self):
1151 self.log('Getting diskencryptionset client')
1152 base_url = self._cloud_environment.endpoints.resource_manager
1153 if not self._diskencryptionset_client:
1154 self._diskencryptionset_client = self.get_mgmt_svc_client(ComputeManagementClient,
1155 base_url=base_url,
1156 api_version='2024-03-02')
1157 return self._diskencryptionset_client
1158
1159 @property
1160 def diskencryptionset_models(self):
1161 self.log("Getting compute models")
1162 return ComputeManagementClient.models("2024-03-02")
1163
1164 @property
1165 def dns_client(self):
1166 self.log('Getting dns client')
1167 if not self._dns_client:
1168 self._dns_client = self.get_mgmt_svc_client(DnsManagementClient,
1169 base_url=self._cloud_environment.endpoints.resource_manager,
1170 api_version='2023-07-01-preview')
1171 return self._dns_client
1172
1173 @property
1174 def dns_models(self):
1175 self.log("Getting dns models...")
1176 return DnsManagementClient.models('2023-07-01-preview')
1177
1178 @property
1179 def private_dns_client(self):
1180 self.log('Getting private dns client')
1181 if not self._private_dns_client:
1182 self._private_dns_client = self.get_mgmt_svc_client(
1183 PrivateDnsManagementClient,
1184 base_url=self._cloud_environment.endpoints.resource_manager)
1185 return self._private_dns_client
1186
1187 @property
1188 def private_dns_models(self):
1189 self.log('Getting private dns models')
1190 return PrivateDnsModels
1191
1192 @property
1193 def web_client(self):
1194 self.log('Getting web client')
1195 if not self._web_client:
1196 self._web_client = self.get_mgmt_svc_client(WebSiteManagementClient,
1197 base_url=self._cloud_environment.endpoints.resource_manager,
1198 api_version='2023-12-01')
1199 return self._web_client
1200
1201 @property
1202 def containerservice_client(self):
1203 self.log('Getting container service client')
1204 if not self._containerservice_client:
1205 self._containerservice_client = self.get_mgmt_svc_client(ContainerServiceClient,
1206 base_url=self._cloud_environment.endpoints.resource_manager,
1207 api_version='2019-04-01')
1208 return self._containerservice_client
1209
1210 @property
1211 def managedcluster_models(self):
1212 self.log("Getting container service models")
1213 return ContainerServiceClient.models('2024-08-01')
1214
1215 @property
1216 def managedcluster_client(self):
1217 self.log('Getting container service client')
1218 if not self._managedcluster_client:
1219 self._managedcluster_client = self.get_mgmt_svc_client(ContainerServiceClient,
1220 base_url=self._cloud_environment.endpoints.resource_manager,
1221 api_version='2024-08-01')
1222 return self._managedcluster_client
1223
1224 @property
1225 def sql_client(self):
1226 self.log('Getting SQL client')
1227 if not self._sql_client:
1228 self._sql_client = self.get_mgmt_svc_client(SqlManagementClient,
1229 base_url=self._cloud_environment.endpoints.resource_manager)
1230 return self._sql_client
1231
1232 @property
1233 def postgresql_flexible_client(self):
1234 self.log('Getting PostgreSQL client')
1235 if not self._postgresql_flexible_client:
1236 self._postgresql_flexible_client = self.get_mgmt_svc_client(PostgreSQLFlexibleManagementClient,
1237 base_url=self._cloud_environment.endpoints.resource_manager,
1238 api_version='2025-08-01')
1239 return self._postgresql_flexible_client
1240
1241 @property
1242 def postgresql_client(self):
1243 self.log('Getting PostgreSQL client')
1244 if not self._postgresql_client:
1245 self._postgresql_client = self.get_mgmt_svc_client(PostgreSQLManagementClient,
1246 base_url=self._cloud_environment.endpoints.resource_manager)
1247 return self._postgresql_client
1248
1249 @property
1250 def mysql_flexible_client(self):
1251 self.log('Getting MySQL Flexible client')
1252 if not self._mysql_flexible_client:
1253 self._mysql_flexible_client = self.get_mgmt_svc_client(MySQLFlexibleManagementClient,
1254 base_url=self._cloud_environment.endpoints.resource_manager,
1255 api_version='2024-08-01')
1256 return self._mysql_flexible_client
1257
1258 @property
1259 def mysql_client(self):
1260 self.log('Getting MySQL client')
1261 if not self._mysql_client:
1262 self._mysql_client = self.get_mgmt_svc_client(MySQLManagementClient,
1263 base_url=self._cloud_environment.endpoints.resource_manager)
1264 return self._mysql_client
1265
1266 @property
1267 def mariadb_client(self):
1268 self.log('Getting MariaDB client')
1269 if not self._mariadb_client:
1270 self._mariadb_client = self.get_mgmt_svc_client(MariaDBManagementClient,
1271 base_url=self._cloud_environment.endpoints.resource_manager)
1272 return self._mariadb_client
1273
1274 @property
1275 def containerregistry_client(self):
1276 self.log('Getting container registry mgmt client')
1277 if not self._containerregistry_client:
1278 self._containerregistry_client = self.get_mgmt_svc_client(ContainerRegistryManagementClient,
1279 base_url=self._cloud_environment.endpoints.resource_manager,
1280 api_version='2021-09-01')
1281
1282 return self._containerregistry_client
1283
1284 @property
1285 def containerregistrytoken_client(self):
1286 self.log('Getting container registry token mgmt client')
1287 if not self._containerregistrytoken_client:
1288 self._containerregistrytoken_client = self.get_mgmt_svc_client(ContainerRegistryManagementClient,
1289 base_url=self._cloud_environment.endpoints.resource_manager,
1290 api_version='2023-07-01')
1291
1292 return self._containerregistrytoken_client
1293
1294 @property
1295 def containerinstance_client(self):
1296 self.log('Getting container instance mgmt client')
1297 if not self._containerinstance_client:
1298 self._containerinstance_client = self.get_mgmt_svc_client(ContainerInstanceManagementClient,
1299 base_url=self._cloud_environment.endpoints.resource_manager,
1300 api_version='2023-05-01')
1301
1302 return self._containerinstance_client
1303
1304 @property
1305 def marketplace_client(self):
1306 self.log('Getting marketplace agreement client')
1307 if not self._marketplace_client:
1308 self._marketplace_client = self.get_mgmt_svc_client(MarketplaceOrderingAgreements,
1309 base_url=self._cloud_environment.endpoints.resource_manager)
1310 return self._marketplace_client
1311
1312 @property
1313 def traffic_manager_management_client(self):
1314 self.log('Getting traffic manager client')
1315 if not self._traffic_manager_management_client:
1316 self._traffic_manager_management_client = self.get_mgmt_svc_client(TrafficManagerManagementClient,
1317 base_url=self._cloud_environment.endpoints.resource_manager)
1318 return self._traffic_manager_management_client
1319
1320 @property
1321 def monitor_autoscale_settings_client(self):
1322 self.log('Getting monitor client for autoscale_settings')
1323 if not self._monitor_autoscale_settings_client:
1324 self._monitor_autoscale_settings_client = self.get_mgmt_svc_client(MonitorManagementClient,
1325 base_url=self._cloud_environment.endpoints.resource_manager,
1326 api_version="2022-10-01")
1327 return self._monitor_autoscale_settings_client
1328
1329 @property
1330 def monitor_log_profiles_client(self):
1331 self.log('Getting monitor client for log_profiles')
1332 if not self._monitor_log_profiles_client:
1333 self._monitor_log_profiles_client = self.get_mgmt_svc_client(MonitorManagementClient,
1334 base_url=self._cloud_environment.endpoints.resource_manager,
1335 api_version="2016-03-01")
1336 return self._monitor_log_profiles_client
1337
1338 @property
1339 def monitor_diagnostic_settings_client(self):
1340 self.log('Getting monitor client for diagnostic_settings')
1341 if not self._monitor_diagnostic_settings_client:
1342 self._monitor_diagnostic_settings_client = self.get_mgmt_svc_client(MonitorManagementClient,
1343 base_url=self._cloud_environment.endpoints.resource_manager,
1344 api_version="2021-05-01-preview")
1345 return self._monitor_diagnostic_settings_client
1346
1347 @property
1348 def monitor_management_client_action_groups(self):
1349 self.log('Getting monitor client for diagnostic_settings')
1350 if not self._monitor_management_client_action_groups:
1351 self._monitor_management_client_action_groups = self.get_mgmt_svc_client(MonitorManagementClient,
1352 base_url=self._cloud_environment.endpoints.resource_manager,
1353 api_version='2023-01-01')
1354 return self._monitor_management_client_action_groups
1355
1356 @property
1357 def monitor_management_client_activity_log_alerts(self):
1358 self.log('Getting monitor client for diagnostic_settings')
1359 if not self._monitor_management_client_activity_log_alerts:
1360 self._monitor_management_client_activity_log_alerts = self.get_mgmt_svc_client(MonitorManagementClient,
1361 base_url=self._cloud_environment.endpoints.resource_manager,
1362 api_version='2020-10-01')
1363 return self._monitor_management_client_activity_log_alerts
1364
1365 @property
1366 def monitor_management_client_data_collection_rules(self):
1367 self.log('Getting monitor client for diagnostic_settings')
1368 if not self._monitor_data_collection_rules_client:
1369 self._monitor_data_collection_rules_client = self.get_mgmt_svc_client(MonitorManagementClient,
1370 base_url=self._cloud_environment.endpoints.resource_manager,
1371 api_version='2022-06-01')
1372 return self._monitor_data_collection_rules_client
1373
1374 @property
1375 def monitor_management_client_metric_alerts(self):
1376 self.log('Getting monitor client for diagnostic_settings')
1377 if not self._monitor_management_client_metric_alerts:
1378 self._monitor_management_client_metric_alerts = self.get_mgmt_svc_client(MonitorManagementClient,
1379 base_url=self._cloud_environment.endpoints.resource_manager,
1380 api_version='2018-03-01')
1381 return self._monitor_management_client_metric_alerts
1382
1383 @property
1384 def monitor_management_client_scheduled_query_rules(self):
1385 self.log('Getting monitor client for scheduled query rules')
1386 if not self._monitor_management_client_scheduled_query_rules:
1387 self._monitor_management_client_scheduled_query_rules = self.get_mgmt_svc_client(MonitorManagementClient,
1388 base_url=self._cloud_environment.endpoints.resource_manager,
1389 api_version='2018-04-16')
1390 return self._monitor_management_client_scheduled_query_rules
1391
1392 @property
1393 def log_analytics_client(self):
1394 self.log('Getting log analytics client')
1395 if not self._log_analytics_client:
1396 self._log_analytics_client = self.get_mgmt_svc_client(LogAnalyticsManagementClient,
1397 base_url=self._cloud_environment.endpoints.resource_manager)
1398 return self._log_analytics_client
1399
1400 @property
1401 def log_analytics_models(self):
1402 self.log('Getting log analytics models')
1403 return LogAnalyticsModels
1404
1405 @property
1406 def servicebus_client(self):
1407 self.log('Getting servicebus client')
1408 if not self._servicebus_client:
1409 self._servicebus_client = self.get_mgmt_svc_client(ServiceBusManagementClient,
1410 api_version="2022-10-01-preview",
1411 base_url=self._cloud_environment.endpoints.resource_manager)
1412 return self._servicebus_client
1413
1414 @property
1415 def servicebus_models(self):
1416 return ServiceBusManagementClient.models("2022-10-01-preview")
1417
1418 @property
1419 def automation_client(self):
1420 self.log('Getting automation client')
1421 if not self._automation_client:
1422 self._automation_client = self.get_mgmt_svc_client(AutomationClient,
1423 base_url=self._cloud_environment.endpoints.resource_manager)
1424 return self._automation_client
1425
1426 @property
1427 def automation_models(self):
1428 return AutomationModel
1429
1430 @property
1431 def IoThub_client(self):
1432 self.log('Getting iothub client')
1433 if not self._IoThub_client:
1434 self._IoThub_client = self.get_mgmt_svc_client(IotHubClient,
1435 api_version='2023-06-30-preview',
1436 base_url=self._cloud_environment.endpoints.resource_manager)
1437 return self._IoThub_client
1438
1439 @property
1440 def IoThub_models(self):
1441 return IoTHubModels
1442
1443 @property
1444 def lock_client(self):
1445 self.log('Getting lock client')
1446 if not self._lock_client:
1447 self._lock_client = self.get_mgmt_svc_client(ManagementLockClient,
1448 base_url=self._cloud_environment.endpoints.resource_manager,
1449 api_version='2016-09-01')
1450 return self._lock_client
1451
1452 @property
1453 def lock_models(self):
1454 self.log("Getting lock models")
1455 return ManagementLockClient.models('2016-09-01')
1456
1457 @property
1458 def recovery_services_backup_client(self):
1459 self.log('Getting recovery services backup client')
1460 if not self._recovery_services_backup_client:
1461 self._recovery_services_backup_client = self.get_mgmt_svc_client(RecoveryServicesBackupClient,
1462 base_url=self._cloud_environment.endpoints.resource_manager)
1463 return self._recovery_services_backup_client
1464
1465 @property
1466 def recovery_services_backup_models(self):
1467 return RecoveryServicesBackupModels
1468
1469 @property
1470 def search_client(self):
1471 self.log('Getting search client...')
1472 if not self._search_client:
1473 self._search_client = self.get_mgmt_svc_client(SearchManagementClient,
1474 base_url=self._cloud_environment.endpoints.resource_manager,
1475 api_version='2024-06-01-preview')
1476 return self._search_client
1477
1478 @property
1479 def notification_hub_client(self):
1480 self.log('Getting notification hub client')
1481 if not self._notification_hub_client:
1482 self._notification_hub_client = self.get_mgmt_svc_client(
1483 NotificationHubsManagementClient,
1484 base_url=self._cloud_environment.endpoints.resource_manager,
1485 api_version='2023-09-01')
1486 return self._notification_hub_client
1487
1488 @property
1489 def event_hub_client(self):
1490 self.log('Getting event hub client')
1491 if not self._event_hub_client:
1492 self._event_hub_client = self.get_mgmt_svc_client(
1493 EventHubManagementClient,
1494 base_url=self._cloud_environment.endpoints.resource_manager,
1495 api_version='2024-01-01')
1496 return self._event_hub_client
1497
1498 @property
1499 def datafactory_client(self):
1500 self.log('Getting datafactory client...')
1501 if not self._datafactory_client:
1502 self._datafactory_client = self.get_mgmt_svc_client(DataFactoryManagementClient,
1503 base_url=self._cloud_environment.endpoints.resource_manager)
1504 return self._datafactory_client
1505
1506 @property
1507 def datafactory_model(self):
1508 return DataFactoryModel
1509
1510 @property
1511 def batch_account_client(self):
1512 self.log('Getting batch account client...')
1513 if not self._batch_account_client:
1514 self._batch_account_client = self.get_mgmt_svc_client(BatchManagementClient,
1515 base_url=self._cloud_environment.endpoints.resource_manager)
1516 return self._batch_account_client
1517
1518 @property
1519 def resourcehealth_client(self):
1520 self.log('Getting resource health client...')
1521 if not self._resourcehealth_client:
1522 self._resourcehealth_client = self.get_mgmt_svc_client(ResourceHealthMgmtClient,
1523 base_url=self._cloud_environment.endpoints.resource_manager)
1524 return self._resourcehealth_client
1525
1526 @property
1527 def batch_account_model(self):
1528 return BatchManagementModel
1529
1530 @property
1531 def cdn_client(self):
1532 self.log('Getting cdn client...')
1533 if not self._cdn_client:
1534 self._cdn_client = self.get_mgmt_svc_client(CdnManagementClient,
1535 base_url=self._cloud_environment.endpoints.resource_manager,
1536 api_version='2024-02-01')
1537 return self._cdn_client
1538
1539 @property
1540 def hybrid_compute_management_client(self):
1541 self.log('Getting hybrid compute management client...')
1542 if not self._hybrid_compute_management_client:
1543 self._hybrid_compute_management_client = self.get_mgmt_svc_client(HybridComputeManagementClient,
1544 base_url=self._cloud_environment.endpoints.resource_manager)
1545 return self._hybrid_compute_management_client
1546
1547
1548 class AzureRMAuthException(Exception):
1549 pass
1550
1551
1552 class AzureRMAuth(object):
1553 _cloud_environment = None
1554 _adfs_authority_url = None
1555
1556 def __init__(self, auth_source=None, profile=None, subscription_id=None, client_id=None, secret=None,
1557 tenant=None, ad_user=None, password=None, cloud_environment='AzureCloud', cert_validation_mode='validate',
1558 api_profile='latest', adfs_authority_url=None, fail_impl=None, is_ad_resource=False,
1559 x509_certificate_path=None, thumbprint=None, oidc_token=None, oidc_token_file_path=None, track1_cred=False,
1560 disable_instance_discovery=False , **kwargs):
1561
1562 if fail_impl:
1563 self._fail_impl = fail_impl
1564 else:
1565 self._fail_impl = self._default_fail_impl
1566 self.is_ad_resource = is_ad_resource
1567
1568 # authenticate
1569 self.credentials = self._get_credentials(
1570 auth_source=auth_source,
1571 profile=profile,
1572 subscription_id=subscription_id,
1573 client_id=client_id,
1574 secret=secret,
1575 tenant=tenant,
1576 ad_user=ad_user,
1577 password=password,
1578 cloud_environment=cloud_environment,
1579 cert_validation_mode=cert_validation_mode,
1580 api_profile=api_profile,
1581 adfs_authority_url=adfs_authority_url,
1582 x509_certificate_path=x509_certificate_path,
1583 thumbprint=thumbprint,
1584 disable_instance_discovery=disable_instance_discovery,
1585 oidc_token=oidc_token,
1586 oidc_token_file_path=oidc_token_file_path)
1587
1588 if not self.credentials:
1589 self.fail("Failed to get credentials. Either pass as parameters, set environment variables, "
1590 "define a profile in ~/.azure/credentials, or log in with Azure CLI (`az login`).")
1591
1592 # cert validation mode precedence: module-arg, credential profile, env, "validate"
1593 self._cert_validation_mode = cert_validation_mode or \
1594 self.credentials.get('cert_validation_mode') or \
1595 self._get_env('cert_validation_mode') or \
1596 'validate'
1597
1598 if self._cert_validation_mode not in ['validate', 'ignore']:
1599 self.fail('invalid cert_validation_mode: {0}'.format(self._cert_validation_mode))
1600
1601 # Disable instance discovery: module-arg, credential profile, env, "False"
1602 self._disable_instance_discovery = disable_instance_discovery or \
1603 self.credentials.get('disable_instance_discovery') or \
1604 self._get_env('disable_instance_discovery') or \
1605 False
1606
1607 # if cloud_environment specified, look up/build Cloud object
1608 raw_cloud_env = self.credentials.get('cloud_environment')
1609 if self.credentials.get('credentials') is not None and raw_cloud_env is not None:
1610 self._cloud_environment = raw_cloud_env
1611 elif not raw_cloud_env:
1612 self._cloud_environment = azure_cloud.AZURE_PUBLIC_CLOUD # SDK default
1613 else:
1614 # try to look up "well-known" values via the name attribute on azure_cloud members
1615 all_clouds = [x[1] for x in inspect.getmembers(azure_cloud) if isinstance(x[1], azure_cloud.Cloud)]
1616 matched_clouds = [x for x in all_clouds if x.name == raw_cloud_env]
1617 if len(matched_clouds) == 1:
1618 self._cloud_environment = matched_clouds[0]
1619 elif len(matched_clouds) > 1:
1620 self.fail("Azure SDK failure: more than one cloud matched for cloud_environment name '{0}'".format(raw_cloud_env))
1621 else:
1622 if not urlparse.urlparse(raw_cloud_env).scheme:
1623 self.fail("cloud_environment must be an endpoint discovery URL or one of {0}".format([x.name for x in all_clouds]))
1624 try:
1625 self._cloud_environment = self._get_cloud_from_metadata_endpoint(raw_cloud_env)
1626 except Exception as e:
1627 self.fail("cloud_environment {0} could not be resolved: {1}".format(raw_cloud_env, e.message), exception=traceback.format_exc())
1628
1629 if self.credentials.get('subscription_id', None) is None and not self.is_ad_resource:
1630 self.fail("Credentials did not include a subscription_id value.")
1631 self.log("setting subscription_id")
1632 self.subscription_id = self.credentials.get('subscription_id')
1633
1634 # get authentication authority
1635 # for adfs, user could pass in authority or not.
1636 # for others, use default authority from cloud environment
1637 if self.credentials.get('adfs_authority_url') is None:
1638 self._adfs_authority_url = self._cloud_environment.endpoints.active_directory
1639 else:
1640 self._adfs_authority_url = self.credentials.get('adfs_authority_url')
1641
1642 if self.credentials.get('auth_source') == 'msi':
1643 # MSI Credentials
1644 self.azure_credential_track2 = self.credentials['credentials']
1645 elif self.credentials.get('credentials') is not None:
1646 # AzureCLI credentials
1647 self.azure_credential_track2 = self.credentials['credentials']
1648 # OIDC direct token
1649 elif self.credentials.get('client_id') is not None and \
1650 self.credentials.get('tenant') is not None and \
1651 self.credentials.get('oidc_token') is not None:
1652 token = self.credentials['oidc_token']
1653
1654 def _load_assertion():
1655 return token
1656
1657 self.azure_credential_track2 = ClientAssertionCredential(tenant_id=self.credentials['tenant'],
1658 client_id=self.credentials['client_id'],
1659 func=_load_assertion,
1660 authority=self._adfs_authority_url,
1661 disable_instance_discovery=self._disable_instance_discovery)
1662 # OIDC token file
1663 elif self.credentials.get('client_id') is not None and \
1664 self.credentials.get('tenant') is not None and \
1665 self.credentials.get('oidc_token_file_path') is not None:
1666 token_file = self.credentials['oidc_token_file_path']
1667
1668 if not os.path.exists(token_file):
1669 self.fail(f"The specified OIDC token file does not exist: {token_file}")
1670
1671 def _load_assertion():
1672 with open(token_file) as f:
1673 return f.read()
1674
1675 self.azure_credential_track2 = ClientAssertionCredential(tenant_id=self.credentials['tenant'],
1676 client_id=self.credentials['client_id'],
1677 func=_load_assertion,
1678 authority=self._adfs_authority_url,
1679 disable_instance_discovery=self._disable_instance_discovery)
1680
1681 elif self.credentials.get('client_id') is not None and \
1682 self.credentials.get('secret') is not None and \
1683 self.credentials.get('tenant') is not None:
1684 self.azure_credential_track2 = client_secret.ClientSecretCredential(client_id=self.credentials['client_id'],
1685 client_secret=self.credentials['secret'],
1686 tenant_id=self.credentials['tenant'],
1687 authority=self._adfs_authority_url,
1688 disable_instance_discovery=self._disable_instance_discovery)
1689
1690 elif self.credentials.get('client_id') is not None and \
1691 self.credentials.get('tenant') is not None and \
1692 self.credentials.get('thumbprint') is not None and \
1693 self.credentials.get('x509_certificate_path') is not None:
1694 self.azure_credential_track2 = certificate.CertificateCredential(tenant_id=self.credentials['tenant'],
1695 client_id=self.credentials['client_id'],
1696 certificate_path=self.credentials['x509_certificate_path'],
1697 authority=self._adfs_authority_url,
1698 disable_instance_discovery=self._disable_instance_discovery)
1699
1700 elif self.credentials.get('ad_user') is not None and \
1701 self.credentials.get('password') is not None and \
1702 self.credentials.get('client_id') is not None and \
1703 self.credentials.get('tenant') is not None:
1704 self.azure_credential_track2 = user_password.UsernamePasswordCredential(username=self.credentials['ad_user'],
1705 password=self.credentials['password'],
1706 tenant_id=self.credentials.get('tenant'),
1707 client_id=self.credentials.get('client_id'),
1708 authority=self._adfs_authority_url,
1709 disable_instance_discovery=self._disable_instance_discovery)
1710
1711 elif self.credentials.get('ad_user') is not None and self.credentials.get('password') is not None:
1712 client_id = self.credentials.get('client_id')
1713 if client_id is None:
1714 client_id = '04b07795-8ddb-461a-bbee-02f9e1bf7b46'
1715 self.azure_credential_track2 = user_password.UsernamePasswordCredential(username=self.credentials['ad_user'],
1716 password=self.credentials['password'],
1717 tenant_id=self.credentials.get('tenant', 'organizations'),
1718 client_id=client_id,
1719 authority=self._adfs_authority_url,
1720 disable_instance_discovery=self._disable_instance_discovery)
1721
1722 else:
1723 self.fail("Failed to authenticate with provided credentials. Some attributes were missing. \n\n"
1724 "Supported authentication methods: \n"
1725 "- Workload identity (OIDC) token: client_id, tenant, and oidc_token\n"
1726 "- Workload identity (OIDC) token file: client_id, tenant, and oidc_token_file_path\n"
1727 "- Service principal with client secret: client_id, tenant, secret\n"
1728 "- Service principal with certificate: client_id, tenant, x509_certificate_path\n"
1729 "- Username/password authentication: ad_user, password\n"
1730 "- Azure CLI authentication: run `az_login`.\n")
1731
1732 def fail(self, msg, exception=None, **kwargs):
1733 self._fail_impl(msg)
1734
1735 def _default_fail_impl(self, msg, exception=None, **kwargs):
1736 raise AzureRMAuthException(msg)
1737
1738 def _get_env(self, module_key, default=None):
1739 "Read envvar matching module parameter"
1740 return os.environ.get(AZURE_CREDENTIAL_ENV_MAPPING[module_key], default)
1741
1742 def _get_profile(self, profile="default", subscription_id=None):
1743 path = expanduser("~/.azure/credentials")
1744 try:
1745 config = configparser.ConfigParser()
1746 config.read(path)
1747 except Exception as exc:
1748 self.fail("Failed to access {0}. Check that the file exists and you have read "
1749 "access. {1}".format(path, str(exc)))
1750 credentials = dict()
1751 for key in AZURE_CREDENTIAL_ENV_MAPPING:
1752 try:
1753 credentials[key] = config.get(profile, key, raw=True)
1754 except Exception:
1755 pass
1756
1757 if credentials.get('subscription_id') is None and not self.is_ad_resource:
1758 return None
1759
1760 if subscription_id is not None:
1761 credentials['subscription_id'] = subscription_id
1762
1763 return credentials
1764
1765 def _get_msi_credentials(self, subscription_id=None, client_id=None, _cloud_environment=None, **kwargs):
1766 # Get object `cloud_environment` from string `_cloud_environment`
1767 cloud_environment = None
1768 if not _cloud_environment:
1769 cloud_environment = azure_cloud.AZURE_PUBLIC_CLOUD
1770 else:
1771 # try to look up "well-known" values via the name attribute on azure_cloud members
1772 all_clouds = [x[1] for x in inspect.getmembers(azure_cloud) if isinstance(x[1], azure_cloud.Cloud)]
1773 matched_clouds = [x for x in all_clouds if x.name == _cloud_environment]
1774 if len(matched_clouds) == 1:
1775 cloud_environment = matched_clouds[0]
1776 elif len(matched_clouds) > 1:
1777 self.fail("Azure SDK failure: more than one cloud matched for cloud_environment name '{0}'".format(_cloud_environment))
1778 else:
1779 if not urlparse.urlparse(_cloud_environment).scheme:
1780 self.fail("cloud_environment must be an endpoint discovery URL or one of {0}".format([x.name for x in all_clouds]))
1781 try:
1782 cloud_environment = self._get_cloud_from_metadata_endpoint(_cloud_environment)
1783 except Exception as exc:
1784 self.fail("cloud_environment {0} could not be resolved: {1}".format(_cloud_environment, str(exc)), exception=traceback.format_exc())
1785
1786 client_id = client_id or self._get_env('client_id')
1787 credential = managed_identity.ManagedIdentityCredential(client_id=client_id, cloud_environment=cloud_environment)
1788 subscription_id = subscription_id or self._get_env('subscription_id')
1789 if not subscription_id:
1790 try:
1791 # use the first subscription of the MSI
1792 subscription_client = SubscriptionClient(credential)
1793 subscription = next(subscription_client.subscriptions.list())
1794 subscription_id = str(subscription.subscription_id)
1795 except Exception as exc:
1796 self.fail("Failed to get MSI token: {0}. "
1797 "Please check whether your machine enabled MSI or grant access to any subscription.".format(str(exc)))
1798 return {
1799 'credentials': credential,
1800 'subscription_id': subscription_id,
1801 'cloud_environment': cloud_environment,
1802 'auth_source': 'msi'
1803 }
1804
1805 def _get_azure_cli_credentials(self, subscription_id=None):
1806 subscription_id = subscription_id or self._get_env('subscription_id')
1807 if not subscription_id:
1808 try:
1809 cmd = ["az", "account", "show", "--query", "id", "-o", "json"]
1810 subscription_id = subprocess.run(cmd, capture_output=True, text=True, check=True).stdout.strip().strip('"') # allow subprocess
1811 except Exception as ec:
1812 raise CLIError("Obtain the az login's subscription occurred exception as {0}".format(ec))
1813
1814 try:
1815 cmd = ["az", "cloud", "show", "--query", "name", "-o", "json"]
1816 cloud_name = subprocess.run(cmd, capture_output=True, text=True, check=True).stdout.strip().strip('"') # allow subprocess
1817 all_clouds = [x[1] for x in inspect.getmembers(azure_cloud) if isinstance(x[1], azure_cloud.Cloud)]
1818 matched_clouds = [x for x in all_clouds if x.name == cloud_name]
1819 except Exception as ec:
1820 raise CLIError("Obtain the az login's active cloud occurred exception as {0}".format(ec))
1821
1822 if len(matched_clouds) != 1:
1823 raise CLIError("Obtain the active cloud failed, There is no or multiple matching clouds")
1824
1825 cli_credentials = {
1826 'credentials': AzureCliCredential(),
1827 'subscription_id': subscription_id,
1828 'cloud_environment': matched_clouds[0],
1829 }
1830 return cli_credentials
1831
1832 def _get_env_credentials(self, subscription_id=None):
1833 env_credentials = dict()
1834 for attribute, env_variable in AZURE_CREDENTIAL_ENV_MAPPING.items():
1835 env_credentials[attribute] = os.environ.get(env_variable, None)
1836
1837 if env_credentials['profile']:
1838 credentials = self._get_profile(env_credentials['profile'], subscription_id=subscription_id)
1839 return credentials
1840
1841 if env_credentials.get('subscription_id') is None and not self.is_ad_resource:
1842 return None
1843
1844 if subscription_id is not None:
1845 env_credentials['subscription_id'] = subscription_id
1846
1847 return env_credentials
1848
1849 def _get_credentials(self, auth_source=None, **params):
1850 # Get authentication credentials.
1851 self.log('Getting credentials')
1852
1853 arg_credentials = dict()
1854 for attribute, env_variable in AZURE_CREDENTIAL_ENV_MAPPING.items():
1855 arg_credentials[attribute] = params.get(attribute, None)
1856
1857 if auth_source == 'msi':
1858 self.log('Retrieving credentials from MSI')
1859 return self._get_msi_credentials(subscription_id=params.get('subscription_id'), client_id=params.get('client_id'),
1860 _cloud_environment=params.get('cloud_environment'))
1861
1862 if auth_source == 'cli':
1863 try:
1864 self.log('Retrieving credentials from Azure CLI profile')
1865 cli_credentials = self._get_azure_cli_credentials(subscription_id=params.get('subscription_id'))
1866 return cli_credentials
1867 except CLIError as err:
1868 self.fail("Azure CLI profile cannot be loaded - {0}".format(err))
1869
1870 if auth_source == 'env':
1871 self.log('Retrieving credentials from environment')
1872 env_credentials = self._get_env_credentials(subscription_id=params.get('subscription_id'))
1873 return env_credentials
1874
1875 if auth_source == 'credential_file':
1876 self.log("Retrieving credentials from credential file")
1877 profile = params.get('profile') or 'default'
1878 default_credentials = self._get_profile(profile, subscription_id=params.get('subscription_id'))
1879 return default_credentials
1880
1881 # auto, precedence: module parameters -> environment variables -> default profile in ~/.azure/credentials -> azure cli
1882 # try module params
1883 if arg_credentials['profile'] is not None:
1884 self.log('Retrieving credentials with profile parameter.')
1885 credentials = self._get_profile(arg_credentials['profile'], subscription_id=params.get('subscription_id'))
1886 return credentials
1887
1888 if arg_credentials['client_id'] or arg_credentials['ad_user']:
1889 self.log('Received credentials from parameters.')
1890 return arg_credentials
1891
1892 # try environment
1893 env_credentials = self._get_env_credentials(subscription_id=params.get('subscription_id'))
1894 if env_credentials:
1895 self.log('Received credentials from env.')
1896 return env_credentials
1897
1898 # try default profile from ~./azure/credentials
1899 default_credentials = self._get_profile(subscription_id=params.get('subscription_id'))
1900 if default_credentials:
1901 self.log('Retrieved default profile credentials from ~/.azure/credentials.')
1902 return default_credentials
1903
1904 try:
1905 self.log('Retrieving credentials from AzureCLI profile')
1906 cli_credentials = self._get_azure_cli_credentials(subscription_id=params.get('subscription_id'))
1907 return cli_credentials
1908 except CLIError as ce:
1909 self.log('Error getting AzureCLI profile credentials - {0}'.format(ce))
1910
1911 return None
1912
1913 def _get_cloud_from_metadata_endpoint(self, metadata_endpoint):
1914 _knownClouds = azure_cloud.KNOWN_CLOUDS
1915 return next(cloud for cloud in _knownClouds if cloud.endpoints.resource_manager.lower().rstrip('/') == metadata_endpoint.lower().rstrip('/'))
1916
1917 def log(self, msg, pretty_print=False):
1918 pass
1919 # Use only during module development
1920 # if self.debug:
1921 # log_file = open('azure_rm.log', 'a')
1922 # if pretty_print:
1923 # log_file.write(json.dumps(msg, indent=4, sort_keys=True))
1924 # else:
1925 # log_file.write(msg + u'\n')