Debian Codegraph @

ansible_collections/azure/azcollection/plugins/modules/azure_rm_arcmachineextensions.py

raw symbols SCIP
1 #!/usr/bin/python
2 #
3 # Copyright (c) 2026 Klaas Weyermann (@Klaas-)
4 #
5 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
6
7 from __future__ import absolute_import, division, print_function
8 __metaclass__ = type
9
10 DOCUMENTATION = '''
11 ---
12 module: azure_rm_arcmachineextensions
13 version_added: "3.17.0"
14 short_description: Create, update and delete arc machine extensions.
15 description:
16 - Create, update and delete arc machine extensions.
17 - >-
18 U(https://learn.microsoft.com/en-us/python/api/azure-mgmt-hybridcompute/azure.mgmt.hybridcompute.operations.machineextensionsoperations?view=azure-python#azure-mgmt-hybridcompute-operations-machineextensionsoperations-begin-create-or-update)
19 options:
20 name:
21 description:
22 - The name of the arc machine extension you're creating, updateing or deleting.
23 required: true
24 type: str
25 machine_name:
26 description:
27 - The name of the arc machine.
28 required: true
29 type: str
30 resource_group:
31 description:
32 - The name of the resource group.
33 required: true
34 type: str
35 location:
36 description:
37 - Location of the arc machine extension.
38 required: false
39 type: str
40 properties:
41 description:
42 - Describes Machine Extension Properties.
43 - Required for creation.
44 - >-
45 U(https://learn.microsoft.com/en-us/python/api/azure-mgmt-hybridcompute/azure.mgmt.hybridcompute.models.machineextensionproperties?view=azure-python)
46 type: dict
47 suboptions:
48 force_update_tag:
49 description:
50 - How the extension handler should be forced to update even if the extension configuration has not changed.
51 type: str
52 publisher:
53 description:
54 - The name of the extension handler publisher.
55 type: str
56 type:
57 description:
58 - Specifies the type of the extension.
59 type: str
60 type_handler_version:
61 description:
62 - Specifies the version of the script handler.
63 type: str
64 enable_automatic_upgrade:
65 description:
66 - Indicates whether the extension should be automatically upgraded by the platform if there is a newer version available.
67 type: bool
68 auto_upgrade_minor_version:
69 description:
70 - Indicates whether the extension should use a newer minor version if one is available at deployment time. Once deployed, however, the
71 extension will not upgrade minor versions unless redeployed, even with this property set to true.
72 - Does not work U(https://github.com/Azure/azure-rest-api-specs/issues/37591)
73 type: bool
74 settings:
75 description:
76 - Public settings for the extension.
77 type: dict
78 protected_settings:
79 description:
80 - Protected settings for the extension.
81 type: dict
82 state:
83 description:
84 - State of the arc machine extension
85 - Use C(present) for creating/updating a arc machine extension.
86 - Use C(absent) for deleting a arc machine extension.
87 default: present
88 type: str
89 choices:
90 - present
91 - absent
92 extends_documentation_fragment:
93 - azure.azcollection.azure
94 - azure.azcollection.azure_tags
95
96 author:
97 - Klaas Weyermann (@Klaas-)
98 '''
99
100 EXAMPLES = '''
101 - name: Add a arc machine extension
102 azure.azcollection.azure_rm_arcmachineextensions:
103 state: present
104 resource_group: resource_group_name
105 machine_name: vm_name
106 name: AzureMonitorLinuxAgent
107 location: germanywestcentral
108 properties:
109 auto_upgrade_minor_version: false
110 enable_automatic_upgrade: true
111 publisher: Microsoft.Azure.Monitor
112 type: AzureMonitorLinuxAgent
113 type_handler_version: 1.37.0
114
115 - name: Delete a arc machine extension
116 azure.azcollection.azure_rm_arcmachineextensions:
117 state: absent
118 name: arc_machine_extension_name
119 machine_name: vm_name
120 resource_group: resource_group_name
121 '''
122
123 RETURN = '''
124 arcmachineextension:
125 description:
126 - Details of the arc machine extension
127 - Is null on state==absent (arc machine extension does not exist or will be deleted)
128 - Assumes you make legal changes in check mode
129 type: dict
130 returned: always
131 sample: {
132 "id": \
133 "/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/ResourceGroup/providers/Microsoft.HybridCompute/machines/VMName/extensions/AzureMonitorLinuxAgent",
134 "location": "germanywestcentral",
135 "name": "AzureMonitorLinuxAgent",
136 "properties":
137 {
138 "auto_upgrade_minor_version": false,
139 "enable_automatic_upgrade": true,
140 "force_update_tag": null,
141 "instance_view":
142 {
143 "name": "AzureMonitorLinuxAgent",
144 "status":
145 {
146 "code": "0",
147 "level": "Information",
148 "message": "Extension Message: Enable succeeded",
149 },
150 "type": "AzureMonitorLinuxAgent",
151 "type_handler_version": "1.37.0",
152 },
153 "protected_settings": null,
154 "publisher": "Microsoft.Azure.Monitor",
155 "settings": null,
156 "type": "AzureMonitorLinuxAgent",
157 "type_handler_version": "1.37.0",
158 },
159 "system_data":
160 {
161 "created_at": "2025-09-24T13:12:35.754905Z",
162 "created_by": "your_sp",
163 "created_by_type": "Application",
164 "last_modified_at": "2025-09-24T13:12:35.754905Z",
165 "last_modified_by": "your_sp",
166 "last_modified_by_type": "Application",
167 },
168 "tags":
169 {
170 "Tag1": "Value1",
171 },
172 "type": "Microsoft.HybridCompute/machines/extensions",
173 }
174 '''
175
176 from ansible_collections.azure.azcollection.plugins.module_utils.azure_rm_common_ext import AzureRMModuleBaseExt
177
178 try:
179 from azure.core.exceptions import ResourceNotFoundError
180
181 except ImportError:
182 # This is handled in azure_rm_common
183 pass
184
185 AZURE_OBJECT_CLASS = 'hybridcomputemachineextensions'
186
187 properties_spec = dict(
188 force_update_tag=dict(type='str'),
189 publisher=dict(type='str'),
190 type=dict(type='str'),
191 type_handler_version=dict(type='str'),
192 enable_automatic_upgrade=dict(type='bool'),
193 auto_upgrade_minor_version=dict(type='bool'),
194 settings=dict(type='dict'),
195 protected_settings=dict(type='dict'),
196 )
197
198
199 class AzureRMarcmachineextensions(AzureRMModuleBaseExt):
200 """Information class for an Azure RM arc machine extensions"""
201
202 def __init__(self):
203 # https://learn.microsoft.com/en-us/python/api/azure-mgmt-hybridcompute/azure.mgmt.hybridcompute.models.machineextension?view=azure-python
204 self.module_arg_spec = dict(
205 name=dict(type='str', required=True),
206 resource_group=dict(type='str', required=True),
207 machine_name=dict(type='str', required=True),
208 location=dict(type='str'),
209 properties=dict(type='dict', options=properties_spec),
210 state=dict(type='str', choices=['present', 'absent'], default='present')
211 )
212
213 self.name = None
214 self.resource_group = None
215 self.machine_name = None
216 self.location = None
217 self.tags = None
218 self.properties = None
219 self.state = None
220 self.log_path = None
221 self.log_mode = None
222
223 self.results = dict(
224 changed=False,
225 arcmachineextension=dict(),
226 diff=dict(
227 before=None,
228 after=None
229 )
230 )
231
232 super(AzureRMarcmachineextensions, self).__init__(derived_arg_spec=self.module_arg_spec,
233 supports_check_mode=True,
234 supports_tags=True)
235
236 def exec_module(self, **kwargs):
237 """Main module execution method"""
238
239 for key in list(self.module_arg_spec.keys()) + ['tags']:
240 if hasattr(self, key):
241 setattr(self, key, kwargs[key])
242
243 # Defaults for variables
244 result = None
245 result_compare = dict(compare=[])
246 before_dict = None
247
248 # Get current arc machine extension if it exists
249 before_dict = self.get_arc_machine_extension()
250
251 # Create dict from input, without None values
252 # https://learn.microsoft.com/en-us/python/api/azure-mgmt-monitor/azure.mgmt.monitor.v2018_03_01.models.arcmachineextensionresource?view=azure-python
253 # tags seperately because of update_tags behavior
254 arc_machine_extension_template = {
255 "location": self.location,
256 "name": self.name,
257 "properties": self.properties
258 }
259 # Filter out all None values
260 arc_machine_extension_input = {key: value for key, value in arc_machine_extension_template.items() if value is not None}
261
262 # Create/Update if state==present
263 if self.state == 'present':
264 if before_dict is None:
265 # arc machine extension does not exist, create
266 # On creation input == what we send to api
267 arc_machine_extension_update = arc_machine_extension_input
268 # Needs to be extended by tags if set
269 if self.tags:
270 arc_machine_extension_update['tags'] = self.tags
271 # If no location is set default to the location of the resource group
272 if not self.location:
273 resource_group = self.get_resource_group(self.resource_group)
274 arc_machine_extension_update['location'] = resource_group.location
275 self.results['changed'] = True
276 if self.check_mode:
277 # Check mode, skipping actual creation
278 pass
279 else:
280 create_response = self.create_or_update(arc_machine_extension_update)
281 else:
282 # arc machine extension already exists, updating it
283 # Dict for update is the union of existing object overwritten by input data
284 arc_machine_extension_update = before_dict | arc_machine_extension_input
285
286 # Enhanced with tags (special behaviour because of append_tags possibility)
287 update_tags, update_tags_content = self.update_tags(before_dict.get('tags'))
288 # Check if we need to update the arc machine extension
289 if update_tags or not self.default_compare({}, arc_machine_extension_update, before_dict, '', result_compare):
290 arc_machine_extension_update['tags'] = update_tags_content
291 # Need to create/update the arc machine extension; changed -> True
292 self.results['changed'] = True
293 if self.check_mode:
294 # Check mode, skipping actual creation
295 pass
296 else:
297 create_response = self.create_or_update(arc_machine_extension_update)
298
299 if self.check_mode or not self.results['changed']:
300 # When object was not updated or when running in check mode
301 # assume arc_machine_extension_update is resulting object
302 result = arc_machine_extension_update
303 else:
304 # otherwise take resulting new object from response of create call
305 result = create_response
306
307 # Delete arc machine extension if state is absent and it exists
308 # if it doesn't exist, it's already absent
309 elif self.state == 'absent' and before_dict is not None:
310 self.results['changed'] = True
311 if self.check_mode:
312 # do not delete in check mode
313 pass
314 else:
315 self.delete()
316
317 self.results['diff']['before'] = before_dict
318 self.results['diff']['after'] = result
319 self.results['arcmachineextension'] = result
320
321 return self.results
322
323 def get_arc_machine_extension(self):
324 '''
325 Gets the properties of the specified arc machine extension.
326
327 :return: List of arc machine extensions
328 '''
329 self.log("Checking if arc machine extension {0} on machien {1} in resource group {2} is present".format(self.name,
330 self.machine_name,
331 self.resource_group))
332
333 result = None
334 response = None
335
336 try:
337 response = self.hybrid_compute_management_client.machine_extensions.get(extension_name=self.name,
338 machine_name=self.machine_name,
339 resource_group_name=self.resource_group)
340 except ResourceNotFoundError as ex:
341 self.log("Could not find arc machine extension {0} on machine {1} in resource group {2}".format(self.name, self.machine_name, self.resource_group))
342 if response:
343 result = self.serialize_obj(response, AZURE_OBJECT_CLASS)
344
345 return result
346
347 def create_or_update(self, arc_machine_extension_update):
348 result = None
349 response = None
350 arc_machine_extensions = self.hybrid_compute_management_client.machine_extensions
351
352 try:
353 response = arc_machine_extensions.begin_create_or_update(resource_group_name=self.resource_group,
354 machine_name=self.machine_name,
355 extension_name=self.name,
356 extension_parameters=arc_machine_extension_update,
357 logging_enable=False)
358 except Exception as ex:
359 self.fail("Error creating or update arc machine extension {0} on machine {1} in resource group {2}: {3}".format(self.name,
360 self.machine_name,
361 self.resource_group,
362 str(ex)))
363
364 if response:
365 result = self.serialize_obj(self.get_poller_result(response), AZURE_OBJECT_CLASS)
366
367 return result
368
369 def delete(self):
370 response = None
371 try:
372 response = self.hybrid_compute_management_client.machine_extensions.begin_delete(resource_group_name=self.resource_group,
373 machine_name=self.machine_name,
374 extension_name=self.name)
375 except Exception as ex:
376 self.fail("Error deleting arc machine {0} in resource group {1}: {2}".format(self.name, self.resource_group, str(ex)))
377
378 if response:
379 return self.get_poller_result(response)
380 else:
381 return None
382
383
384 def main():
385 """Main execution"""
386 AzureRMarcmachineextensions()
387
388
389 if __name__ == '__main__':
390 main()