Debian Codegraph @

ansible_collections/community/general/plugins/modules/packet_volume.py

raw
1 #!/usr/bin/python
2
3 # Copyright (c) 2019, Nurfet Becirevic <[email protected]>
4 # Copyright (c) 2017, Tomas Karasek <[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 annotations
9
10 DOCUMENTATION = r"""
11 module: packet_volume
12
13 short_description: Create/delete a volume in Packet host
14
15 description:
16 - Create/delete a volume in Packet host.
17 - API is documented at U(https://www.packet.com/developers/api/#volumes).
18 version_added: '0.2.0'
19
20 author:
21 - Tomas Karasek (@t0mk) <[email protected]>
22 - Nurfet Becirevic (@nurfet-becirevic) <[email protected]>
23
24 extends_documentation_fragment:
25 - community.general._attributes
26
27 attributes:
28 check_mode:
29 support: full
30 diff_mode:
31 support: none
32
33 options:
34 state:
35 description:
36 - Desired state of the volume.
37 default: present
38 choices: ['present', 'absent']
39 type: str
40
41 project_id:
42 description:
43 - ID of project of the device.
44 required: true
45 type: str
46
47 auth_token:
48 description:
49 - Packet API token. You can also supply it in environment variable E(PACKET_API_TOKEN).
50 type: str
51
52 name:
53 description:
54 - Selector for API-generated name of the volume.
55 type: str
56
57 description:
58 description:
59 - User-defined description attribute for Packet volume.
60 - It is used used as idempotent identifier - if volume with given description exists, new one is not created.
61 type: str
62
63 id:
64 description:
65 - UUID of a volume.
66 type: str
67
68 plan:
69 description:
70 - V(storage_1) for standard tier, V(storage_2) for premium (performance) tier.
71 - Tiers are described at U(https://www.packet.com/cloud/storage/).
72 choices: ['storage_1', 'storage_2']
73 default: 'storage_1'
74 type: str
75
76 facility:
77 description:
78 - Location of the volume.
79 - Volumes can only be attached to device in the same location.
80 type: str
81
82 size:
83 description:
84 - Size of the volume in gigabytes.
85 type: int
86
87 locked:
88 description:
89 - Create new volume locked.
90 type: bool
91 default: false
92
93 billing_cycle:
94 description:
95 - Billing cycle for new volume.
96 choices: ['hourly', 'monthly']
97 default: 'hourly'
98 type: str
99
100 snapshot_policy:
101 description:
102 - Snapshot policy for new volume.
103 type: dict
104
105 suboptions:
106 snapshot_count:
107 description:
108 - How many snapshots to keep, a positive integer.
109 required: true
110 type: int
111
112 snapshot_frequency:
113 description:
114 - Frequency of snapshots.
115 required: true
116 choices: ["15min", "1hour", "1day", "1week", "1month", "1year"]
117 type: str
118
119 requirements:
120 - "packet-python >= 1.35"
121 """
122
123 EXAMPLES = r"""
124 # All the examples assume that you have your Packet API token in env var PACKET_API_TOKEN.
125 # You can also pass the api token in module param auth_token.
126
127 - hosts: localhost
128 vars:
129 volname: testvol123
130 project_id: 53000fb2-ee46-4673-93a8-de2c2bdba33b
131
132 tasks:
133 - name: Create volume
134 community.general.packet_volume:
135 description: "{{ volname }}"
136 project_id: "{{ project_id }}"
137 facility: 'ewr1'
138 plan: 'storage_1'
139 state: present
140 size: 10
141 snapshot_policy:
142 snapshot_count: 10
143 snapshot_frequency: 1day
144 register: result_create
145
146 - name: Delete volume
147 community.general.packet_volume:
148 id: "{{ result_create.id }}"
149 project_id: "{{ project_id }}"
150 state: absent
151 """
152
153 RETURN = r"""
154 id:
155 description: UUID of specified volume.
156 type: str
157 returned: success
158 sample: 53000fb2-ee46-4673-93a8-de2c2bdba33c
159 name:
160 description: The API-generated name of the volume resource.
161 type: str
162 returned: if volume is attached/detached to/from some device
163 sample: "volume-a91dc506"
164 description:
165 description: The user-defined description of the volume resource.
166 type: str
167 returned: success
168 sample: "Just another volume"
169 """
170
171 import uuid
172
173 from ansible.module_utils.basic import AnsibleModule, env_fallback
174
175 HAS_PACKET_SDK = True
176
177
178 try:
179 import packet
180 except ImportError:
181 HAS_PACKET_SDK = False
182
183
184 PACKET_API_TOKEN_ENV_VAR = "PACKET_API_TOKEN"
185
186 VOLUME_PLANS = ["storage_1", "storage_2"]
187 VOLUME_STATES = ["present", "absent"]
188 BILLING = ["hourly", "monthly"]
189
190
191 def is_valid_uuid(myuuid):
192 try:
193 val = uuid.UUID(myuuid, version=4)
194 except ValueError:
195 return False
196 return str(val) == myuuid
197
198
199 def get_volume_selector(module):
200 if module.params.get("id"):
201 i = module.params.get("id")
202 if not is_valid_uuid(i):
203 raise Exception(f"Volume ID '{i}' is not a valid UUID")
204 return lambda v: v["id"] == i
205 elif module.params.get("name"):
206 n = module.params.get("name")
207 return lambda v: v["name"] == n
208 elif module.params.get("description"):
209 d = module.params.get("description")
210 return lambda v: v["description"] == d
211
212
213 def get_or_fail(params, key):
214 item = params.get(key)
215 if item is None:
216 raise Exception(f"{key} must be specified for new volume")
217 return item
218
219
220 def act_on_volume(target_state, module, packet_conn):
221 return_dict = {"changed": False}
222 s = get_volume_selector(module)
223 project_id = module.params.get("project_id")
224 api_method = f"projects/{project_id}/storage"
225 all_volumes = packet_conn.call_api(api_method, "GET")["volumes"]
226 matching_volumes = [v for v in all_volumes if s(v)]
227
228 if target_state == "present":
229 if len(matching_volumes) == 0:
230 params = {
231 "description": get_or_fail(module.params, "description"),
232 "size": get_or_fail(module.params, "size"),
233 "plan": get_or_fail(module.params, "plan"),
234 "facility": get_or_fail(module.params, "facility"),
235 "locked": get_or_fail(module.params, "locked"),
236 "billing_cycle": get_or_fail(module.params, "billing_cycle"),
237 "snapshot_policies": module.params.get("snapshot_policy"),
238 }
239
240 new_volume_data = packet_conn.call_api(api_method, "POST", params)
241 return_dict["changed"] = True
242 for k in ["id", "name", "description"]:
243 return_dict[k] = new_volume_data[k]
244
245 else:
246 for k in ["id", "name", "description"]:
247 return_dict[k] = matching_volumes[0][k]
248
249 else:
250 if len(matching_volumes) > 1:
251 _msg = f"More than one volume matches in module call for absent state: {matching_volumes}"
252 module.fail_json(msg=_msg)
253
254 if len(matching_volumes) == 1:
255 volume = matching_volumes[0]
256 packet_conn.call_api(f"storage/{volume['id']}", "DELETE")
257 return_dict["changed"] = True
258 for k in ["id", "name", "description"]:
259 return_dict[k] = volume[k]
260
261 return return_dict
262
263
264 def main():
265 module = AnsibleModule(
266 argument_spec=dict(
267 id=dict(type="str"),
268 description=dict(type="str"),
269 name=dict(type="str"),
270 state=dict(choices=VOLUME_STATES, default="present"),
271 auth_token=dict(type="str", fallback=(env_fallback, [PACKET_API_TOKEN_ENV_VAR]), no_log=True),
272 project_id=dict(required=True),
273 plan=dict(choices=VOLUME_PLANS, default="storage_1"),
274 facility=dict(type="str"),
275 size=dict(type="int"),
276 locked=dict(type="bool", default=False),
277 snapshot_policy=dict(type="dict"),
278 billing_cycle=dict(type="str", choices=BILLING, default="hourly"),
279 ),
280 supports_check_mode=True,
281 required_one_of=[("name", "id", "description")],
282 mutually_exclusive=[
283 ("name", "id"),
284 ("id", "description"),
285 ("name", "description"),
286 ],
287 )
288
289 if not HAS_PACKET_SDK:
290 module.fail_json(msg="packet required for this module")
291
292 if not module.params.get("auth_token"):
293 _fail_msg = f"if Packet API token is not in environment variable {PACKET_API_TOKEN_ENV_VAR}, the auth_token parameter is required"
294 module.fail_json(msg=_fail_msg)
295
296 auth_token = module.params.get("auth_token")
297
298 packet_conn = packet.Manager(auth_token=auth_token)
299
300 state = module.params.get("state")
301
302 if state in VOLUME_STATES:
303 if module.check_mode:
304 module.exit_json(changed=False)
305
306 try:
307 module.exit_json(**act_on_volume(state, module, packet_conn))
308 except Exception as e:
309 module.fail_json(msg=f"failed to set volume state {state}: {e}")
310 else:
311 module.fail_json(msg=f"{state} is not a valid state for this module")
312
313
314 if __name__ == "__main__":
315 main()