Debian Codegraph @

ansible_collections/azure/azcollection/plugins/inventory/azure_kql.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_kql
9 version_added: "3.7.0"
10 short_description: Azure Resource Manager inventory plugin using Graph QL
11 extends_documentation_fragment:
12 - azure.azcollection.azure
13 - azure.azcollection.azure_kql
14 - constructed
15 - inventory_cache
16 description:
17 - Query VM details from Azure Resource Manager using Graph QL
18 - See https://learn.microsoft.com/en-us/azure/virtual-machines/resource-graph-samples?tabs=azure-cli
19 for how to craft your own query. The one requirement is that you need to provide inventory_hostname.
20 - Requires a YAML configuration file whose name ends with 'azure_kql.(yml|yaml)'
21 - Be aware that currently Azure Resource Graph may not be consistent with the actual state of your
22 resources. It can take up to 30 minutes for updates to propagate. This applies both for resources
23 to appear and to dissapear.
24 '''
25
26 EXAMPLES = '''
27 plugin: azure.azcollection.azure_kql
28
29 graph_query: |-
30 Resources
31 | where type =~ 'microsoft.compute/virtualmachines'
32 | project vmId = tolower(tostring(id)),
33 inventory_hostname = name,
34 tags,
35 location,
36 resourceGroup,
37 osType = tostring(properties.storageProfile.osDisk.osType),
38 powerState = tostring(properties.extended.instanceView.powerState.displayStatus),
39 hostName = properties.osProfile.computerName,
40 subscription_id = subscriptionId
41 | join kind=inner (ResourceContainers
42 | where type=='microsoft.resources/subscriptions'
43 | extend subscription_name = name,
44 subscription_id = subscriptionId,
45 state = properties.state
46 | where state == 'Enabled'
47 | project subscription_name,
48 subscription_id)
49 on subscription_id
50 | project-away subscription_id1
51 | join (Resources
52 | where type =~ 'microsoft.network/networkinterfaces'
53 | mv-expand ipconfig=properties.ipConfigurations
54 | project vmId = tolower(tostring(properties.virtualMachine.id)),
55 privateIp = ipconfig.properties.privateIPAddress,
56 publicIpId = tostring(ipconfig.properties.publicIPAddress.id)
57 | join kind=leftouter (Resources
58 | where type =~ 'microsoft.network/publicipaddresses'
59 | project publicIpId = id, publicIp = properties.ipAddress
60 ) on publicIpId
61 | project-away publicIpId, publicIpId1
62 | summarize privateIps = make_list(privateIp), publicIps = make_list(publicIp) by vmId
63 ) on vmId
64 | project-away vmId1
65 | sort by inventory_hostname asc
66
67 # adds variables to each host found by this inventory plugin, whose values are the result of the associated expression
68 compose:
69 ansible_host: "(publicIps + privateIps) | first"
70 ansible_winrm_kerberos_hostname_override: "inventory_name + '.domain.tld'"
71 ansible_winrm_transport: "'ntlm' if ('AAP_managed' in tags and ('DMZ' in (tags.AAP_Managed|list) or 'Local' in (tags.AAP_Managed|list))) else 'kerberos'"
72
73 groups:
74 AAP_Managed: "'AAP_Managed' in (tags|list)"
75 ubuntu18: "'AAP_Managed' in (tags|list) and 'ubuntu18' in tags.Ansible_OS"
76 ubuntu20: "'AAP_Managed' in (tags|list) and 'ubuntu20' in tags.Ansible_OS"
77 ubuntu22: "'AAP_Managed' in (tags|list) and 'ubuntu22' in tags.Ansible_OS"
78 rhel7: "'AAP_Managed' in (tags|list) and 'rhel7' in tags.Ansible_OS"
79 rhel8: "'AAP_Managed' in (tags|list) and 'rhel8' in tags.Ansible_OS"
80 rhel9: "'AAP_Managed' in (tags|list) and 'rhel9' in tags.Ansible_OS"
81 windows2012: "'AAP_Managed' in (tags|list) and 'windows2012' in tags.Ansible_OS"
82 windows2016: "'AAP_Managed' in (tags|list) and 'windows2016' in tags.Ansible_OS"
83 windows2019: "'AAP_Managed' in (tags|list) and 'windows2019' in tags.Ansible_OS"
84 windows2022: "'AAP_Managed' in (tags|list) and 'windows2022' in tags.Ansible_OS"
85 Asia: "'AAP_managed' in (tags|list) and 'Asia' in tags.AAP_Managed"
86 North_America: "'AAP_managed' in (tags|list) and 'Asia' not in tags.AAP_Managed"
87
88 # change how inventory_hostname is generated. Each item is a jinja2 expression similar to hostvar_expressions.
89 hostnames:
90 - "tags.vm_name if 'vm_name' in tags"
91 - default_inventory_hostname + ".domain.tld" # Transfer to fqdn if you use shortnames for VMs
92 - default # special var that uses the default hashed name
93
94 keyed_groups:
95 - prefix: ""
96 separator: ""
97 key: osType
98 - prefix: ""
99 separator: ""
100 key: location
101 - prefix: ""
102 separator: ""
103 key: powerState
104 '''
105
106 import re
107 from ansible.plugins.inventory import BaseInventoryPlugin, Constructable, Cacheable
108 from ansible.errors import AnsibleError
109 from ansible.module_utils.parsing.convert_bool import boolean
110 from ansible.module_utils._text import to_native, to_text
111 from ansible_collections.azure.azcollection.plugins.module_utils.azure_rm_common import AzureRMAuth
112 from os import environ
113
114 try:
115 import pandas as pd
116 import azure.mgmt.resourcegraph as arg
117 except ImportError:
118 pd = object
119 arg = object
120 pass
121
122
123 class InventoryModule(BaseInventoryPlugin, Constructable, Cacheable):
124
125 NAME = 'azure.azcollection.azure_kql'
126
127 def __init__(self):
128 super(InventoryModule, self).__init__()
129
130 self.azure_auth = None
131
132 def verify_file(self, path):
133 """ Verify inventory file """
134 if super(InventoryModule, self).verify_file(path):
135 if re.match(r'.{0,}azure_kql\.y(a)?ml$', path):
136 return True
137 raise AnsibleError("azure_kql inventory filename must end with 'azure_kql.yml' or 'azure_kql.yaml'")
138
139 def parse(self, inventory, loader, path, cache=True):
140 """ parses the inventory file """
141
142 super(InventoryModule, self).parse(inventory, loader, path)
143
144 self._read_config_data(path)
145
146 # Load results from Cache if requested
147 cache_key = self.get_cache_key(path)
148
149 # cache may be True or False at this point to indicate if the inventory is being refreshed
150 # get the user's cache option too to see if we should save the cache if it is changing
151 user_cache_setting = self.get_option('cache')
152
153 # read if the user has caching enabled and the cache isn't being refreshed
154 attempt_to_read_cache = user_cache_setting and cache
155 # update if the user has caching enabled and the cache is being refreshed;
156 # update this value to True if the cache has expired below
157 cache_needs_update = user_cache_setting and not cache
158
159 # attempt to read the cache if inventory isn't being refreshed and the user has caching enabled
160 if attempt_to_read_cache:
161 try:
162 results = self._cache[cache_key]
163 except KeyError:
164 # This occurs if the cache_key is not in the cache or if the cache_key
165 # expired, so the cache needs to be updated
166 cache_needs_update = True
167 if not attempt_to_read_cache or cache_needs_update:
168 # parse the provided inventory source
169 try:
170 self._credential_setup()
171 results = self._get_hosts()
172 except Exception:
173 raise
174 if cache_needs_update:
175 self._cache[cache_key] = results
176
177 self._populate(results)
178
179 def _populate(self, results):
180 """ Populate inventory """
181 constructable_config_strict = boolean(self.get_option('fail_on_template_errors'))
182 constructable_config_compose = self.get_option('compose')
183 constructable_config_groups = self.get_option('groups')
184 constructable_config_keyed_groups = self.get_option('keyed_groups')
185 constructable_hostnames = self.get_option('hostnames')
186
187 for h in results:
188 hostvars = h.get("hostvars")
189 inventory_hostname = self._get_hostname(h,
190 hostnames=constructable_hostnames,
191 strict=constructable_config_strict)
192 self.inventory.add_host(inventory_hostname)
193
194 for k, v in hostvars.items():
195 self.inventory.set_variable(inventory_hostname, k, v)
196
197 # constructable delegation
198 self._set_composite_vars(constructable_config_compose,
199 hostvars,
200 inventory_hostname,
201 strict=constructable_config_strict)
202 self._add_host_to_composed_groups(constructable_config_groups,
203 hostvars,
204 inventory_hostname,
205 strict=constructable_config_strict)
206 self._add_host_to_keyed_groups(constructable_config_keyed_groups,
207 hostvars,
208 inventory_hostname,
209 strict=constructable_config_strict)
210
211 def _get_hostname(self, host, hostnames=None, strict=False):
212 hostname = None
213 errors = []
214
215 for preference in hostnames:
216 if preference == 'default':
217 return host.get("default_inventory_hostname")
218 try:
219 hostname = self._compose(preference, host.get("hostvars"))
220 except Exception as e: # pylint: disable=broad-except
221 if strict:
222 raise AnsibleError("Could not compose %s as hostnames - %s" % (preference, to_native(e)))
223 else:
224 errors.append(
225 (preference, str(e))
226 )
227 if hostname:
228 return to_text(hostname)
229
230 raise AnsibleError(
231 'Could not template any hostname for host, errors for each preference: %s' % (
232 ', '.join(['%s: %s' % (pref, err) for pref, err in errors])
233 )
234 )
235
236 def _credential_setup(self):
237 auth_source = environ.get('ANSIBLE_AZURE_AUTH_SOURCE', None) or self.get_option('auth_source')
238 auth_options = dict(
239 auth_source=auth_source,
240 profile=self.get_option('profile'),
241 subscription_id=self.get_option('subscription_id'),
242 client_id=self.get_option('client_id'),
243 secret=self.get_option('secret'),
244 tenant=self.get_option('tenant'),
245 ad_user=self.get_option('ad_user'),
246 password=self.get_option('password'),
247 cloud_environment=self.get_option('cloud_environment'),
248 cert_validation_mode=self.get_option('cert_validation_mode'),
249 api_profile=self.get_option('api_profile'),
250 track1_cred=True,
251 adfs_authority_url=self.get_option('adfs_authority_url')
252 )
253
254 if self.templar.is_template(auth_options["tenant"]):
255 auth_options["tenant"] = self.templar.template(variable=auth_options["tenant"], disable_lookups=False)
256
257 if self.templar.is_template(auth_options["client_id"]):
258 auth_options["client_id"] = self.templar.template(variable=auth_options["client_id"], disable_lookups=False)
259
260 if self.templar.is_template(auth_options["secret"]):
261 auth_options["secret"] = self.templar.template(variable=auth_options["secret"], disable_lookups=False)
262
263 if self.templar.is_template(auth_options["subscription_id"]):
264 auth_options["subscription_id"] = self.templar.template(variable=auth_options["subscription_id"], disable_lookups=False)
265
266 self.azure_auth = AzureRMAuth(**auth_options)
267
268 def execute_kql(self, query, resource_name='VMs'):
269 """ Execute KQL query """
270
271 argClient = arg.ResourceGraphClient(self.azure_auth.azure_credential_track2)
272 skpToken = 'hasData'
273 output = []
274
275 while skpToken is not None:
276 if skpToken == 'hasData':
277 argQueryOptions = arg.models.QueryRequestOptions(result_format="objectArray")
278 else:
279 argQueryOptions = arg.models.QueryRequestOptions(result_format="objectArray", skip_token=skpToken)
280 argQuery = arg.models.QueryRequest(query=query, options=argQueryOptions)
281 argResults = argClient.resources(argQuery)
282 output.extend(argResults.data)
283 skpToken = argResults.skip_token
284
285 df_output = pd.DataFrame(output)
286 return df_output
287
288 def _get_hosts(self):
289 """ Get all hosts via graph_query """
290
291 df_vms = self.execute_kql(query=self.get_option('graph_query'))
292 results = []
293
294 for index, row in df_vms.iterrows():
295 # Convert panda object to dict
296 row = row.to_dict()
297 # If no tags are present use an empty dict
298 tags = row.pop('tags') or {}
299 # Update row with updated tags
300 row.update({'tags': tags})
301 results.append(dict(default_inventory_hostname=row.get('inventory_hostname'),
302 hostvars=row))
303
304 return results