Debian Codegraph @

ansible_collections/community/hrobot/plugins/modules/storagebox_snapshot_plan.py

raw
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3
4 # Copyright (c) 2025 Felix Fontein <[email protected]>
5 # GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
6 # SPDX-License-Identifier: GPL-3.0-or-later
7
8 from __future__ import absolute_import, division, print_function
9 __metaclass__ = type
10
11
12 DOCUMENTATION = r"""
13 module: storagebox_snapshot_plan
14 short_description: Modify a storage box's snapshot plans
15 version_added: 2.1.0
16 author:
17 - Felix Fontein (@felixfontein)
18 description:
19 - Enable, modify, and disable the snapshot plans of a storage box.
20 extends_documentation_fragment:
21 - community.hrobot.api._robot_compat_shim_deprecation # must come before api and robot
22 - community.hrobot.api
23 - community.hrobot.robot
24 - community.hrobot.attributes
25 - community.hrobot.attributes._actiongroup_robot_and_api_deprecation # must come before the other two!
26 - community.hrobot.attributes.actiongroup_api
27 - community.hrobot.attributes.actiongroup_robot
28 attributes:
29 check_mode:
30 support: full
31 diff_mode:
32 support: full
33 idempotent:
34 support: full
35
36 options:
37 hetzner_token:
38 version_added: 2.5.0
39 storagebox_id:
40 description:
41 - The ID of the storage box to modify.
42 type: int
43 required: true
44 plans:
45 description:
46 - The storage plan configurations.
47 - Note that right now there must be exactly one element.
48 - All date and time parameters are in UTC.
49 type: list
50 elements: dict
51 required: true
52 suboptions:
53 status:
54 description:
55 - The status of the snapshot plan.
56 type: str
57 choices:
58 - enabled
59 - disabled
60 required: true
61 minute:
62 description:
63 - The minute of execution of the plan.
64 - Required if O(plans[].status=enabled).
65 type: int
66 hour:
67 description:
68 - The hour of execution of the plan.
69 - Required if O(plans[].status=enabled).
70 type: int
71 day_of_week:
72 description:
73 - The day of the week of execution of the plan. V(1) is Monday, V(7) is Sunday.
74 - If set to V(null) or omitted, the plan is run every day of a week, unless there are other restrictions.
75 type: int
76 day_of_month:
77 description:
78 - The day of month of execution of the plan. V(1) is the 1st day of the month.
79 - If set to V(null) or omitted, the plan is run every day of a month, unless there are other restrictions.
80 type: int
81 month:
82 description:
83 - The month of execution of the plan. V(1) is January, V(12) is December.
84 - If set to V(null) or omitted, the plan is run every month.
85 - Cannot be used if O(hetzner_token) is provided.
86 type: int
87 max_snapshots:
88 description:
89 - The maximum number of automatic snapshots of this plan.
90 - Required if O(plans[].status=enabled).
91 type: int
92 """
93
94 EXAMPLES = r"""
95 ---
96 - name: Setup storagebox
97 community.hrobot.storagebox_snapshot_plan:
98 hetzner_user: foo
99 hetzner_password: bar
100 storagebox_id: 123
101 plans:
102 - status: enabled
103 minute: 5
104 hour: 12
105 day_of_week: 2 # Tuesday
106 max_snapshots: 2
107 """
108
109 RETURN = r"""
110 plans:
111 description:
112 - The storage box's snapshot plan configurations.
113 - All date and time parameters are in UTC.
114 returned: success
115 type: list
116 elements: dict
117 contains:
118 status:
119 description:
120 - The status of the snapshot plan.
121 type: str
122 sample: enabled
123 returned: success
124 choices:
125 - enabled
126 - disabled
127 minute:
128 description:
129 - The minute of execution of the plan.
130 type: int
131 sample: 5
132 returned: success
133 hour:
134 description:
135 - The hour of execution of the plan.
136 type: int
137 sample: 12
138 returned: success
139 day_of_week:
140 description:
141 - The day of the week of execution of the plan. V(1) is Monday, V(7) is Sunday.
142 - If set to V(null), the plan is run every day of a week, unless there are other restrictions.
143 type: int
144 sample: 2
145 returned: success
146 day_of_month:
147 description:
148 - The day of month of execution of the plan. V(1) is the 1st day of the month.
149 - If set to V(null), the plan is run every day of a month, unless there are other restrictions.
150 type: int
151 sample: null
152 returned: success
153 month:
154 description:
155 - The month of execution of the plan. V(1) is January, V(12) is December.
156 - If set to V(null), the plan is run every month.
157 - Always V(null) if O(hetzner_token) is provided.
158 - B(This return value is deprecated and will be removed from community.hrobot 3.0.0.)
159 If you are using ansible-core 2.19 or newer, you will see a deprecation message when using this return value when using O(hetzner_token).
160 type: int
161 sample: null
162 returned: success
163 max_snapshots:
164 description:
165 - The maximum number of automatic snapshots of this plan.
166 type: int
167 sample: 2
168 returned: success
169 """
170
171 from ansible.module_utils.basic import AnsibleModule
172
173 from ansible_collections.community.hrobot.plugins.module_utils.robot import (
174 BASE_URL,
175 ROBOT_DEFAULT_ARGUMENT_SPEC,
176 _ROBOT_DEFAULT_ARGUMENT_SPEC_COMPAT_DEPRECATED,
177 fetch_url_json,
178 )
179
180 from ansible_collections.community.hrobot.plugins.module_utils.api import (
181 API_BASE_URL,
182 API_DEFAULT_ARGUMENT_SPEC,
183 _API_DEFAULT_ARGUMENT_SPEC_COMPAT,
184 ApplyActionError,
185 api_apply_action,
186 api_fetch_url_json,
187 )
188
189 from ansible_collections.community.hrobot.plugins.module_utils._tagging import (
190 deprecate_value,
191 )
192
193 try:
194 from urllib.parse import urlencode
195 except ImportError:
196 # Python 2.x fallback:
197 from urllib import urlencode
198
199
200 LEGACY_PARAMETERS = {
201 'status': ('status', 'status'), # according to the API docs 'status' cannot be provided as input to POST, but that's not true
202 'minute': ('minute', 'minute'),
203 'hour': ('hour', 'hour'),
204 'day_of_week': ('day_of_week', 'day_of_week'),
205 'day_of_month': ('day_of_month', 'day_of_month'),
206 'month': ('month', 'month'),
207 'max_snapshots': ('max_snapshots', 'max_snapshots'),
208 }
209
210
211 def extract_legacy(result):
212 sb = result['snapshotplan']
213 return {key: sb.get(key) for key, dummy in LEGACY_PARAMETERS.values()}
214
215
216 def extract(result):
217 sb = result['storage_box']
218 sp = sb.get('snapshot_plan')
219 if not sp:
220 return {
221 'status': 'disabled',
222 'minute': None,
223 'hour': None,
224 'day_of_week': None,
225 'day_of_month': None,
226 'month': deprecate_value(None, "The return value `month` is deprecated; it is always null.", version="3.0.0"),
227 'max_snapshots': None,
228 }
229
230 return {
231 'status': 'enabled',
232 'minute': sp['minute'],
233 'hour': sp['hour'],
234 'day_of_week': sp['day_of_week'],
235 'day_of_month': sp['day_of_month'],
236 'month': deprecate_value(None, "The return value `month` is deprecated; it is always null.", version="3.0.0"),
237 'max_snapshots': sp['max_snapshots'],
238 }
239
240
241 def main():
242 argument_spec = dict(
243 storagebox_id=dict(type='int', required=True),
244 plans=dict(
245 type='list',
246 elements='dict',
247 required=True,
248 options=dict(
249 status=dict(type='str', required=True, choices=['enabled', 'disabled']),
250 minute=dict(type='int'),
251 hour=dict(type='int'),
252 day_of_week=dict(type='int'),
253 day_of_month=dict(type='int'),
254 month=dict(type='int'),
255 max_snapshots=dict(type='int'),
256 ),
257 required_if=[
258 ('status', 'enabled', ('minute', 'hour', 'max_snapshots')),
259 ],
260 ),
261 )
262 argument_spec.update(ROBOT_DEFAULT_ARGUMENT_SPEC)
263 argument_spec.update(_ROBOT_DEFAULT_ARGUMENT_SPEC_COMPAT_DEPRECATED)
264 argument_spec.update(API_DEFAULT_ARGUMENT_SPEC)
265 argument_spec.update(_API_DEFAULT_ARGUMENT_SPEC_COMPAT)
266 module = AnsibleModule(
267 argument_spec=argument_spec,
268 supports_check_mode=True,
269 )
270
271 storagebox_id = module.params['storagebox_id']
272 plans = module.params['plans']
273 # TODO: If the API ever changes to support more than one plan, the following needs to
274 # be removed and the corresponding part in the documentation must be updated.
275 if len(plans) != 1:
276 module.fail_json(msg='`plans` must have exactly one element')
277 plan = plans[0]
278
279 if module.params["hetzner_user"] is not None:
280 module.deprecate(
281 "The hetzner_token parameter will be required from community.hrobot 3.0.0 on.",
282 collection_name="community.hrobot",
283 version="3.0.0",
284 )
285 # DEPRECATED: old API
286 url = "{0}/storagebox/{1}/snapshotplan".format(BASE_URL, storagebox_id)
287 result, error = fetch_url_json(module, url, accept_errors=['STORAGEBOX_NOT_FOUND'])
288 if error:
289 module.fail_json(msg='Storagebox with ID {0} does not exist'.format(storagebox_id))
290
291 # The documentation (https://robot.hetzner.com/doc/webservice/en.html#get-storagebox-storagebox-id-snapshotplan)
292 # claims that the result is a list, but actually it is a dictionary. Convert it to a list of dicts if that's the case.
293 if isinstance(result, dict):
294 result = [result]
295
296 before = [extract_legacy(plan) for plan in result]
297 after = [
298 {
299 data_name: (
300 plan[option_name]
301 if plan['status'] == 'enabled' or option_name == 'status' else
302 None
303 )
304 for option_name, (data_name, dummy) in LEGACY_PARAMETERS.items()
305 }
306 for plan in plans
307 ]
308 changes = []
309
310 for index, plan in enumerate(after):
311 existing_plan = before[index] if index < len(before) else {}
312 plan_values = {}
313 has_changes = False
314 for data_name, change_name in LEGACY_PARAMETERS.values():
315 before_value = existing_plan.get(data_name)
316 after_value = plan[data_name]
317 if before_value != after_value:
318 has_changes = True
319 if after_value is not None and change_name is not None:
320 plan_values[change_name] = after_value
321 if has_changes:
322 if plan['status'] == 'disabled':
323 # For some reason, minute and hour are required even for disabled plans,
324 # even though the documentation says otherwise
325 plan_values['minute'] = 0
326 plan_values['hour'] = 0
327 changes.append((index, plan_values))
328
329 if changes and not module.check_mode:
330 headers = {"Content-type": "application/x-www-form-urlencoded"}
331 # TODO: If the API ever changes to support more than one plan, the following need to change
332 if len(changes) != 1: # pragma: no cover
333 raise AssertionError('Current implementation can handle only one plan') # pragma: no cover
334 actual_changes = changes[0][1]
335 result, error = fetch_url_json(
336 module,
337 url,
338 data=urlencode(actual_changes) if actual_changes else None,
339 headers=headers,
340 method='POST',
341 accept_errors=['INVALID_INPUT'],
342 )
343 if error:
344 invalid = result['error'].get('invalid') or []
345 module.fail_json(msg='The values to update were invalid ({0})'.format(', '.join(invalid)))
346
347 # The documentation (https://robot.hetzner.com/doc/webservice/en.html#post-storagebox-storagebox-id-snapshotplan)
348 # claims that the result is a list, but actually it is a dictionary. Convert it to a list of dicts if that's the case.
349 if isinstance(result, dict):
350 result = [result]
351
352 after = [extract_legacy(plan) for plan in result]
353
354 changed = bool(changes)
355
356 else:
357 # NEW API!
358 if plans[0]['month'] is not None:
359 module.fail_json(msg='The new Hetzner API does not support specifying month for a plan.')
360
361 url = "{0}/v1/storage_boxes/{1}".format(API_BASE_URL, storagebox_id)
362 result, dummy, error = api_fetch_url_json(module, url, accept_errors=["not_found"])
363 if error:
364 module.fail_json(msg='Storagebox with ID {0} does not exist'.format(storagebox_id))
365
366 before = extract(result)
367 after = {
368 key: (value if plan['status'] == 'enabled' or key == 'status' else None)
369 for key, value in plan.items()
370 }
371 action_enable = None
372 if before != after:
373 action_enable = (after['status'] == 'enabled')
374 action = {key: value for key, value in plan.items() if key not in ('status', 'month')} if action_enable else {}
375
376 if action_enable is not None and not module.check_mode:
377 action_url = "{0}/actions/{1}".format(url, 'enable_snapshot_plan' if action_enable else 'disable_snapshot_plan')
378 try:
379 api_apply_action(
380 module,
381 action_url,
382 action if action_enable else None,
383 lambda action_id: "{0}/v1/storage_boxes/actions/{1}".format(API_BASE_URL, action_id),
384 check_done_delay=1,
385 check_done_timeout=60,
386 )
387 except ApplyActionError as exc:
388 module.fail_json(msg='Error while updating the snapshot plan: {0}'.format(exc))
389
390 changed = action_enable is not None
391 before = [before]
392 after = [after]
393
394 module.exit_json(
395 changed=changed,
396 plans=after,
397 diff={
398 'before': {'plans': before},
399 'after': {'plans': after},
400 },
401 )
402
403
404 if __name__ == '__main__': # pragma: no cover
405 main() # pragma: no cover