Debian Codegraph @

ansible_collections/hetzner/hcloud/plugins/modules/floating_ip.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: floating_ip
12
13 short_description: Create and manage cloud Floating IPs on the Hetzner Cloud.
14
15
16 description:
17 - Create, update and manage cloud Floating IPs on the Hetzner Cloud.
18 - To manage the DNS pointer of a Floating IP, use the M(hetzner.hcloud.rdns) module.
19
20 author:
21 - Lukas Kaemmerling (@lkaemmerling)
22 version_added: 0.1.0
23 options:
24 id:
25 description:
26 - The ID of the Hetzner Cloud Floating IPs to manage.
27 - Only required if no Floating IP I(name) is given.
28 type: int
29 name:
30 description:
31 - The Name of the Hetzner Cloud Floating IPs to manage.
32 - Only required if no Floating IP I(id) is given or a Floating IP does not exist.
33 type: str
34 description:
35 description:
36 - The Description of the Hetzner Cloud Floating IPs.
37 type: str
38 home_location:
39 description:
40 - Home Location of the Hetzner Cloud Floating IP.
41 - Required if no I(server) is given and Floating IP does not exist.
42 type: str
43 server:
44 description:
45 - Server Name the Floating IP should be assigned to.
46 - Required if no I(home_location) is given and Floating IP does not exist.
47 type: str
48 type:
49 description:
50 - Type of the Floating IP.
51 - Required if Floating IP does not exist
52 choices: [ ipv4, ipv6 ]
53 type: str
54 force:
55 description:
56 - Force the assignment or deletion of the Floating IP.
57 type: bool
58 delete_protection:
59 description:
60 - Protect the Floating IP for deletion.
61 type: bool
62 labels:
63 description:
64 - User-defined labels (key-value pairs).
65 type: dict
66 state:
67 description:
68 - State of the Floating IP.
69 default: present
70 choices: [ absent, present ]
71 type: str
72
73 extends_documentation_fragment:
74 - hetzner.hcloud.hcloud
75 """
76
77 EXAMPLES = """
78 - name: Create a basic IPv4 Floating IP
79 hetzner.hcloud.floating_ip:
80 name: my-floating-ip
81 home_location: fsn1
82 type: ipv4
83 state: present
84 - name: Create a basic IPv6 Floating IP
85 hetzner.hcloud.floating_ip:
86 name: my-floating-ip
87 home_location: fsn1
88 type: ipv6
89 state: present
90 - name: Assign a Floating IP to a server
91 hetzner.hcloud.floating_ip:
92 name: my-floating-ip
93 server: 1234
94 state: present
95 - name: Assign a Floating IP to another server
96 hetzner.hcloud.floating_ip:
97 name: my-floating-ip
98 server: 1234
99 force: true
100 state: present
101 - name: Floating IP should be absent
102 hetzner.hcloud.floating_ip:
103 name: my-floating-ip
104 state: absent
105 """
106
107 RETURN = """
108 hcloud_floating_ip:
109 description: The Floating IP instance
110 returned: Always
111 type: dict
112 contains:
113 id:
114 description: ID of the Floating IP
115 type: int
116 returned: Always
117 sample: 12345
118 name:
119 description: Name of the Floating IP
120 type: str
121 returned: Always
122 sample: my-floating-ip
123 description:
124 description: Description of the Floating IP
125 type: str
126 returned: Always
127 sample: my-floating-ip
128 ip:
129 description: IP Address of the Floating IP
130 type: str
131 returned: Always
132 sample: 116.203.104.109
133 type:
134 description: Type of the Floating IP
135 type: str
136 returned: Always
137 sample: ipv4
138 home_location:
139 description: Name of the home location of the Floating IP
140 type: str
141 returned: Always
142 sample: fsn1
143 server:
144 description: Name of the server the Floating IP is assigned to.
145 type: str
146 returned: Always
147 sample: "my-server"
148 delete_protection:
149 description: True if Floating IP is protected for deletion
150 type: bool
151 returned: always
152 sample: false
153 version_added: "0.1.0"
154 labels:
155 description: User-defined labels (key-value pairs)
156 type: dict
157 returned: Always
158 sample:
159 key: value
160 mylabel: 123
161 """
162
163 from ..module_utils import _floating_ip
164 from ..module_utils._base import AnsibleHCloud, AnsibleModule
165 from ..module_utils._vendor.hcloud import HCloudException
166 from ..module_utils._vendor.hcloud.floating_ips import BoundFloatingIP
167
168
169 class AnsibleFloatingIP(AnsibleHCloud):
170 represent = "floating_ip"
171
172 floating_ip: BoundFloatingIP | None = None
173
174 def _prepare_result(self):
175 if self.floating_ip is None:
176 return {}
177 return _floating_ip.prepare_result(self.floating_ip)
178
179 def _get(self):
180 if (value := self.module.params.get("id")) is not None:
181 self.floating_ip = self.client.floating_ips.get_by_id(value)
182 elif (value := self.module.params.get("name")) is not None:
183 self.floating_ip = self.client.floating_ips.get_by_name(value)
184
185 def _create(self):
186 self.fail_on_invalid_params(
187 required=["name", "type"],
188 required_one_of=[["home_location", "server"]],
189 )
190
191 params = {
192 "name": self.module.params.get("name"),
193 "type": self.module.params.get("type"),
194 }
195
196 if (value := self.module.params.get("home_location")) is not None:
197 params["home_location"] = self.client.locations.get_by_name(value)
198 elif (value := self.module.params.get("server")) is not None:
199 params["server"] = self.client.servers.get_by_name(value)
200 else:
201 self.module.fail_json(msg="one of the following is required: home_location, server")
202
203 if (value := self.module.params.get("description")) is not None:
204 params["description"] = value
205
206 if (value := self.module.params.get("labels")) is not None:
207 params["labels"] = value
208
209 if not self.module.check_mode:
210 resp = self.client.floating_ips.create(**params)
211 self.floating_ip = resp.floating_ip
212 if resp.action is not None:
213 resp.action.wait_until_finished()
214 self._mark_as_changed()
215
216 if (value := self.module.params.get("delete_protection")) is not None:
217 if not self.module.check_mode:
218 action = self.floating_ip.change_protection(delete=value)
219 action.wait_until_finished()
220 self._mark_as_changed()
221
222 if not self.module.check_mode:
223 self.floating_ip.reload()
224
225 def _update(self):
226 need_reload = False
227
228 if (value := self.module.params.get("delete_protection")) is not None:
229 if value != self.floating_ip.protection["delete"]:
230 if not self.module.check_mode:
231 action = self.floating_ip.change_protection(delete=value)
232 action.wait_until_finished()
233 need_reload = True
234 self._mark_as_changed()
235
236 if (value := self.module.params.get("server")) is not None:
237 if self.floating_ip.server is not None:
238 if value != self.floating_ip.server.name:
239 if self.module.params.get("force"):
240 if not self.module.check_mode:
241 action = self.floating_ip.assign(self.client.servers.get_by_name(value))
242 action.wait_until_finished()
243 need_reload = True
244 self._mark_as_changed()
245 else:
246 self.module.warn(
247 "Floating IP is already assigned to another server "
248 f"{self.floating_ip.server.name}. You need to "
249 "unassign the Floating IP or use force=true."
250 )
251
252 else: # self.floating_ip.server is None
253 if not self.module.check_mode:
254 action = self.floating_ip.assign(self.client.servers.get_by_name(value))
255 action.wait_until_finished()
256 need_reload = True
257 self._mark_as_changed()
258
259 else: # value is None
260 if self.floating_ip.server is not None:
261 if not self.module.check_mode:
262 action = self.floating_ip.unassign()
263 action.wait_until_finished()
264 need_reload = True
265 self._mark_as_changed()
266
267 params = {}
268
269 if (value := self.module.params.get("labels")) is not None:
270 if value != self.floating_ip.labels:
271 params["labels"] = value
272 self._mark_as_changed()
273
274 if (value := self.module.params.get("description")) is not None:
275 if value != self.floating_ip.description:
276 params["description"] = value
277 self._mark_as_changed()
278
279 if params or need_reload:
280 if not self.module.check_mode:
281 self.floating_ip = self.floating_ip.update(**params)
282
283 def _delete(self):
284 if self.floating_ip.server is not None:
285 if self.module.params.get("force"):
286 if not self.module.check_mode:
287 action = self.floating_ip.unassign()
288 action.wait_until_finished()
289
290 self.floating_ip.delete()
291 self._mark_as_changed()
292 else:
293 self.module.warn(
294 "Floating IP is currently assigned to server "
295 f"{self.floating_ip.server.name}. You need to "
296 "unassign the Floating IP or use force=true."
297 )
298 else:
299 if not self.module.check_mode:
300 self.floating_ip.delete()
301 self._mark_as_changed()
302
303 self.floating_ip = None
304
305 def present(self):
306 try:
307 self._get()
308 if self.floating_ip is None:
309 self._create()
310 else:
311 self._update()
312 except HCloudException as exception:
313 self.fail_json_hcloud(exception)
314
315 def delete(self):
316 try:
317 self._get()
318 if self.floating_ip is not None:
319 self._delete()
320 except HCloudException as exception:
321 self.fail_json_hcloud(exception)
322
323 @classmethod
324 def define_module(cls):
325 return AnsibleModule(
326 argument_spec=dict(
327 id={"type": "int"},
328 name={"type": "str"},
329 description={"type": "str"},
330 server={"type": "str"},
331 home_location={"type": "str"},
332 force={"type": "bool"},
333 type={"choices": ["ipv4", "ipv6"]},
334 labels={"type": "dict"},
335 delete_protection={"type": "bool"},
336 state={
337 "choices": ["absent", "present"],
338 "default": "present",
339 },
340 **super().base_module_arguments(),
341 ),
342 required_one_of=[["id", "name"]],
343 mutually_exclusive=[["home_location", "server"]],
344 supports_check_mode=True,
345 )
346
347
348 def main():
349 o = AnsibleFloatingIP(AnsibleFloatingIP.define_module())
350
351 match o.module.params["state"]:
352 case "absent":
353 o.delete()
354 case "present":
355 o.present()
356
357 result = o.get_result()
358 result["hcloud_floating_ip"] = result.pop(o.represent)
359
360 o.module.exit_json(**result)
361
362
363 if __name__ == "__main__":
364 main()