Debian Codegraph @

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

raw symbols SCIP
1 #!/usr/bin/python
2 #
3 # Copyright (c) 2026 Zun Yang (@zunyangc)
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
11 DOCUMENTATION = '''
12 ---
13 module: azure_rm_appconfiguration
14 version_added: "3.15.0"
15 short_description: Manage Azure App Configuration stores.
16 description:
17 - Create, update and delete Azure App Configuration stores.
18
19 options:
20 resource_group:
21 description:
22 - The name of the Resource Group to which the App Configuration store belongs.
23 required: True
24 type: str
25 appconfig_name:
26 description:
27 - Name of the app configuration store.
28 required: True
29 type: str
30 identity:
31 description:
32 - Managed identity configuration for the store.
33 type: dict
34 suboptions:
35 type:
36 description:
37 - Type of the managed identity
38 required: true
39 choices:
40 - SystemAssigned
41 - UserAssigned
42 - SystemAssigned, UserAssigned
43 type: str
44 user_assigned_identity_ids:
45 description:
46 - List of user-assigned identity resource IDs (required when type includes UserAssigned).
47 required: false
48 type: list
49 elements: str
50 location:
51 description:
52 - Resource location. If not set, location from the resource group will be used as default.
53 type: str
54 sku:
55 description:
56 - SKU tier of the store.
57 type: str
58 choices:
59 - 'free'
60 - 'developer'
61 - 'standard'
62 - 'premium'
63 enable_purge_protection:
64 description:
65 - Property specifying whether protection against purge is enabled for this store.
66 type: bool
67 default: False
68 soft_delete_retention_in_days:
69 description:
70 - Property specifying the number of days to retain deleted store.
71 type: int
72 public_network_access:
73 description:
74 - Public network access setting for the store.
75 - If omitted at creation, Azure treats it as C(Automatic). Once set to C(Enabled) or C(Disabled), it cannot be returned to C(Automatic);
76 omit the property in updates to leave unchanged.
77 type: str
78 choices:
79 - Disabled
80 - Enabled
81 disable_local_auth:
82 description:
83 - Property specifying whether local authentication (access keys) is enabled for the store.
84 type: bool
85 default: False
86 replicas:
87 description:
88 - List of replicas to manage for this store.
89 type: list
90 elements: dict
91 suboptions:
92 name:
93 description:
94 - Name of the replica.
95 required: true
96 type: str
97 location:
98 description:
99 - Location of the replica.
100 required: true
101 type: str
102 is_purge_deleted:
103 description:
104 - Whether permanently deletes the specified store. aka Purges the deleted Azure App Configuration store
105 - When I(is_purge_deleted) is specified, the I(location) has to be configured.
106 - If not configured, the default location of the resource group will be used.
107 type: bool
108 default: False
109 state:
110 description:
111 - Assert the state of the App Configuration store. Use C(present) to create or update an App Configuration store and C(absent) to delete it.
112 default: present
113 type: str
114 choices:
115 - absent
116 - present
117
118 extends_documentation_fragment:
119 - azure.azcollection.azure
120 - azure.azcollection.azure_tags
121
122 author:
123 - Zun Yang (@zunyangc)
124
125 '''
126
127 EXAMPLES = '''
128 - name: Create a Standard App Configuration store with system-assigned identity
129 azure.azcollection.azure_rm_appconfiguration:
130 resource_group: myResourceGroup
131 appconfig_name: myAppConfigStore
132 location: eastus
133 sku: standard
134 identity:
135 type: SystemAssigned
136 enable_local_auth: true
137 tags:
138 env: prod
139 state: present
140
141 - name: Assign a user-assigned identity and enable purge protection
142 azure.azcollection.azure_rm_appconfiguration:
143 resource_group: myResourceGroup
144 appconfig_name: myAppConfigStore
145 identity:
146 type: UserAssigned
147 user_assigned_identity_ids:
148 - /subscriptions/xxxx/resourceGroups/myResourceGroup/providers/Microsoft.ManagedIdentity/userAssignedIdentities/myIdentity
149 enable_purge_protection: true
150 soft_delete_retention_in_days: 7
151 state: present
152
153 - name: Delete an App Configuration store
154 azure.azcollection.azure_rm_appconfiguration:
155 resource_group: myRG
156 appconfig_name: my-appconf-legacy
157 state: absent
158
159 - name: Purge a soft-deleted App Configuration store (subscription-level permission required)
160 azure.azcollection.azure_rm_appconfiguration:
161 resource_group: myRG
162 appconfig_name: my-appconf-legacy
163 location: eastus
164 is_purge_deleted: true
165 state: absent
166
167 - name: Create store with two replicas
168 azure.azcollection.azure_rm_appconfiguration:
169 resource_group: myRG
170 appconfig_name: myappconf
171 location: eastus
172 sku: standard
173 replicas:
174 - name: r1
175 location: westus
176 - name: r2
177 location: northeurope
178 state: present
179 '''
180
181 RETURN = '''
182 id:
183 description:
184 - The Azure Resource Manager resource ID for the App Configuration store.
185 returned: always
186 type: str
187 sample: /subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/myRG/providers/Microsoft.AppConfiguration/configurationStores/myAppConfigStore
188 '''
189
190 from ansible_collections.azure.azcollection.plugins.module_utils.azure_rm_common_ext import AzureRMModuleBaseExt
191
192 try:
193 from azure.core.polling import LROPoller
194 from azure.core.exceptions import ResourceNotFoundError, HttpResponseError
195 from azure.mgmt.appconfiguration import AppConfigurationManagementClient
196 except ImportError:
197 # Handled in azure_rm_common_ext
198 pass
199
200
201 class Actions:
202 NoAction, Create, Update, Delete = range(4)
203
204
205 class AzureRMAppConfiguration(AzureRMModuleBaseExt):
206 def __init__(self):
207 self.module_arg_spec = dict(
208 resource_group=dict(
209 type='str',
210 required=True
211 ),
212 appconfig_name=dict(
213 type='str',
214 required=True
215 ),
216 identity=dict(
217 type='dict',
218 options=dict(
219 type=dict(
220 type='str',
221 required=True,
222 choices=['SystemAssigned', 'UserAssigned', 'SystemAssigned, UserAssigned']
223 ),
224 user_assigned_identity_ids=dict(
225 type='list',
226 elements='str'
227 )
228 )
229 ),
230 location=dict(type='str'),
231 sku=dict(
232 type='str',
233 choices=['free', 'developer', 'standard', 'premium']
234 ),
235 enable_purge_protection=dict(
236 type='bool',
237 default=False
238 ),
239 soft_delete_retention_in_days=dict(
240 type='int'
241 ),
242 public_network_access=dict(
243 type='str',
244 choices=['Disabled', 'Enabled']
245 ),
246 disable_local_auth=dict(
247 type='bool',
248 default=False
249 ),
250 replicas=dict(
251 type='list',
252 elements='dict',
253 options=dict(
254 name=dict(type='str', required=True),
255 location=dict(type='str', required=True)
256 )
257 ),
258 # Administrative op: purge soft-deleted store
259 is_purge_deleted=dict(type='bool', default=False),
260
261 # Azure tags (provided by AzureRMModuleBaseExt)
262 # 'tags' is injected by base class when supports_tags=True
263
264 state=dict(
265 type='str',
266 default='present',
267 choices=['absent', 'present']
268 )
269 )
270
271 self.resource_group = None
272 self.appconfig_name = None
273 self.identity = None
274 self.is_purge_deleted = None
275
276 self.results = dict(changed=False)
277 self.mgmt_client = None
278 self.state = None
279 self.to_do = Actions.NoAction
280 self.parameters = dict()
281 self.tags = None
282
283 super(AzureRMAppConfiguration, self).__init__(derived_arg_spec=self.module_arg_spec,
284 supports_tags=True,
285 supports_check_mode=True)
286
287 @property
288 def managed_identity(self):
289 return {}
290
291 def exec_module(self, **kwargs):
292 """Main module execution method"""
293
294 # Bind known attributes and build parameters payload
295 for key in list(self.module_arg_spec.keys()) + ['tags']:
296 if key in kwargs:
297 setattr(self, key, kwargs[key])
298 if key in kwargs and kwargs.get(key) is not None:
299 if key == 'location':
300 self.parameters['location'] = kwargs[key]
301 elif key == 'sku':
302 # ARM expects {"sku": {"name": "<tier>"}}
303 self.parameters.setdefault('sku', {})['name'] = kwargs[key]
304 elif key == "public_network_access":
305 self.parameters.setdefault("properties", {})["publicNetworkAccess"] = kwargs[key]
306 elif key == "disable_local_auth":
307 self.parameters.setdefault("properties", {})["disableLocalAuth"] = kwargs[key]
308 elif key == "enable_purge_protection":
309 self.parameters.setdefault("properties", {})["enablePurgeProtection"] = kwargs[key]
310 elif key == "soft_delete_retention_in_days":
311 self.parameters.setdefault("properties", {})["softDeleteRetentionInDays"] = kwargs[key]
312
313 self.mgmt_client = self.get_mgmt_svc_client(AppConfigurationManagementClient,
314 base_url=self._cloud_environment.endpoints.resource_manager)
315
316 # Resolve RG + default location
317 resource_group = self.get_resource_group(self.resource_group)
318 if "location" not in self.parameters:
319 self.parameters['location'] = resource_group.location
320
321 # Validation: SKU vs purge fields
322 if self.sku not in ('standard', 'premium'):
323 if self.enable_purge_protection:
324 self.fail("enable_purge_protection is only supported on 'standard' or 'premium' SKUs.")
325 if self.soft_delete_retention_in_days is not None:
326 self.fail("soft_delete_retention_in_days is only supported on 'standard' or 'premium' SKUs.")
327
328 # Normalize identity changes using base helper
329 identity_dict = None
330 if self.identity:
331 id_type = (self.identity.get("type") or "").strip()
332 ids = self.identity.get("user_assigned_identity_ids") or []
333 if "UserAssigned" in id_type and not ids:
334 self.fail("identity.user_assigned_identity_ids must be provided when identity.type includes 'UserAssigned'.")
335 if id_type == "SystemAssigned":
336 identity_dict = {"type": "SystemAssigned"}
337 elif id_type == "UserAssigned":
338 identity_dict = {"type": "UserAssigned",
339 "userAssignedIdentities": {uid: {} for uid in ids}}
340 elif id_type == "SystemAssigned, UserAssigned":
341 identity_dict = {"type": "SystemAssigned, UserAssigned",
342 "userAssignedIdentities": {uid: {} for uid in ids}}
343 else:
344 # If not provided or unrecognized, omit identity block altogether
345 identity_dict = None
346
347 if identity_dict:
348 self.parameters["identity"] = identity_dict
349
350 # Read current
351 old_response = self.get_instance()
352 response = None
353
354 # Compute identity_changed
355 identity_changed = False
356 if old_response and identity_dict:
357 old_ident = old_response.get('identity') or {}
358 old_type = (old_ident.get('type') or '').lower()
359 new_type = (identity_dict.get('type') or '').lower()
360 if old_type != new_type:
361 identity_changed = True
362 else:
363 # Compare UAMI sets if applicable
364 if 'userassigned' in new_type:
365 old_ids = set(((old_ident.get('user_assigned_identities') or {}).keys()) or [])
366 new_ids = set(((identity_dict.get('userAssignedIdentities') or {}).keys()) or [])
367 if old_ids != new_ids:
368 identity_changed = True
369
370 # Decide action
371 if not old_response:
372 if self.state == 'absent':
373 self.log("Old instance didn't exist")
374 self.to_do = Actions.NoAction
375 else:
376 self.to_do = Actions.Create
377 else:
378 if self.state == 'absent':
379 self.to_do = Actions.Delete
380 else:
381 # compute update deltas
382 self.to_do = self._needs_update(old_response, self.parameters, identity_changed)
383
384 # Execute
385 if self.to_do in (Actions.Create, Actions.Update):
386 self.results['changed'] = True
387 if not self.check_mode:
388 self.parameters["tags"] = self.tags
389 response = self.create_or_update_store()
390 if self.replicas is not None:
391 self.reconcile_replicas(self.replicas)
392 if response is None:
393 response = self.get_instance()
394 elif self.to_do == Actions.Delete:
395 self.results['changed'] = True
396 if not self.check_mode:
397 self.delete_store()
398 elif self.to_do == Actions.NoAction and self.replicas is not None:
399 self.reconcile_replicas(self.replicas)
400 if response is None:
401 response = old_response or self.get_instance()
402 else:
403 # NoAction
404 self.results['changed'] = False
405 response = old_response
406
407 # Purge soft-deleted if requested
408 if self.is_purge_deleted:
409 purge_response = self.get_deleted(self.parameters["location"])
410 if purge_response:
411 self.results['changed'] = True
412 if not self.check_mode:
413 self.purge_deleted(self.parameters["location"])
414
415 if response is not None and hasattr(response, "as_dict"):
416 response = response.as_dict()
417
418 if response:
419 self.results["id"] = response["id"]
420
421 return self.results
422
423 def get_instance(self):
424 '''
425 Get the properties of the specified App Configuration store.
426
427 :return: deserialized App Configuration store instance state dictionary.
428 '''
429 try:
430 response = self.mgmt_client.configuration_stores.get(resource_group_name=self.resource_group,
431 config_store_name=self.appconfig_name)
432 return response.as_dict()
433 except ResourceNotFoundError:
434 return False
435
436 def create_or_update_store(self):
437 '''
438 Create or update (PUT) App Configuration store with the specified configuration.
439
440 :return: deserialized App Configuration store state dictionary.
441 '''
442 try:
443 poller = self.mgmt_client.configuration_stores.begin_create(resource_group_name=self.resource_group,
444 config_store_name=self.appconfig_name,
445 config_store_creation_parameters=self.parameters)
446 if isinstance(poller, LROPoller):
447 return self.get_poller_result(poller)
448 return poller.as_dict() if hasattr(poller, "as_dict") else poller
449 except Exception as exc:
450 self.fail("Error creating/updating App Configuration store '{}': {}".format(self.appconfig_name, str(exc)))
451
452 def delete_store(self):
453 '''
454 Delete the specified App Configuration store.
455
456 :return: True.
457 '''
458 try:
459 poller = self.mgmt_client.configuration_stores.begin_delete(resource_group_name=self.resource_group,
460 config_store_name=self.appconfig_name)
461 if isinstance(poller, LROPoller):
462 return self.get_poller_result(poller)
463 return True
464 except Exception as exc:
465 self.fail("Error deleting the App Configuration store '{}': {}".format(self.appconfig_name, str(exc)))
466
467 def get_deleted(self, location):
468 '''
469 Get deleted store
470 :return: True or False
471 '''
472 try:
473 self.mgmt_client.configuration_stores.get_deleted(self.appconfig_name, location)
474 except Exception as e:
475 self.log('Error attempting to get the deleted store: {0}'.format(str(e)))
476 return False
477 return True
478
479 def purge_deleted(self, location):
480 '''
481 Purge the specified soft-deleted App Configuration store.
482 '''
483 try:
484 poller = self.mgmt_client.configuration_stores.begin_purge_deleted(location=location,
485 config_store_name=self.appconfig_name)
486 if isinstance(poller, LROPoller):
487 return self.get_poller_result(poller)
488 return True
489 except HttpResponseError as e:
490 # 404/NotFound => nothing to purge
491 status = getattr(e, 'status_code', None) or getattr(getattr(e, 'response', None), 'status_code', None)
492 if status == 404:
493 return False
494 self.fail("Error purging deleted App Configuration store '{0}' in '{1}': {2}".format(
495 self.appconfig_name, location, str(e)))
496 except Exception as exc:
497 self.fail("Error purging deleted App Configuration store '{0}' in '{1}': {2}".format(
498 self.appconfig_name, location, str(exc)))
499
500 def _list_replicas(self):
501 '''
502 List replicas for the specified App Configuration store.
503
504 :return: Dictionary of replicas.
505 '''
506 found = {}
507 pager = self.mgmt_client.replicas.list_by_configuration_store(
508 resource_group_name=self.resource_group,
509 config_store_name=self.appconfig_name
510 )
511 for r in pager:
512 rd = r.as_dict()
513 found[rd['name']] = {'location': rd.get('location'), 'id': rd.get('id')}
514 return found
515
516 def _create_replica(self, name, location):
517 '''
518 Create a replica for the specified App Configuration store.
519
520 :return: deserialized replica instance state dictionary.
521 '''
522 poller = self.mgmt_client.replicas.begin_create(
523 resource_group_name=self.resource_group,
524 config_store_name=self.appconfig_name,
525 replica_name=name,
526 replica_creation_parameters={'location': location, 'properties': {}}
527 )
528 return self.get_poller_result(poller)
529
530 def _delete_replica(self, name):
531 '''
532 Delete a replica for the specified App Configuration store.
533
534 :return: True.
535 '''
536 poller = self.mgmt_client.replicas.begin_delete(
537 resource_group_name=self.resource_group,
538 config_store_name=self.appconfig_name,
539 replica_name=name
540 )
541 return self.get_poller_result(poller)
542
543 def reconcile_replicas(self, desired):
544 '''
545 Reconcile replicas to match desired state.
546 Authoritative: create missing, delete extras, recreate on location change.
547 '''
548 # desired: list[{'name': ..., 'location': ...}]
549 # authoritative behavior: create missing, delete extras, (re)create on location change
550 desired_index = {x['name']: x['location'] for x in (desired or [])}
551 current = self._list_replicas()
552
553 # create or recreate when location changed
554 for name, loc in desired_index.items():
555 if name not in current:
556 self.results['changed'] = True
557 if not self.check_mode:
558 self._create_replica(name, loc)
559 else:
560 if loc and (loc.lower() != (current[name].get('location') or '').lower()):
561 self.results['changed'] = True
562 if not self.check_mode:
563 self._delete_replica(name)
564 self._create_replica(name, loc)
565
566 # delete extras (authoritative)
567 extra = set(current.keys()) - set(desired_index.keys())
568 for name in sorted(extra):
569 self.results['changed'] = True
570 if not self.check_mode:
571 self._delete_replica(name)
572
573 def _needs_update(self, old, new_params, identity_changed):
574 '''
575 Determine whether an update is required by comparing fields.
576 Explicitly manage. Keep parity with Azure defaults where possible.
577
578 :return: Action Required.
579 '''
580 to_do = Actions.NoAction
581 props_new = new_params.get('properties') or {}
582
583 # sku
584 sku_old = ((old.get('sku') or {}).get('name') or '').lower()
585 sku_new = ((new_params.get('sku') or {}).get('name') or '').lower()
586 if sku_new and sku_new != sku_old:
587 # Note: provider/API might restrict downgrades; PUT will handle errors.
588 to_do = Actions.Update
589
590 # publicNetworkAccess
591 if 'publicNetworkAccess' in props_new:
592 if (props_new.get('publicNetworkAccess') or '').lower() != (old.get('public_network_access') or '').lower():
593 to_do = Actions.Update
594
595 # disableLocalAuth
596 if 'disableLocalAuth' in props_new:
597 if bool(props_new.get('disableLocalAuth')) != bool(old.get('disable_local_auth')):
598 to_do = Actions.Update
599
600 # enablePurgeProtection
601 if 'enablePurgeProtection' in props_new:
602 if bool(props_new.get('enablePurgeProtection')) != bool(old.get('enable_purge_protection')):
603 to_do = Actions.Update
604
605 # softDeleteRetentionInDays
606 if 'softDeleteRetentionInDays' in props_new:
607 if props_new.get('softDeleteRetentionInDays') != old.get('soft_delete_retention_in_days'):
608 to_do = Actions.Update
609
610 # tags
611 update_tags, newtags = self.update_tags(old.get('tags', {}) or {})
612 if update_tags:
613 self.tags = newtags
614 to_do = Actions.Update
615
616 # identity
617 if identity_changed:
618 to_do = Actions.Update
619
620 # Write back potentially adjusted props
621 if props_new:
622 new_params['properties'] = props_new
623
624 return to_do
625
626
627 def main():
628 """Main execution"""
629 AzureRMAppConfiguration()
630
631
632 if __name__ == '__main__':
633 main()