Debian Codegraph @

ansible_collections/azure/azcollection/plugins/inventory/azure_rm.py

raw symbols SCIP
1 # Copyright (c) 2018 Ansible Project
2 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
3
4 from __future__ import (absolute_import, division, print_function)
5 __metaclass__ = type
6
7 DOCUMENTATION = r'''
8 name: azure_rm
9 short_description: Azure Resource Manager inventory plugin
10 options:
11 batch_fetch_interval:
12 description: Interval with which to check if the batched requests are completed
13 default: 3
14 type: int
15 batch_fetch_timeout:
16 description: The timeout to use when polling for batched requests
17 default: 5
18 type: int
19 extends_documentation_fragment:
20 - azure.azcollection.azure
21 - azure.azcollection.azure_rm
22 - constructed
23 - inventory_cache
24 description:
25 - Query VM details from Azure Resource Manager
26 - Requires a YAML configuration file whose name ends with 'azure_rm.(yml|yaml)'
27 - By default, sets C(ansible_host) to the first public IP address found (preferring the primary NIC). If no
28 public IPs are found, the first private IP (also preferring the primary NIC). The default may be overridden
29 via C(hostvar_expressions); see examples.
30 '''
31
32 EXAMPLES = '''
33 # The following host variables are always available:
34 # public_ipv4_addresses: all public IP addresses, with the primary IP config from the primary NIC first
35 # public_dns_hostnames: all public DNS hostnames, with the primary IP config from the primary NIC first
36 # private_ipv4_addresses: all private IP addressses, with the primary IP config from the primary NIC first
37 # id: the VM's Azure resource ID, eg /subscriptions/00000000-0000-0000-1111-1111aaaabb/resourceGroups/my_rg/providers/Microsoft.Compute/virtualMachines/my_vm
38 # location: the VM's Azure location, eg 'westus', 'eastus'
39 # name: the VM's resource name, eg 'myvm'
40 # os_profile: The VM OS properties, a dictionary, only system is currently available, eg 'os_profile.system not in ['linux']'
41 # powerstate: the VM's current power state, eg: 'running', 'stopped', 'deallocated'
42 # provisioning_state: the VM's current provisioning state, eg: 'succeeded'
43 # tags: dictionary of the VM's defined tag values
44 # resource_type: the VM's resource type, eg: 'Microsoft.Compute/virtualMachines', 'Microsoft.Compute/virtualMachineScaleSets/virtualMachines',
45 # 'microsoft.azurestackhci/virtualmachineinstances'
46 # vmid: the VM's internal SMBIOS ID, eg: '36bca69d-c365-4584-8c06-a62f4a1dc5d2'
47 # vmss: if the VM is a member of a scaleset (vmss), a dictionary including the id and name of the parent scaleset
48 # availability_zone: availability zone in which VM is deployed, eg '1','2','3'
49 # creation_time: datetime object of when the VM was created, eg '2023-07-21T09:30:30.4710164+00:00'
50 #
51 # The following host variables are sometimes available:
52 # computer_name: the Operating System's hostname. Will be available if azure agent is available and picking it up.
53 # The following host variables are available for Azure Stack HCI vms:
54 # customLocation: the azure arc custom location.
55 # virtual_machine_memoryMB: RAM allowed (static)
56 # virtual_machine_processors: number of vCPUs
57
58
59 # sample 'myazuresub.azure_rm.yaml'
60
61 # required for all azure_rm inventory plugin configs
62 plugin: azure.azcollection.azure_rm
63
64 # forces this plugin to use a CLI auth session instead of the automatic auth source selection (eg, prevents the
65 # presence of 'ANSIBLE_AZURE_RM_X' environment variables from overriding CLI auth)
66 auth_source: cli
67
68 # fetches VMs from an explicit list of resource groups instead of default all (- '*')
69 include_vm_resource_groups:
70 - myrg1
71 - myrg2
72
73 # fetches VMs from VMSSs in all resource groups (defaults to no VMSS fetch)
74 include_vmss_resource_groups:
75 - '*'
76
77 # fetches VMs from Azure StackHCI in specific resource groups (defaults to no HCI vm fetch)
78 include_hcivm_resource_groups:
79 - myrg1
80
81 # fetches ARC hosts in specific resource groups (defaults to no ARC fetch)
82 include_arc_resource_groups:
83 - myrg1
84
85 # places a host in the named group if the associated condition evaluates to true
86 conditional_groups:
87 # since this will be true for every host, every host sourced from this inventory plugin config will be in the
88 # group 'all_the_hosts'
89 all_the_hosts: true
90 # if the VM's "name" variable contains "dbserver", it will be placed in the 'db_hosts' group
91 db_hosts: "'dbserver' in name"
92
93 # adds variables to each host found by this inventory plugin, whose values are the result of the associated expression
94 hostvar_expressions:
95 my_host_var:
96 # A statically-valued expression has to be both single and double-quoted, or use escaped quotes, since the outer
97 # layer of quotes will be consumed by YAML. Without the second set of quotes, it interprets 'staticvalue' as a
98 # variable instead of a string literal.
99 some_statically_valued_var: "'staticvalue'"
100 # overrides the default ansible_host value with a custom Jinja2 expression, in this case, the first DNS hostname, or
101 # if none are found, the first public IP address.
102 ansible_host: (public_dns_hostnames + public_ipv4_addresses) | first
103
104 # change how inventory_hostname is generated. Each item is a jinja2 expression similar to hostvar_expressions.
105 hostnames:
106 - tags.vm_name
107 - default_inventory_hostname + ".domain.tld" # Transfer to fqdn if you use shortnames for VMs
108 - default # special var that uses the default hashed name
109
110 # places hosts in dynamically-created groups based on a variable value.
111 keyed_groups:
112 # places each host in a group named 'tag_(tag name)_(tag value)' for each tag on a VM.
113 - prefix: tag
114 key: tags
115 # places each host in a group named 'azure_loc_(location name)', depending on the VM's location
116 - prefix: azure_loc
117 key: location
118 # places host in a group named 'some_tag_X' using the value of the 'sometag' tag on a VM as X, and defaulting to the
119 # value 'none' (eg, the group 'some_tag_none') if the 'sometag' tag is not defined for a VM.
120 - prefix: some_tag
121 key: tags.sometag | default('none')
122
123 # excludes a host from the inventory when any of these expressions is true, can refer to any vars defined on the host
124 exclude_host_filters:
125 # excludes hosts in the eastus region
126 - location in ['eastus']
127 - tags['tagkey'] is defined and tags['tagkey'] == 'tagvalue'
128 - tags['tagkey2'] is defined and tags['tagkey2'] == 'tagvalue2'
129 # excludes hosts that are powered off
130 - powerstate != 'running'
131
132 # includes a host to the inventory when any of these expressions is true, can refer to any vars defined on the host
133 include_host_filters:
134 # includes hosts that in the eastus region and power on
135 - location in ['eastus'] and powerstate == 'running'
136 # includes hosts in the eastus region and power on OR includes hosts in the eastus2 region and tagkey value is tagvalue
137 - location in ['eastus'] and powerstate == 'running'
138 - location in ['eastus2'] and tags['tagkey'] is defined and tags['tagkey'] == 'tagvalue'
139 '''
140
141 # FUTURE: do we need a set of sane default filters, separate from the user-defineable ones?
142 # eg, powerstate==running, provisioning_state==succeeded
143
144
145 import hashlib
146 import json
147 import re
148 import uuid
149 import os
150 import time
151
152 try:
153 from queue import Queue, Empty
154 except ImportError:
155 from Queue import Queue, Empty
156
157 from collections import namedtuple
158 from ansible.plugins.inventory import BaseInventoryPlugin, Constructable, Cacheable
159 from ansible_collections.azure.azcollection.plugins.module_utils.azure_rm_common import AzureRMAuth
160 from ansible.errors import AnsibleParserError, AnsibleError
161 from ansible.module_utils.parsing.convert_bool import boolean
162 from ansible.module_utils._text import to_native, to_bytes, to_text
163 from ansible.utils.display import Display
164 from itertools import chain
165 from os import environ
166 try:
167 from ansible.template import trust_as_template
168 except ImportError:
169 trust_as_template = None
170
171 try:
172 from azure.core._pipeline_client import PipelineClient
173 from azure.core.pipeline.policies import BearerTokenCredentialPolicy
174 from azure.core.configuration import Configuration
175 from azure.mgmt.core.tools import parse_resource_id
176 from azure.core.pipeline import PipelineResponse
177 from azure.mgmt.core.polling.arm_polling import ARMPolling
178 from azure.core.polling import LROPoller
179 from netaddr import IPAddress
180 from azure.core.exceptions import ResourceNotFoundError
181 except ImportError:
182 Configuration = object
183 parse_resource_id = object
184 PipelineClient = object
185 BearerTokenCredentialPolicy = object
186 pass
187
188
189 display = Display()
190
191
192 class AzureRMRestConfiguration(Configuration):
193 def __init__(self, credentials, subscription_id, base_url=None):
194
195 if credentials is None:
196 raise ValueError("Parameter 'credentials' must not be None.")
197 if subscription_id is None:
198 raise ValueError("Parameter 'subscription_id' must not be None.")
199 if not base_url:
200 base_url = 'https://management.azure.com'
201
202 credential_scopes = [f"{base_url}/.default"]
203
204 super(AzureRMRestConfiguration, self).__init__()
205
206 self.authentication_policy = BearerTokenCredentialPolicy(credentials, *credential_scopes)
207 self.credentials = credentials
208 self.subscription_id = subscription_id
209
210
211 UrlAction = namedtuple('UrlAction', ['url', 'api_version', 'handler', 'handler_args'])
212
213
214 class InventoryModule(BaseInventoryPlugin, Constructable, Cacheable):
215
216 NAME = 'azure.azcollection.azure_rm'
217
218 def __init__(self):
219 super(InventoryModule, self).__init__()
220
221 self._hosts = []
222 self._filters = None
223
224 # FUTURE: use API profiles with defaults
225 self._compute_api_version = '2024-07-01'
226 self._network_api_version = '2024-05-01'
227 self._scaleSet_network_api_version = '2025-04-01'
228 self._hybridcompute_api_version = '2024-05-20-preview'
229 self._stackhci_api_version = '2024-01-01'
230
231 self._default_header_parameters = {'Content-Type': 'application/json; charset=utf-8'}
232
233 self._request_queue = Queue()
234
235 self.azure_auth = None
236
237 self._batch_fetch = False
238
239 def verify_file(self, path):
240 '''
241 :param loader: an ansible.parsing.dataloader.DataLoader object
242 :param path: the path to the inventory config file
243 :return the contents of the config file
244 '''
245 if super(InventoryModule, self).verify_file(path):
246 if re.match(r'.{0,}azure_rm\.y(a)?ml$', path):
247 display.vvv("Matching extension for azure_rm.py inventory plugin")
248 return True
249 # display.debug("azure_rm inventory filename must end with 'azure_rm.yml' or 'azure_rm.yaml'")
250 raise AnsibleError("azure_rm inventory filename must end with 'azure_rm.yml' or 'azure_rm.yaml'")
251
252 def parse(self, inventory, loader, path, cache=True):
253 super(InventoryModule, self).parse(inventory, loader, path)
254
255 self._read_config_data(path)
256
257 if self.get_option('use_contrib_script_compatible_sanitization'):
258 self._sanitize_group_name = self._legacy_script_compatible_group_sanitization
259
260 self._batch_fetch = self.get_option('batch_fetch')
261 self._batch_fetch_interval = self.get_option('batch_fetch_interval')
262 self._batch_fetch_timeout = self.get_option('batch_fetch_timeout')
263
264 self._legacy_hostnames = self.get_option('plain_host_names')
265
266 self._filters = self.get_option('exclude_host_filters') + self.get_option('default_host_filters')
267
268 self._include_filters = self.get_option('include_host_filters')
269
270 # Load results from Cache if requested
271 cache_key = self.get_cache_key(path)
272
273 # cache may be True or False at this point to indicate if the inventory is being refreshed
274 # get the user's cache option too to see if we should save the cache if it is changing
275 user_cache_setting = self.get_option('cache')
276
277 # read if the user has caching enabled and the cache isn't being refreshed
278 attempt_to_read_cache = user_cache_setting and cache
279 # update if the user has caching enabled and the cache is being refreshed;
280 # update this value to True if the cache has expired below
281 cache_needs_update = user_cache_setting and not cache
282
283 # attempt to read the cache if inventory isn't being refreshed and the user has caching enabled
284 if attempt_to_read_cache:
285 try:
286 results = self._cache[cache_key]
287 except KeyError:
288 # This occurs if the cache_key is not in the cache or if the cache_key
289 # expired, so the cache needs to be updated
290 cache_needs_update = True
291 if not attempt_to_read_cache or cache_needs_update:
292 # parse the provided inventory source
293 try:
294 self._credential_setup()
295 self._get_hosts()
296 results = self._serialize(self._hosts)
297 except Exception:
298 raise
299 if cache_needs_update:
300 self._cache[cache_key] = results
301
302 self._populate(results)
303
304 def _serialize(self, hosts):
305 results = []
306 for h in hosts:
307 try:
308 host_data = dict(default_inventory_hostname=h.default_inventory_hostname,
309 hostvars=h.hostvars)
310 except ResourceNotFoundError as e:
311 continue
312 results.append(host_data)
313 return results
314
315 def _credential_setup(self):
316 auth_source = environ.get('ANSIBLE_AZURE_AUTH_SOURCE', None) or self.get_option('auth_source')
317 auth_options = dict(
318 auth_source=auth_source,
319 profile=self.get_option('profile'),
320 subscription_id=self.get_option('subscription_id'),
321 client_id=self.get_option('client_id'),
322 secret=self.get_option('secret'),
323 tenant=self.get_option('tenant'),
324 ad_user=self.get_option('ad_user'),
325 password=self.get_option('password'),
326 cloud_environment=self.get_option('cloud_environment'),
327 cert_validation_mode=self.get_option('cert_validation_mode'),
328 api_profile=self.get_option('api_profile'),
329 track1_cred=True,
330 adfs_authority_url=self.get_option('adfs_authority_url')
331 )
332
333 if self.templar.is_template(auth_options["tenant"]):
334 auth_options["tenant"] = self.templar.template(variable=auth_options["tenant"], disable_lookups=False)
335
336 if self.templar.is_template(auth_options["client_id"]):
337 auth_options["client_id"] = self.templar.template(variable=auth_options["client_id"], disable_lookups=False)
338
339 if self.templar.is_template(auth_options["secret"]):
340 auth_options["secret"] = self.templar.template(variable=auth_options["secret"], disable_lookups=False)
341
342 if self.templar.is_template(auth_options["subscription_id"]):
343 auth_options["subscription_id"] = self.templar.template(variable=auth_options["subscription_id"], disable_lookups=False)
344
345 self.azure_auth = AzureRMAuth(**auth_options)
346
347 self._clientconfig = AzureRMRestConfiguration(self.azure_auth.azure_credential_track2, self.azure_auth.subscription_id,
348 self.azure_auth._cloud_environment.endpoints.resource_manager)
349
350 self.new_client = PipelineClient(self.azure_auth._cloud_environment.endpoints.resource_manager, config=self._clientconfig)
351
352 def _enqueue_get(self, url, api_version, handler, handler_args=None):
353 if not handler_args:
354 handler_args = {}
355 self._request_queue.put_nowait(UrlAction(url=url, api_version=api_version, handler=handler, handler_args=handler_args))
356
357 def _enqueue_vm_list(self, rg='*'):
358 if not rg or rg == '*':
359 url = '/subscriptions/{subscriptionId}/providers/Microsoft.Compute/virtualMachines'
360 else:
361 url = '/subscriptions/{subscriptionId}/resourceGroups/{rg}/providers/Microsoft.Compute/virtualMachines'
362
363 url = url.format(subscriptionId=self._clientconfig.subscription_id, rg=rg)
364 self._enqueue_get(url=url, api_version=self._compute_api_version, handler=self._on_vm_page_response)
365
366 def _enqueue_arc_list(self, rg='*'):
367 if not rg or rg == '*':
368 url = '/subscriptions/{subscriptionId}/providers/Microsoft.HybridCompute/machines'
369 else:
370 url = '/subscriptions/{subscriptionId}/resourceGroups/{rg}/providers/Microsoft.HybridCompute/machines'
371
372 url = url.format(subscriptionId=self._clientconfig.subscription_id, rg=rg)
373 self._enqueue_get(url=url, api_version=self._hybridcompute_api_version, handler=self._on_arc_page_response)
374
375 def _enqueue_archcivm_list(self, rg='*'):
376 if not rg or rg == '*':
377 url = '/subscriptions/{subscriptionId}/providers/Microsoft.HybridCompute/machines'
378 else:
379 url = '/subscriptions/{subscriptionId}/resourceGroups/{rg}/providers/Microsoft.HybridCompute/machines'
380
381 url = url.format(subscriptionId=self._clientconfig.subscription_id, rg=rg)
382 self._enqueue_get(url=url, api_version=self._hybridcompute_api_version, handler=self._on_archcivm_page_response)
383
384 def _enqueue_vmss_list(self, rg=None):
385 if not rg or rg == '*':
386 url = '/subscriptions/{subscriptionId}/providers/Microsoft.Compute/virtualMachineScaleSets'
387 else:
388 url = '/subscriptions/{subscriptionId}/resourceGroups/{rg}/providers/Microsoft.Compute/virtualMachineScaleSets'
389
390 url = url.format(subscriptionId=self._clientconfig.subscription_id, rg=rg)
391 self._enqueue_get(url=url, api_version=self._compute_api_version, handler=self._on_vmss_page_response)
392
393 def _get_hosts(self):
394 if os.environ.get('ANSIBLE_AZURE_VM_RESOURCE_GROUPS'):
395 for vm_rg in os.environ['ANSIBLE_AZURE_VM_RESOURCE_GROUPS'].split(","):
396 self._enqueue_vm_list(vm_rg)
397 else:
398 for vm_rg in self.get_option('include_vm_resource_groups'):
399 self._enqueue_vm_list(vm_rg)
400
401 for arc_rg in self.get_option('include_arc_resource_groups'):
402 self._enqueue_arc_list(arc_rg)
403
404 for vm_rg in self.get_option('include_hcivm_resource_groups'):
405 self._enqueue_archcivm_list(vm_rg)
406
407 if os.environ.get('ANSIBLE_AZURE_VMSS_RESOURCE_GROUPS'):
408 for vmss_rg in os.environ['ANSIBLE_AZURE_VMSS_RESOURCE_GROUPS'].split(","):
409 self._enqueue_vmss_list(vmss_rg)
410 else:
411 for vmss_rg in self.get_option('include_vmss_resource_groups'):
412 self._enqueue_vmss_list(vmss_rg)
413
414 if self._batch_fetch:
415 self._process_queue_batch()
416 else:
417 self._process_queue_serial()
418
419 def _populate(self, results):
420 constructable_config_strict = boolean(self.get_option('fail_on_template_errors'))
421 if self.get_option('hostvar_expressions') is not None:
422 constructable_config_compose = self.get_option('hostvar_expressions')
423 else:
424 constructable_config_compose = self.get_option('compose')
425 constructable_config_groups = self.get_option('conditional_groups')
426 constructable_config_keyed_groups = self.get_option('keyed_groups')
427
428 constructable_hostnames = self.get_option('hostnames')
429
430 for h in results:
431 hostvars = h.get("hostvars")
432 # FUTURE: track hostnames to warn if a hostname is repeated (can happen for legacy and for composed inventory_hostname)
433 inventory_hostname = self._get_hostname(h, hostnames=constructable_hostnames, strict=constructable_config_strict)
434 display.vvvv(f"Populate {inventory_hostname}")
435
436 if self._filter_exclude_host(inventory_hostname, hostvars):
437 continue
438 if not self._filter_include_host(inventory_hostname, hostvars):
439 continue
440
441 try:
442 self.inventory.add_host(inventory_hostname)
443 # FUTURE: configurable default IP list? can already do this via hostvar_expressions
444
445 self.inventory.set_variable(inventory_hostname, "ansible_host",
446 next(chain(hostvars['public_ipv4_address'], hostvars['private_ipv4_addresses']), None))
447 for k, v in hostvars.items():
448 # FUTURE: configurable hostvar prefix? Makes docs harder...
449 self.inventory.set_variable(inventory_hostname, k, v)
450
451 # constructable delegation
452 self._set_composite_vars(constructable_config_compose, hostvars, inventory_hostname, strict=constructable_config_strict)
453 self._add_host_to_composed_groups(constructable_config_groups, hostvars, inventory_hostname, strict=constructable_config_strict)
454 self._add_host_to_keyed_groups(constructable_config_keyed_groups, hostvars, inventory_hostname, strict=constructable_config_strict)
455 display.vvvv(f"Done Populate {inventory_hostname}")
456 except Exception as e:
457 display.error(f"Exception in _populate of {inventory_hostname}: {e}")
458
459 # FUTURE: fix underlying inventory stuff to allow us to quickly access known groupvars from reconciled host
460 def _filter_host(self, filter, inventory_hostname, hostvars):
461 self.templar.available_variables = hostvars
462
463 for condition in filter:
464 # FUTURE: should warn/fail if conditional doesn't return True or False
465 conditional = "{{% if {0} %}}true{{% else %}}false{{% endif %}}".format(condition)
466 if trust_as_template:
467 conditional = trust_as_template(conditional)
468 try:
469 if boolean(self.templar.template(conditional)):
470 return True
471 except Exception as e:
472 if boolean(self.get_option('fail_on_template_errors')):
473 raise AnsibleParserError("Error evaluating filter condition '{0}' for host {1}: {2}".format(condition, inventory_hostname, to_native(e)))
474 continue
475
476 return False
477
478 def _filter_include_host(self, inventory_hostname, hostvars):
479 return self._filter_host(self._include_filters, inventory_hostname, hostvars)
480
481 def _filter_exclude_host(self, inventory_hostname, hostvars):
482 return self._filter_host(self._filters, inventory_hostname, hostvars)
483
484 def _get_hostname(self, host, hostnames=None, strict=False):
485 hostname = None
486 errors = []
487
488 for preference in hostnames:
489 if preference == 'default':
490 return host.get("default_inventory_hostname")
491 try:
492 hostname = self._compose(preference, host.get("hostvars"))
493 except Exception as e: # pylint: disable=broad-except
494 if strict:
495 raise AnsibleError("Could not compose %s as hostnames - %s" % (preference, to_native(e)))
496 else:
497 errors.append(
498 (preference, str(e))
499 )
500 if hostname:
501 return to_text(hostname)
502
503 raise AnsibleError(
504 'Could not template any hostname for host, errors for each preference: %s' % (
505 ', '.join(['%s: %s' % (pref, err) for pref, err in errors])
506 )
507 )
508
509 def _process_queue_serial(self):
510 try:
511 while True:
512 item = self._request_queue.get_nowait()
513 display.vvvv(item.url)
514 resp = self.send_request(item.url, item.api_version)
515 if resp.status_code == 200:
516 item.handler(json.loads(resp.body()), **item.handler_args)
517 else:
518 display.error(item.url)
519 display.error(resp.text())
520 except Empty:
521 pass
522
523 def _on_vm_page_response(self, response, vmss=None, archcivm=None):
524 next_link = response.get('nextLink')
525
526 if next_link:
527 self._enqueue_get(url=next_link, api_version=self._compute_api_version, handler=self._on_vm_page_response,
528 handler_args=dict(vmss=vmss, archcivm=archcivm))
529
530 if 'value' in response:
531 for h in response['value']:
532 display.debug("AzureHost raw response:")
533 display.debug(h)
534 # FUTURE: add direct VM filtering by tag here (performance optimization)?
535 self._hosts.append(AzureHost(h, self, vmss=vmss, archcivm=archcivm, legacy_name=self._legacy_hostnames))
536
537 def _on_arc_page_response(self, response):
538 next_link = response.get('nextLink')
539
540 if next_link:
541 self._enqueue_get(url=next_link, api_version=self._hybridcompute_api_version, handler=self._on_arc_page_response)
542
543 for arcvm in response['value']:
544 display.debug("ArcHost raw response:")
545 display.debug(arcvm)
546 self._hosts.append(ArcHost(arcvm, self, legacy_name=self._legacy_hostnames))
547
548 def _on_archcivm_page_response(self, response):
549 next_link = response.get('nextLink')
550
551 if next_link:
552 self._enqueue_get(url=next_link, api_version=self._hybridcompute_api_version, handler=self._on_archcivm_page_response)
553
554 for archcivm in response['value']:
555 if archcivm.get('kind') == 'HCI':
556 url = '{0}/providers/Microsoft.AzureStackHCI/virtualMachineInstances'.format(archcivm['id'])
557 # Stack HCI instances look close enough to regular VMs that we can share the handler impl...
558 self._enqueue_get(url=url, api_version=self._stackhci_api_version, handler=self._on_vm_page_response, handler_args=dict(archcivm=archcivm))
559
560 def _on_vmss_page_response(self, response):
561 next_link = response.get('nextLink')
562
563 if next_link:
564 self._enqueue_get(url=next_link, api_version=self._compute_api_version, handler=self._on_vmss_page_response)
565
566 # FUTURE: add direct VMSS filtering by tag here (performance optimization)?
567 for vmss in response['value']:
568 url = '{0}/virtualMachines'.format(vmss['id'])
569
570 # Since Flexible instance is a standalone VM we are processing them as regular VM.
571 if vmss['properties']['orchestrationMode'] != 'Flexible':
572 # VMSS instances look close enough to regular VMs that we can share the handler impl...
573 self._enqueue_get(url=url, api_version=self._compute_api_version, handler=self._on_vm_page_response, handler_args=dict(vmss=vmss))
574
575 # use the undocumented /batch endpoint to bulk-send up to 500 requests in a single round-trip
576 #
577 def _process_queue_batch(self):
578 while True:
579 batch_requests = []
580 batch_item_index = 0
581 batch_response_handlers = dict()
582 try:
583 while batch_item_index < 100:
584 item = self._request_queue.get_nowait()
585
586 name = str(uuid.uuid4())
587 query_parameters = {'api-version': item.api_version}
588 header_parameters = {'x-ms-client-request-id': str(uuid.uuid4()), 'Content-Type': 'application/json; charset=utf-8'}
589 body = {}
590 req = self.new_client.get(item.url, query_parameters, header_parameters, body)
591 batch_requests.append(dict(httpMethod="GET", url=req.url, name=name))
592 batch_response_handlers[name] = item
593 batch_item_index += 1
594 except Empty:
595 pass
596
597 if not batch_requests:
598 break
599
600 self.retry_batch(batch_requests, batch_response_handlers)
601
602 def retry_batch(self, batch_requests, batch_response_handlers, backoff_factor=0.8, retry_limit=10):
603 retry_count = 1
604 _SAFE_CODES = set(range(506)) - set([408, 429, 500, 502, 503, 504])
605 _RETRY_CODES = set(range(999)) - _SAFE_CODES
606 while True:
607 batch_resp = self._send_batch(batch_requests)
608 key_name = None
609 if 'responses' in batch_resp:
610 key_name = 'responses'
611 elif 'value' in batch_resp:
612 key_name = 'value'
613 else:
614 raise AnsibleError("didn't find expected key responses/value in batch response")
615 batch_processed = []
616 batch_retry = False
617 for idx, r in enumerate(batch_resp[key_name]):
618 status_code = r.get('httpStatusCode')
619 returned_name = r['name']
620 result = batch_response_handlers[returned_name]
621 if status_code == 200:
622 # FUTURE: error-tolerant operation mode (eg, permissions)
623 # FUTURE: store/handle errors from individual handlers
624 result.handler(r['content'], **result.handler_args)
625 batch_processed.append(returned_name)
626 elif status_code in _RETRY_CODES:
627 # 429: Too many requests Error, Backoff and Retry
628 batch_retry = True
629 else:
630 corresponding_request = [req for req in batch_requests if req['name'] == r['name']]
631 if len(corresponding_request) > 0:
632 display.error(corresponding_request[0])
633 display.error(r['content'])
634 if batch_retry:
635 time.sleep(backoff_factor * (2 ** (retry_count)))
636 retry_count += 1
637 if len(batch_processed) > 0:
638 # Remove already processed requests
639 for idx, r in enumerate(batch_requests):
640 if r.get('name') in batch_processed:
641 processed = batch_requests.pop(idx)
642 if retry_count > retry_limit:
643 raise AnsibleError("Reached maximum retries in batch request")
644 else:
645 break
646
647 def _send_batch(self, batched_requests):
648 url = '/batch'
649 query_parameters = {'api-version': '2015-11-01'}
650 header_parameters = {'x-ms-client-request-id': str(uuid.uuid4()), 'Content-Type': 'application/json; charset=utf-8'}
651 operation_config = {}
652 body_content = dict(requests=batched_requests)
653
654 header = {'x-ms-client-request-id': str(uuid.uuid4())}
655 header.update(self._default_header_parameters)
656
657 display.vvvv("Batch:")
658 for r in batched_requests:
659 display.vvvv(" " + r['url'])
660 display.vvvv("EndBatch")
661 request_new = self.new_client.post(url, query_parameters, header_parameters, body_content)
662 response = self.new_client.send_request(request_new, **operation_config)
663
664 if response.status_code == 202:
665 def get_long_running_output(response):
666 return response
667 poller = LROPoller(self.new_client,
668 PipelineResponse(None, response, None),
669 get_long_running_output,
670 ARMPolling(self._batch_fetch_interval, **operation_config))
671 response = self.get_poller_result(poller, self._batch_fetch_timeout)
672 if hasattr(response, 'body'):
673 response = json.loads(response.body())
674 elif hasattr(response, 'context'):
675 response = response.context['deserialized_data']
676 else:
677 response = json.loads(response.body())
678
679 return response
680
681 def get_poller_result(self, poller, timeout):
682 try:
683 while not poller.done():
684 poller.wait(timeout=timeout)
685 return poller.result()
686 except Exception as exc:
687 raise
688
689 def send_request(self, url, api_version):
690 query_parameters = {'api-version': api_version}
691 header_parameters = {'x-ms-client-request-id': str(uuid.uuid4()), 'Content-Type': 'application/json; charset=utf-8'}
692 body = {}
693 request_new = self.new_client.get(url, query_parameters, header_parameters)
694 response = self.new_client.send_request(request_new)
695 return response
696
697 @staticmethod
698 def _legacy_script_compatible_group_sanitization(name):
699
700 # note that while this mirrors what the script used to do, it has many issues with unicode and usability in python
701 regex = re.compile(r"[^A-Za-z0-9\_\-]")
702
703 return regex.sub('_', name)
704
705 # VM list (all, N resource groups): VM -> InstanceView, N NICs, N PublicIPAddress)
706 # VMSS VMs (all SS, N specific SS, N resource groups?): SS -> VM -> InstanceView, N NICs, N PublicIPAddress)
707
708
709 class ArcHost(object):
710 def __init__(self, arc_model, inventory_client, legacy_name=False):
711 self._inventory_client = inventory_client
712 self._arc_model = arc_model
713 self._instanceview = self._arc_model
714 self._status = self._arc_model['properties'].get('status', '').lower() # 'Connected'
715 self._powerstate = self._status.replace('connected', 'running')
716
717 self._hostvars = {}
718
719 arc_name = self._arc_model['name']
720
721 if legacy_name:
722 self.default_inventory_hostname = arc_name
723 else:
724 # Azure often doesn't provide a globally-unique filename, so use resource name + a chunk of ID hash
725 self.default_inventory_hostname = '{0}_{1}'.format(arc_name, hashlib.sha1(to_bytes(arc_model['id'])).hexdigest()[0:4])
726
727 @property
728 def hostvars(self):
729 if self._hostvars != {}:
730 return self._hostvars
731
732 properties = self._arc_model.get('properties', {})
733 new_hostvars = dict(
734 network_interface=[],
735 mac_address=[],
736 ansible_all_ipv4_addresses=[],
737 ansible_all_ipv6_addresses=[],
738 public_ipv4_address=[],
739 private_ipv4_addresses=[],
740 public_dns_hostnames=[],
741 ansible_dns=[],
742 id=self._arc_model['id'],
743 location=self._arc_model['location'],
744 name=self._arc_model['name'],
745 default_inventory_hostname=self.default_inventory_hostname,
746 powerstate=self._powerstate,
747 status=self._status,
748 provisioning_state=properties.get('provisioningState', 'unknown').lower(),
749 vmid=self._arc_model['properties']['vmId'],
750 os_profile=dict(
751 sku=properties.get('osSku', 'unknown'),
752 system=properties.get('osType', 'unknown'),
753 version=properties.get('osVersion', 'unknown'),
754 ),
755 tags=self._arc_model.get('tags', {}),
756 resource_type=self._arc_model.get('type', "unknown"),
757 resource_group=parse_resource_id(self._arc_model['id']).get('resource_group').lower(),
758 )
759
760 for nic in properties.get('networkProfile', {}).get('networkInterfaces', []):
761 new_hostvars['mac_address'].append(nic.get('macAddress'))
762 new_hostvars['network_interface'].append(nic.get('name'))
763 for ipaddr in nic.get('ipAddresses', []):
764 ipAddressVersion = ipaddr.get('ipAddressVersion')
765 if ipAddressVersion == 'IPv4':
766 ipv4_address = ipaddr.get('address')
767 new_hostvars['ansible_all_ipv4_addresses'].append(ipv4_address)
768 if IPAddress(ipv4_address).is_global():
769 new_hostvars['public_ipv4_address'].append(ipv4_address)
770 else:
771 new_hostvars['private_ipv4_addresses'].append(ipv4_address)
772 if ipAddressVersion == 'IPv6':
773 new_hostvars['ansible_all_ipv6_addresses'].append(ipaddr.get('address'))
774 self._hostvars = new_hostvars
775 return self._hostvars
776
777
778 class AzureHost(object):
779 _powerstate_regex = re.compile('^PowerState/(?P<powerstate>.+)$')
780
781 def __init__(self, vm_model, inventory_client, vmss=None, archcivm=None, legacy_name=False):
782 self._inventory_client = inventory_client
783 self._vm_model = vm_model
784 self._vmss = vmss
785 self._archcivm = archcivm
786 self._type = vm_model['type'].lower()
787
788 self._instanceview = None
789
790 self._powerstate = "unknown"
791 self.nics = []
792
793 vm_name = self._archcivm['name'] if self._archcivm else self._vm_model['name']
794
795 if legacy_name:
796 self.default_inventory_hostname = vm_name
797 else:
798 # Azure often doesn't provide a globally-unique filename, so use resource name + a chunk of ID hash
799 self.default_inventory_hostname = '{0}_{1}'.format(vm_name, hashlib.sha1(to_bytes(vm_model['id'])).hexdigest()[0:4])
800
801 self._hostvars = {}
802
803 if self._archcivm:
804 self._instanceview = self._vm_model
805 self._powerstate = self._vm_model['properties'].get('status', {}).get('powerState', '').lower() # 'Running'
806 else:
807 inventory_client._enqueue_get(url="{0}/instanceView".format(vm_model['id']),
808 api_version=self._inventory_client._compute_api_version,
809 handler=self._on_instanceview_response)
810
811 nic_refs = vm_model['properties'].get('networkProfile', dict()).get('networkInterfaces', [])
812 for nic in nic_refs:
813 # single-nic instances don't set primary, so figure it out...
814 is_primary = nic.get('properties', {}).get('primary', len(nic_refs) == 1)
815
816 api_version = self._inventory_client._network_api_version
817 if self._archcivm:
818 api_version = self._inventory_client._stackhci_api_version
819 elif self._type == 'microsoft.compute/virtualmachinescalesets/virtualmachines':
820 api_version = self._inventory_client._scaleSet_network_api_version
821
822 inventory_client._enqueue_get(url=nic['id'],
823 api_version=api_version,
824 handler=self._on_nic_response,
825 handler_args=dict(is_primary=is_primary))
826
827 @property
828 def hostvars(self):
829 if self._hostvars != {}:
830 return self._hostvars
831
832 system = "unknown"
833 if self._archcivm and self._archcivm['properties'].get('osType'): # osType unavailable with disabled guest agent
834 system = self._archcivm['properties']['osType']
835 elif 'osProfile' in self._vm_model['properties']:
836 if 'linuxConfiguration' in self._vm_model['properties']['osProfile']:
837 system = 'linux'
838 if 'windowsConfiguration' in self._vm_model['properties']['osProfile']:
839 system = 'windows'
840 else:
841 osType = self._vm_model['properties']['storageProfile']['osDisk']['osType']
842 if osType == 'Linux':
843 system = 'linux'
844 if osType == 'Windows':
845 system = 'windows'
846 av_zone = None
847 if 'zones' in self._vm_model:
848 av_zone = self._vm_model['zones']
849
850 createdAt = self._vm_model.get('systemData', {}).get('createdAt') # hci specific
851
852 if self._instanceview and self._instanceview.get('computerName'):
853 computer_name = self._instanceview['computerName']
854 else:
855 computer_name = self._vm_model['properties'].get('osProfile', {}).get('computerName')
856
857 new_hostvars = dict(
858 network_interface=[],
859 network_interface_properties=[],
860 mac_address=[],
861 network_interface_id=[],
862 security_group_id=[],
863 security_group=[],
864 public_ip_address=[],
865 public_ipv4_address=[],
866 public_dns_hostnames=[],
867 private_ipv4_addresses=[],
868 subnet=[],
869 id=self._vm_model['id'],
870 location=self._archcivm['location'] if self._archcivm else self._vm_model['location'],
871 name=self._archcivm['name'] if self._archcivm else self._vm_model['name'],
872 computer_name=computer_name,
873 availability_zone=av_zone,
874 powerstate=self._powerstate,
875 provisioning_state=self._vm_model['properties']['provisioningState'].lower(),
876 tags=self._archcivm.get('tags', {}) if self._archcivm else self._vm_model.get('tags', {}),
877 resource_type=self._vm_model.get('type', "unknown"),
878 vmid=self._vm_model['properties']['vmId'],
879 os_profile=dict(
880 system=system,
881 ),
882 vmss=dict(
883 id=self._vmss['id'],
884 name=self._vmss['name'],
885 ) if self._vmss else {},
886 virtual_machine_size=self._vm_model['properties']['hardwareProfile']['vmSize'] if self._vm_model['properties'].get('hardwareProfile') else None,
887 plan=self._vm_model['properties']['plan']['name'] if self._vm_model['properties'].get('plan') else None,
888 resource_group=parse_resource_id(self._vm_model['id']).get('resource_group').lower(),
889 default_inventory_hostname=self.default_inventory_hostname,
890 creation_time=createdAt if createdAt else self._vm_model['properties'].get('timeCreated'),
891 license_type=self._vm_model['properties'].get('licenseType', 'Unknown')
892 )
893
894 # Instance view
895 if self._instanceview:
896 if self._instanceview.get('osName'):
897 new_hostvars['os_name'] = self._instanceview['osName']
898 if self._instanceview.get('osVersion'):
899 new_hostvars['os_version'] = self._instanceview['osVersion']
900 if self._instanceview.get('hyperVGeneration'):
901 new_hostvars['hyper_v_generation'] = self._instanceview['hyperVGeneration']
902
903 if self._type == 'microsoft.azurestackhci/virtualmachineinstances':
904 new_hostvars['customLocation'] = self._vm_model.get('extendedLocation', {}).get('name', '').split('/')[-1]
905 new_hostvars['virtual_machine_memoryMB'] = self._vm_model['properties']['hardwareProfile'].get('memoryMB')
906 new_hostvars['virtual_machine_processors'] = self._vm_model['properties']['hardwareProfile'].get('processors')
907
908 if (self._type in [
909 'microsoft.compute/virtualmachines',
910 'microsoft.compute/virtualmachinescalesets/virtualmachines',
911 'microsoft.azurestackhci/virtualmachineinstances']):
912 # set nic-related values from the primary NIC first
913 for nic in sorted(self.nics, key=lambda n: n.is_primary, reverse=True):
914 # and from the primary IP config per NIC first
915 for ipc in sorted(nic._nic_model.get('properties', {}).get('ipConfigurations', []),
916 key=lambda i: i.get('properties', {}).get('primary', False), reverse=True):
917 try:
918 subnet = ipc['properties'].get('subnet')
919 if subnet:
920 new_hostvars['subnet'].append(subnet)
921 private_ip = ipc['properties'].get('privateIPAddress')
922 if private_ip:
923 new_hostvars['private_ipv4_addresses'].append(private_ip)
924 pip_id = ipc['properties'].get('publicIPAddress', {}).get('id')
925 if pip_id and pip_id in nic.public_ips:
926 pip = nic.public_ips[pip_id]
927 new_hostvars['public_ipv4_address'].append(pip._pip_model['properties'].get('ipAddress', None))
928 new_hostvars['public_ip_address'].append({
929 'id': pip_id,
930 'name': pip._pip_model['name'],
931 'ipv4_address': pip._pip_model['properties'].get('ipAddress', None),
932 })
933 pip_fqdn = pip._pip_model['properties'].get('dnsSettings', {}).get('fqdn')
934 if pip_fqdn:
935 new_hostvars['public_dns_hostnames'].append(pip_fqdn)
936 except Exception:
937 continue
938
939 new_hostvars['mac_address'].append(nic._nic_model['properties'].get('macAddress'))
940 new_hostvars['network_interface'].append(nic._nic_model['name'])
941 new_hostvars['network_interface_id'].append(nic._nic_model['id'])
942 new_hostvars['security_group_id'].append(nic._nic_model['properties']['networkSecurityGroup']['id']) \
943 if nic._nic_model['properties'].get('networkSecurityGroup') else None
944 new_hostvars['security_group'].append(parse_resource_id(nic._nic_model['properties']['networkSecurityGroup']['id'])['resource_name']) \
945 if nic._nic_model['properties'].get('networkSecurityGroup') else None
946
947 new_hostvars['network_interface_properties'].append(nic._nic_model)
948
949 # set image and os_disk
950 new_hostvars['image'] = {}
951 new_hostvars['os_disk'] = {}
952 new_hostvars['data_disks'] = []
953 storageProfile = self._vm_model['properties'].get('storageProfile')
954 if storageProfile:
955 imageReference = storageProfile.get('imageReference')
956 if imageReference:
957 if imageReference.get('publisher'):
958 new_hostvars['image'] = dict(
959 sku=imageReference.get('sku'),
960 publisher=imageReference.get('publisher'),
961 version=imageReference.get('version'),
962 offer=imageReference.get('offer')
963 )
964 elif imageReference.get('id'):
965 new_hostvars['image'] = dict(
966 id=imageReference.get('id')
967 )
968
969 osDisk = storageProfile.get('osDisk')
970 new_hostvars['os_disk'] = dict(
971 name=osDisk.get('name'),
972 operating_system_type=osDisk.get('osType').lower() if osDisk.get('osType') else None,
973 id=storageProfile.get('vmConfigStoragePathId') if self._archcivm else osDisk.get('managedDisk', {}).get('id')
974 )
975
976 if self._archcivm:
977 new_hostvars['data_disks'] = [
978 dict(
979 name=dataDisk.get('id').split('/')[-1],
980 id=dataDisk.get('id')
981 ) for dataDisk in storageProfile.get('dataDisks', [])
982 ]
983 else:
984 new_hostvars['data_disks'] = [
985 dict(
986 name=dataDisk.get('name'),
987 lun=dataDisk.get('lun'),
988 id=dataDisk.get('managedDisk', {}).get('id')
989 ) for dataDisk in storageProfile.get('dataDisks', [])
990 ]
991
992 self._hostvars = new_hostvars
993 return self._hostvars
994
995 def _on_instanceview_response(self, vm_instanceview_model):
996 self._instanceview = vm_instanceview_model
997 self._powerstate = next((self._powerstate_regex.match(s.get('code', '')).group('powerstate')
998 for s in vm_instanceview_model.get('statuses', []) if self._powerstate_regex.match(s.get('code', ''))), 'unknown')
999
1000 def _on_nic_response(self, nic_model, is_primary=False):
1001 display.debug("AzureNic raw response:")
1002 display.debug(nic_model)
1003 nic = AzureNic(nic_model=nic_model, inventory_client=self._inventory_client, is_primary=is_primary)
1004 self.nics.append(nic)
1005
1006
1007 class AzureNic(object):
1008 def __init__(self, nic_model, inventory_client, is_primary=False):
1009 self._nic_model = nic_model
1010 self.is_primary = is_primary
1011 self._inventory_client = inventory_client
1012
1013 self.public_ips = {}
1014
1015 if nic_model.get('properties', {}).get('ipConfigurations'):
1016 for ipc in nic_model['properties']['ipConfigurations']:
1017 pip = ipc['properties'].get('publicIPAddress')
1018 if pip:
1019 self._inventory_client._enqueue_get(url=pip['id'], api_version=self._inventory_client._network_api_version, handler=self._on_pip_response)
1020
1021 def _on_pip_response(self, pip_model):
1022 display.debug("AzurePip raw response:")
1023 display.debug(pip_model)
1024 self.public_ips[pip_model['id']] = AzurePip(pip_model)
1025
1026
1027 class AzurePip(object):
1028 def __init__(self, pip_model):
1029 self._pip_model = pip_model