Debian Codegraph @

ansible_collections/hetzner/hcloud/plugins/modules/volume.py

raw
1 #!/usr/bin/python
2
3 # Copyright: (c) 2019, Hetzner Cloud GmbH <[email protected]>
4 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
5
6
7 from __future__ import annotations
8
9 DOCUMENTATION = """
10 ---
11 module: volume
12
13 short_description: Create and manage block Volume on the Hetzner Cloud.
14
15
16 description:
17 - Create, update and attach/detach block Volume on the Hetzner Cloud.
18
19 author:
20 - Christopher Schmitt (@cschmitt-hcloud)
21
22 options:
23 id:
24 description:
25 - The ID of the Hetzner Cloud Block Volume to manage.
26 - Only required if no volume I(name) is given
27 type: int
28 name:
29 description:
30 - The Name of the Hetzner Cloud Block Volume to manage.
31 - Only required if no volume I(id) is given or a volume does not exist.
32 type: str
33 size:
34 description:
35 - The size of the Block Volume in GB.
36 - Required if volume does not yet exists.
37 type: int
38 automount:
39 description:
40 - Automatically mount the Volume.
41 type: bool
42 default: False
43 format:
44 description:
45 - Automatically Format the volume on creation
46 - Can only be used in case the Volume does not exist.
47 type: str
48 choices: [xfs, ext4]
49 location:
50 description:
51 - Location of the Hetzner Cloud Volume.
52 - Required if no I(server) is given and Volume does not exist.
53 type: str
54 server:
55 description:
56 - Server Name the Volume should be assigned to.
57 - Required if no I(location) is given and Volume does not exist.
58 type: str
59 delete_protection:
60 description:
61 - Protect the Volume for deletion.
62 type: bool
63 labels:
64 description:
65 - User-defined key-value pairs.
66 type: dict
67 state:
68 description:
69 - State of the Volume.
70 default: present
71 choices: [absent, present]
72 type: str
73 extends_documentation_fragment:
74 - hetzner.hcloud.hcloud
75
76 """
77
78 EXAMPLES = """
79 - name: Create a Volume
80 hetzner.hcloud.volume:
81 name: my-volume
82 location: fsn1
83 size: 100
84 state: present
85 - name: Create a Volume and format it with ext4
86 hetzner.hcloud.volume:
87 name: my-volume
88 location: fsn
89 format: ext4
90 size: 100
91 state: present
92 - name: Mount a existing Volume and automount
93 hetzner.hcloud.volume:
94 name: my-volume
95 server: my-server
96 automount: true
97 state: present
98 - name: Mount a existing Volume and automount
99 hetzner.hcloud.volume:
100 name: my-volume
101 server: my-server
102 automount: true
103 state: present
104 - name: Ensure the Volume is absent (remove if needed)
105 hetzner.hcloud.volume:
106 name: my-volume
107 state: absent
108 """
109
110 RETURN = """
111 hcloud_volume:
112 description: The block Volume
113 returned: Always
114 type: dict
115 contains:
116 id:
117 description: ID of the Volume
118 type: int
119 returned: Always
120 sample: 12345
121 name:
122 description: Name of the Volume
123 type: str
124 returned: Always
125 sample: my-volume
126 size:
127 description: Size in GB of the Volume
128 type: int
129 returned: Always
130 sample: 1337
131 linux_device:
132 description: Path to the device that contains the Volume.
133 returned: always
134 type: str
135 sample: /dev/disk/by-id/scsi-0HC_Volume_12345
136 version_added: "0.1.0"
137 location:
138 description: Location name where the Volume is located at
139 type: str
140 returned: Always
141 sample: "fsn1"
142 labels:
143 description: User-defined labels (key-value pairs)
144 type: dict
145 returned: Always
146 sample:
147 key: value
148 mylabel: 123
149 server:
150 description: Server name where the Volume is attached to
151 type: str
152 returned: Always
153 sample: "my-server"
154 delete_protection:
155 description: True if Volume is protected for deletion
156 type: bool
157 returned: always
158 sample: false
159 version_added: "0.1.0"
160 """
161
162 from ansible.module_utils.basic import AnsibleModule
163
164 from ..module_utils._base import AnsibleHCloud
165 from ..module_utils._vendor.hcloud import HCloudException
166 from ..module_utils._vendor.hcloud.volumes import BoundVolume
167
168
169 class AnsibleHCloudVolume(AnsibleHCloud):
170 represent = "hcloud_volume"
171
172 hcloud_volume: BoundVolume | None = None
173
174 def _prepare_result(self):
175 return {
176 "id": self.hcloud_volume.id,
177 "name": self.hcloud_volume.name,
178 "size": self.hcloud_volume.size,
179 "location": self.hcloud_volume.location.name,
180 "labels": self.hcloud_volume.labels,
181 "server": self.hcloud_volume.server.name if self.hcloud_volume.server is not None else None,
182 "linux_device": self.hcloud_volume.linux_device,
183 "delete_protection": self.hcloud_volume.protection["delete"],
184 }
185
186 def _get_volume(self):
187 try:
188 if self.module.params.get("id") is not None:
189 self.hcloud_volume = self.client.volumes.get_by_id(self.module.params.get("id"))
190 else:
191 self.hcloud_volume = self.client.volumes.get_by_name(self.module.params.get("name"))
192 except HCloudException as exception:
193 self.fail_json_hcloud(exception)
194
195 def _create_volume(self):
196 self.module.fail_on_missing_params(required_params=["name", "size"])
197 params = {
198 "name": self.module.params.get("name"),
199 "size": self.module.params.get("size"),
200 "automount": self.module.params.get("automount"),
201 "format": self.module.params.get("format"),
202 "labels": self.module.params.get("labels"),
203 }
204 if self.module.params.get("server") is not None:
205 params["server"] = self.client.servers.get_by_name(self.module.params.get("server"))
206 elif self.module.params.get("location") is not None:
207 params["location"] = self.client.locations.get_by_name(self.module.params.get("location"))
208 else:
209 self.module.fail_json(msg="server or location is required")
210
211 if not self.module.check_mode:
212 try:
213 resp = self.client.volumes.create(**params)
214 resp.action.wait_until_finished()
215 [action.wait_until_finished() for action in resp.next_actions]
216 delete_protection = self.module.params.get("delete_protection")
217 if delete_protection is not None:
218 self._get_volume()
219 action = self.hcloud_volume.change_protection(delete=delete_protection)
220 action.wait_until_finished()
221 except HCloudException as exception:
222 self.fail_json_hcloud(exception)
223 self._mark_as_changed()
224 self._get_volume()
225
226 def _update_volume(self):
227 try:
228 size = self.module.params.get("size")
229 if size:
230 if self.hcloud_volume.size < size:
231 if not self.module.check_mode:
232 action = self.hcloud_volume.resize(size)
233 action.wait_until_finished()
234 self._mark_as_changed()
235 elif self.hcloud_volume.size > size:
236 self.module.warn("Shrinking of volumes is not supported")
237
238 server_name = self.module.params.get("server")
239 if server_name:
240 server = self.client.servers.get_by_name(server_name)
241 if self.hcloud_volume.server is None or self.hcloud_volume.server.name != server.name:
242 if not self.module.check_mode:
243 automount = self.module.params.get("automount", False)
244 action = self.hcloud_volume.attach(server, automount=automount)
245 action.wait_until_finished()
246 self._mark_as_changed()
247
248 update_params = {}
249
250 name = self.module.params.get("name")
251 if name is not None and name != self.hcloud_volume.name:
252 self.module.fail_on_missing_params(required_params=["id"])
253 update_params["name"] = name
254
255 labels = self.module.params.get("labels")
256 if labels is not None and labels != self.hcloud_volume.labels:
257 update_params["labels"] = labels
258
259 if update_params:
260 if not self.module.check_mode:
261 self.hcloud_volume.update(**update_params)
262 self._mark_as_changed()
263
264 delete_protection = self.module.params.get("delete_protection")
265 if delete_protection is not None and delete_protection != self.hcloud_volume.protection["delete"]:
266 if not self.module.check_mode:
267 action = self.hcloud_volume.change_protection(delete=delete_protection)
268 action.wait_until_finished()
269 self._mark_as_changed()
270
271 self._get_volume()
272 except HCloudException as exception:
273 self.fail_json_hcloud(exception)
274
275 def present_volume(self):
276 self._get_volume()
277 if self.hcloud_volume is None:
278 self._create_volume()
279 else:
280 self._update_volume()
281
282 def delete_volume(self):
283 try:
284 self._get_volume()
285 if self.hcloud_volume is not None:
286 if not self.module.check_mode:
287 if self.hcloud_volume.server is not None:
288 action = self.hcloud_volume.detach()
289 action.wait_until_finished()
290 self.client.volumes.delete(self.hcloud_volume)
291 self._mark_as_changed()
292 self.hcloud_volume = None
293 except HCloudException as exception:
294 self.fail_json_hcloud(exception)
295
296 @classmethod
297 def define_module(cls):
298 return AnsibleModule(
299 argument_spec=dict(
300 id={"type": "int"},
301 name={"type": "str"},
302 size={"type": "int"},
303 location={"type": "str"},
304 server={"type": "str"},
305 labels={"type": "dict"},
306 automount={"type": "bool", "default": False},
307 format={"type": "str", "choices": ["xfs", "ext4"]},
308 delete_protection={"type": "bool"},
309 state={
310 "choices": ["absent", "present"],
311 "default": "present",
312 },
313 **super().base_module_arguments(),
314 ),
315 required_one_of=[["id", "name"]],
316 mutually_exclusive=[["location", "server"]],
317 supports_check_mode=True,
318 )
319
320
321 def main():
322 module = AnsibleHCloudVolume.define_module()
323
324 hcloud = AnsibleHCloudVolume(module)
325 state = module.params.get("state")
326 if state == "absent":
327 module.fail_on_missing_params(required_params=["name"])
328 hcloud.delete_volume()
329 else:
330 hcloud.present_volume()
331
332 module.exit_json(**hcloud.get_result())
333
334
335 if __name__ == "__main__":
336 main()