Debian Codegraph @

ansible_collections/azure/azcollection/plugins/modules/azure_rm_appconfigurationkey.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_appconfigurationkey
14 version_added: "3.15.0"
15 short_description: Manage key-values (and Key Vault reference) in Azure App Configuration.
16 description:
17 - Create, update, lock/unlock, or delete a key in an Azure App Configuration store.
18 - Supports both simple key-values (type=kv) and Key Vault reference (type=vault).
19 - For C(type=vault), the module writes the reference value and content-type required by App Configuration.
20
21 options:
22 endpoint:
23 description:
24 - The App Configuration data-plane endpoint, for example C(https://myappconf.azconfig.io).
25 type: str
26 required: true
27 key:
28 description:
29 - Name of the configuration key.
30 - Together with I(label), identifies a single setting.
31 type: str
32 required: true
33 label:
34 description:
35 - Optional label to disambiguate settings with the same key.
36 type: str
37 type:
38 description:
39 - The setting type to manage.
40 - C(kv) creates/updates a plain key-value.
41 - C(vault) creates/updates a Key Vault reference entry.
42 type: str
43 choices:
44 - kv
45 - vault
46 default: kv
47 value:
48 description:
49 - The value for C(type=kv). Required when creating a new C(kv) setting.
50 - Ignored on updates if you only want to change I(content_type), or I(read_only).
51 type: str
52 content_type:
53 description:
54 - Content type metadata for the setting.
55 - Ignored for C(type=vault), the KV-reference content-type is fixed by the service.
56 type: str
57 vault_key_reference:
58 description:
59 - The versionless Key Vault Secret ID for a Key Vault reference C(type=vault).
60 type: str
61 read_only:
62 description:
63 - Whether the setting should be read-only in App Configuration.
64 type: bool
65 state:
66 description:
67 - Assert the state of the configuration setting. Use C(present) to create or update the setting and C(absent) to delete.
68 type: str
69 default: present
70 choices:
71 - absent
72 - present
73
74 extends_documentation_fragment:
75 - azure.azcollection.azure
76
77 author:
78 - Zun Yang (@zunyangc)
79
80 '''
81
82 EXAMPLES = '''
83 - name: Create/Update a plain key-value
84 azure.azcollection.azure_rm_appconfigurationkey:
85 endpoint: https://myappconf.azconfig.io
86 key: "Payments:TimeoutSeconds"
87 label: "prod"
88 type: kv
89 value: "30"
90 content_type: "text/plain"
91 read_only: true
92 state: present
93
94 - name: Create/Update a Key Vault reference (versionless secret ID)
95 azure.azcollection.azure_rm_appconfigurationkey:
96 endpoint: https://myappconf.azconfig.io
97 key: "Payments:ApiKey"
98 label: "prod"
99 type: vault
100 vault_key_reference: "https://myvault.vault.azure.net/secrets/my-secret/xxxx"
101 read_only: false
102 state: present
103
104 - name: Delete a key
105 azure.azcollection.azure_rm_appconfigurationkey:
106 endpoint: https://myappconf.azconfig.io
107 key: "Legacy:Flag"
108 label: "prod"
109 state: absent
110 '''
111
112 RETURN = '''
113 id:
114 description:
115 - Identifier of the configuration setting (data-plane URL form).
116 returned: always
117 type: str
118 example: https://myappconf.azconfig.io/kv/Payments:TimeoutSeconds?label=prod
119 ''' # NOQA
120
121 import json
122 import traceback
123 from ansible_collections.azure.azcollection.plugins.module_utils.azure_rm_common_ext import AzureRMModuleBaseExt
124
125 try:
126 from azure.core.exceptions import ResourceNotFoundError
127 from azure.appconfiguration import AzureAppConfigurationClient, ConfigurationSetting
128 except ImportError:
129 # Handled in azure_rm_common_ext
130 pass
131
132
133 VAULT_CT = "application/vnd.microsoft.appconfig.keyvaultref+json;charset=utf-8"
134
135
136 class Actions:
137 NoAction, Create, Update, Delete = range(4)
138
139
140 class AzureRMAppConfigurationKey(AzureRMModuleBaseExt):
141 def __init__(self):
142 self.module_arg_spec = dict(
143 endpoint=dict(type='str', required=True),
144 key=dict(
145 type='str',
146 required=True,
147 no_log=False
148 ),
149 label=dict(type='str'),
150 type=dict(
151 type='str',
152 choices=['kv', 'vault'],
153 default='kv'
154 ),
155 value=dict(
156 type='str',
157 no_log=True
158 ),
159 content_type=dict(type='str'),
160 vault_key_reference=dict(type='str', no_log=True),
161 read_only=dict(type='bool'),
162
163 state=dict(
164 type='str',
165 default='present',
166 choices=['absent', 'present']
167 )
168 )
169
170 self.endpoint = None
171 self.key = None
172 self.label = None
173 self.type = None
174 self.value = None
175 self.content_type = None
176 self.vault_key_reference = None
177 self.read_only = None
178
179 self.dataplane_client = None
180 self.mgmt_client = None
181 self.state = None
182 self.parameters = dict()
183 self.results = dict(changed=False)
184 self.to_do = Actions.NoAction
185
186 super(AzureRMAppConfigurationKey, self).__init__(derived_arg_spec=self.module_arg_spec,
187 supports_tags=False,
188 supports_check_mode=True)
189
190 def exec_module(self, **kwargs):
191 """Main module execution method"""
192
193 for key in list(self.module_arg_spec.keys()):
194 if key in kwargs:
195 setattr(self, key, kwargs[key])
196 if key in kwargs and kwargs.get(key) is not None:
197 if key == 'type':
198 self.parameters['type'] = kwargs[key]
199 elif key == 'content_type':
200 self.parameters['content_type'] = kwargs[key]
201 elif key == 'value':
202 self.parameters['value'] = kwargs[key]
203 elif key == 'vault_key_reference':
204 self.parameters['vault_key_reference'] = kwargs[key]
205 elif key == 'read_only':
206 self.parameters['read_only'] = bool(kwargs[key])
207
208 # Resolve endpoint if needed (from ARM ID)
209 self.mgmt_client = None
210
211 # Build data-plane client
212 self.dataplane_client = AzureAppConfigurationClient(self.endpoint,
213 credential=self.azure_auth.azure_credential_track2)
214
215 # Read current
216 old_response = self.get_setting()
217 response = None
218
219 # Validation: kv vs value
220 if self.state == 'present' and old_response is None:
221 # default type if not provided
222 if self.type == 'kv' and self.value is None:
223 self.fail("Parameter 'value' is required when creating a type='kv' setting.")
224 if self.type == 'vault' and not self.vault_key_reference:
225 self.fail("Parameter 'vault_key_reference' is required when creating a type='vault' setting.")
226
227 # Decide action
228 if not old_response:
229 if self.state == 'absent':
230 self.log("Settings did not exist")
231 self.to_do = Actions.NoAction
232 else:
233 self.to_do = Actions.Create
234 else:
235 if self.state == 'absent':
236 self.to_do = Actions.Delete
237 else:
238 self.to_do = self._needs_update(old_response, self.parameters)
239
240 # unlock-first, upsert/delete, lock-finally
241 if self.to_do in (Actions.Create, Actions.Update):
242 # If the existing setting is locked, unlock BEFORE upsert.
243 original_ro = bool(old_response.get('read_only')) if old_response else False
244 if old_response and original_ro and not self.check_mode:
245 self.ensure_lock_state(False)
246
247 # Perform the upsert
248 self.results['changed'] = True
249 if not self.check_mode:
250 response = self.upsert_setting()
251
252 # Decide final lock state:
253 # If caller explicitly set read_only, honor it.
254 # Otherwise, restore the original lock (for updates).
255 final_ro = bool(self.read_only) if self.read_only is not None else original_ro
256 if not self.check_mode:
257 self.ensure_lock_state(final_ro)
258
259 if response is None:
260 response = self.get_setting()
261
262 elif self.to_do == Actions.Delete:
263 # If the existing setting is locked, unlock BEFORE delete.
264 original_ro = bool(old_response.get('read_only')) if old_response else False
265 if old_response and original_ro and not self.check_mode:
266 self.ensure_lock_state(False)
267
268 self.results['changed'] = True
269 if not self.check_mode:
270 self.delete_setting()
271 self.results['id'] = self._compose_id(self.endpoint, self.key, self.label)
272 return self.results
273
274 else:
275 # No data changes; converge lock ONLY if the user explicitly asked.
276 self.log("No action needed on the setting.")
277 self.results['changed'] = False
278 response = old_response
279
280 if response and self.read_only is not None:
281 current_ro = bool(response.get('read_only'))
282 desired_ro = bool(self.read_only)
283 if current_ro != desired_ro:
284 self.results['changed'] = True
285 if not self.check_mode:
286 self.ensure_lock_state(desired_ro)
287 response = self.get_setting()
288
289 if response:
290 self.results['id'] = self._compose_id(self.endpoint, self.key, self.label)
291
292 return self.results
293
294 def get_setting(self):
295 '''
296 Retrieve the current configuration setting from the data plane.
297
298 :return: The configuration setting as a dictionary, or False if not found.
299 '''
300 try:
301 response = self.dataplane_client.get_configuration_setting(
302 key=self.key,
303 label=self.label
304 )
305 return response.as_dict()
306 except ResourceNotFoundError:
307 return False
308 except Exception as e:
309 # Catch SDK bug: empty response causes JSONDecodeError
310 self.fail("Failed to retrieve setting '{}': {}\n{}".format(self.key, str(e), traceback.format_exc()))
311
312 def upsert_setting(self):
313 '''
314 Upsert (create or update) the configuration setting in the data plane.
315
316 :return: The updated configuration setting as a dictionary.
317 '''
318 try:
319 if self.type == 'kv':
320 if self.value is not None:
321 desired_value = self.value
322 else:
323 cur = self.get_setting() or {}
324 desired_value = cur.get('value', '')
325
326 cs = ConfigurationSetting(key=self.key,
327 label=self.label,
328 value=desired_value,
329 content_type=self.content_type)
330
331 response = self.dataplane_client.set_configuration_setting(configuration_setting=cs)
332 else:
333 # vault
334 payload = json.dumps({"uri": self.vault_key_reference})
335
336 cs = ConfigurationSetting(key=self.key,
337 label=self.label,
338 value=payload,
339 content_type=VAULT_CT) # official KV-ref MIME
340
341 response = self.dataplane_client.set_configuration_setting(configuration_setting=cs)
342 return response.as_dict()
343 except Exception as exc:
344 self.fail("Error creating/updating the Configuration Setting '{}': {}".format(self.key, str(exc)))
345
346 def delete_setting(self):
347 '''
348 Delete the configuration setting from the data plane.
349
350 :return: The deleted configuration setting as a dictionary.
351 '''
352 try:
353 response = self.dataplane_client.delete_configuration_setting(key=self.key,
354 label=self.label)
355 return response.as_dict()
356 except Exception as exc:
357 self.fail("Error deleting the Configuration Setting '{}': {}".format(self.key, str(exc)))
358
359 def ensure_lock_state(self, read_only):
360 '''
361 Converge the read-only (lock) state of the setting.
362
363 :return: The updated configuration setting as a dictionary.
364 '''
365 try:
366 cs = ConfigurationSetting(key=self.key, label=self.label)
367 response = self.dataplane_client.set_read_only(configuration_setting=cs,
368 read_only=bool(read_only))
369 return response.as_dict()
370 except Exception as exc:
371 self.fail("Error setting read_only={} on Configuration Setting '{}': {}".format(read_only, self.key, str(exc)))
372
373 def _needs_update(self, old, new_params):
374 '''
375 Determine whether an update is required by comparing fields, honoring user intent.
376
377 :return: Actions.Update or Actions.NoAction
378 '''
379 to_do = Actions.NoAction
380 # type
381 if (old.get('type') or 'kv') != (new_params.get('type') or 'kv'):
382 to_do = Actions.Update
383
384 if (new_params.get('type') or 'kv') == 'kv':
385 if self.value is not None and old.get('value') != self.value:
386 to_do = Actions.Update
387 if self.content_type is not None and (self.content_type or None) != (old.get('content_type') or None):
388 to_do = Actions.Update
389 else:
390 if self.vault_key_reference is not None and old.get('vault_key_reference') != self.vault_key_reference:
391 to_do = Actions.Update
392
393 return to_do
394
395 @staticmethod
396 def _compose_id(endpoint, key, label):
397 '''
398 Compose a deterministic data-plane identifier for the setting.
399 - With label: "<endpoint>/kv/<key>?label=<label>"
400 - Without label: "<endpoint>/kv/<key>"
401
402 :return: The composed identifier string.
403 '''
404 base = endpoint.rstrip('/')
405 if label:
406 return f"{base}/kv/{key}?label={label}"
407 return f"{base}/kv/{key}"
408
409
410 def main():
411 """Main execution"""
412 AzureRMAppConfigurationKey()
413
414
415 if __name__ == '__main__':
416 main()