Debian Codegraph @

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

raw
1 #!/usr/bin/python
2
3 # Copyright: (c) 2020, 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: load_balancer
12
13 short_description: Create and manage cloud Load Balancers on the Hetzner Cloud.
14
15 description:
16 - Create, update and manage cloud Load Balancers on the Hetzner Cloud.
17 - To manage the DNS pointer of a Load Balancer, use the M(hetzner.hcloud.rdns) module.
18
19 author:
20 - Lukas Kaemmerling (@LKaemmerling)
21 version_added: 0.1.0
22 options:
23 id:
24 description:
25 - The ID of the Hetzner Cloud Load Balancer to manage.
26 - Only required if no Load Balancer I(name) is given
27 type: int
28 name:
29 description:
30 - The Name of the Hetzner Cloud Load Balancer to manage.
31 - Only required if no Load Balancer I(id) is given or a Load Balancer does not exist.
32 type: str
33 load_balancer_type:
34 description:
35 - The Load Balancer Type of the Hetzner Cloud Load Balancer to manage.
36 - Required if Load Balancer does not exist.
37 type: str
38 algorithm:
39 description:
40 - Algorithm of the Load Balancer.
41 type: str
42 default: round_robin
43 choices: [round_robin, least_connections]
44 location:
45 description:
46 - Location of Load Balancer.
47 - Required if no I(network_zone) is given and Load Balancer does not exist.
48 type: str
49 network_zone:
50 description:
51 - Network Zone of Load Balancer.
52 - Required of no I(location) is given and Load Balancer does not exist.
53 type: str
54 labels:
55 description:
56 - User-defined labels (key-value pairs).
57 type: dict
58 disable_public_interface:
59 description:
60 - Disables the public interface.
61 type: bool
62 default: False
63 delete_protection:
64 description:
65 - Protect the Load Balancer for deletion.
66 type: bool
67 state:
68 description:
69 - State of the Load Balancer.
70 default: present
71 choices: [ absent, present ]
72 type: str
73 extends_documentation_fragment:
74 - hetzner.hcloud.hcloud
75 """
76
77 EXAMPLES = """
78 - name: Create a basic Load Balancer
79 hetzner.hcloud.load_balancer:
80 name: my-Load Balancer
81 load_balancer_type: lb11
82 algorithm: round_robin
83 location: fsn1
84 state: present
85
86 - name: Ensure the Load Balancer is absent (remove if needed)
87 hetzner.hcloud.load_balancer:
88 name: my-Load Balancer
89 state: absent
90 """
91
92 RETURN = """
93 hcloud_load_balancer:
94 description: The Load Balancer instance
95 returned: Always
96 type: dict
97 contains:
98 id:
99 description: Numeric identifier of the Load Balancer
100 returned: always
101 type: int
102 sample: 1937415
103 name:
104 description: Name of the Load Balancer
105 returned: always
106 type: str
107 sample: my-Load-Balancer
108 load_balancer_type:
109 description: Name of the Load Balancer type of the Load Balancer
110 returned: always
111 type: str
112 sample: lb11
113 algorithm:
114 description: Algorithm of the Load Balancer.
115 returned: always
116 type: str
117 choices: [round_robin, least_connections]
118 sample: round_robin
119 ipv4_address:
120 description: Public IPv4 address of the Load Balancer
121 returned: always
122 type: str
123 sample: 116.203.104.109
124 ipv6_address:
125 description: Public IPv6 address of the Load Balancer
126 returned: always
127 type: str
128 sample: 2a01:4f8:1c1c:c140::1
129 location:
130 description: Name of the location of the Load Balancer
131 returned: always
132 type: str
133 sample: fsn1
134 labels:
135 description: User-defined labels (key-value pairs)
136 returned: always
137 type: dict
138 delete_protection:
139 description: True if Load Balancer is protected for deletion
140 type: bool
141 returned: always
142 sample: false
143 disable_public_interface:
144 description: True if Load Balancer public interface is disabled
145 type: bool
146 returned: always
147 sample: false
148 """
149
150 from ansible.module_utils.basic import AnsibleModule
151
152 from ..module_utils._base import AnsibleHCloud
153 from ..module_utils._vendor.hcloud import HCloudException
154 from ..module_utils._vendor.hcloud.load_balancers import (
155 BoundLoadBalancer,
156 LoadBalancerAlgorithm,
157 )
158
159
160 class AnsibleHCloudLoadBalancer(AnsibleHCloud):
161 represent = "hcloud_load_balancer"
162
163 hcloud_load_balancer: BoundLoadBalancer | None = None
164
165 def _prepare_result(self):
166 return {
167 "id": self.hcloud_load_balancer.id,
168 "name": self.hcloud_load_balancer.name,
169 "ipv4_address": self.hcloud_load_balancer.public_net.ipv4.ip,
170 "ipv6_address": self.hcloud_load_balancer.public_net.ipv6.ip,
171 "private_ipv4_address": (
172 self.hcloud_load_balancer.private_net[0].ip if len(self.hcloud_load_balancer.private_net) else None
173 ),
174 "load_balancer_type": self.hcloud_load_balancer.load_balancer_type.name,
175 "algorithm": self.hcloud_load_balancer.algorithm.type,
176 "location": self.hcloud_load_balancer.location.name,
177 "labels": self.hcloud_load_balancer.labels,
178 "delete_protection": self.hcloud_load_balancer.protection["delete"],
179 "disable_public_interface": not self.hcloud_load_balancer.public_net.enabled,
180 }
181
182 def _get_load_balancer(self):
183 try:
184 if self.module.params.get("id") is not None:
185 self.hcloud_load_balancer = self.client.load_balancers.get_by_id(self.module.params.get("id"))
186 else:
187 self.hcloud_load_balancer = self.client.load_balancers.get_by_name(self.module.params.get("name"))
188 except HCloudException as exception:
189 self.fail_json_hcloud(exception)
190
191 def _create_load_balancer(self):
192 self.module.fail_on_missing_params(required_params=["name", "load_balancer_type"])
193 try:
194 params = {
195 "name": self.module.params.get("name"),
196 "algorithm": LoadBalancerAlgorithm(type=self.module.params.get("algorithm", "round_robin")),
197 "load_balancer_type": self.client.load_balancer_types.get_by_name(
198 self.module.params.get("load_balancer_type")
199 ),
200 "labels": self.module.params.get("labels"),
201 }
202
203 if self.module.params.get("location") is None and self.module.params.get("network_zone") is None:
204 self.module.fail_json(msg="one of the following is required: location, network_zone")
205 elif self.module.params.get("location") is not None and self.module.params.get("network_zone") is None:
206 params["location"] = self.client.locations.get_by_name(self.module.params.get("location"))
207 elif self.module.params.get("location") is None and self.module.params.get("network_zone") is not None:
208 params["network_zone"] = self.module.params.get("network_zone")
209
210 if not self.module.check_mode:
211 resp = self.client.load_balancers.create(**params)
212 resp.action.wait_until_finished()
213
214 delete_protection = self.module.params.get("delete_protection")
215 if delete_protection is not None:
216 self._get_load_balancer()
217 action = self.hcloud_load_balancer.change_protection(delete=delete_protection)
218 action.wait_until_finished()
219 except HCloudException as exception:
220 self.fail_json_hcloud(exception)
221 self._mark_as_changed()
222 self._get_load_balancer()
223
224 def _update_load_balancer(self):
225 try:
226 labels = self.module.params.get("labels")
227 if labels is not None and labels != self.hcloud_load_balancer.labels:
228 if not self.module.check_mode:
229 self.hcloud_load_balancer.update(labels=labels)
230 self._mark_as_changed()
231
232 delete_protection = self.module.params.get("delete_protection")
233 if delete_protection is not None and delete_protection != self.hcloud_load_balancer.protection["delete"]:
234 if not self.module.check_mode:
235 action = self.hcloud_load_balancer.change_protection(delete=delete_protection)
236 action.wait_until_finished()
237 self._mark_as_changed()
238 self._get_load_balancer()
239
240 disable_public_interface = self.module.params.get("disable_public_interface")
241 if disable_public_interface is not None and disable_public_interface != (
242 not self.hcloud_load_balancer.public_net.enabled
243 ):
244 if not self.module.check_mode:
245 if disable_public_interface is True:
246 action = self.hcloud_load_balancer.disable_public_interface()
247 action.wait_until_finished()
248 else:
249 action = self.hcloud_load_balancer.enable_public_interface()
250 action.wait_until_finished()
251 self._mark_as_changed()
252
253 load_balancer_type = self.module.params.get("load_balancer_type")
254 if (
255 load_balancer_type is not None
256 and self.hcloud_load_balancer.load_balancer_type.name != load_balancer_type
257 ):
258 new_load_balancer_type = self.client.load_balancer_types.get_by_name(load_balancer_type)
259 if not new_load_balancer_type:
260 self.module.fail_json(msg="unknown load balancer type")
261 if not self.module.check_mode:
262 action = self.hcloud_load_balancer.change_type(
263 load_balancer_type=new_load_balancer_type,
264 )
265 action.wait_until_finished()
266
267 self._mark_as_changed()
268
269 algorithm = self.module.params.get("algorithm")
270 if algorithm is not None and self.hcloud_load_balancer.algorithm.type != algorithm:
271 action = self.hcloud_load_balancer.change_algorithm(algorithm=LoadBalancerAlgorithm(type=algorithm))
272 action.wait_until_finished()
273 self._mark_as_changed()
274
275 self._get_load_balancer()
276 except HCloudException as exception:
277 self.fail_json_hcloud(exception)
278
279 def present_load_balancer(self):
280 self._get_load_balancer()
281 if self.hcloud_load_balancer is None:
282 self._create_load_balancer()
283 else:
284 self._update_load_balancer()
285
286 def delete_load_balancer(self):
287 try:
288 self._get_load_balancer()
289 if self.hcloud_load_balancer is not None:
290 if not self.module.check_mode:
291 self.client.load_balancers.delete(self.hcloud_load_balancer)
292 self._mark_as_changed()
293 self.hcloud_load_balancer = None
294 except HCloudException as exception:
295 self.fail_json_hcloud(exception)
296
297 @classmethod
298 def define_module(cls):
299 return AnsibleModule(
300 argument_spec=dict(
301 id={"type": "int"},
302 name={"type": "str"},
303 load_balancer_type={"type": "str"},
304 algorithm={"choices": ["round_robin", "least_connections"], "default": "round_robin"},
305 location={"type": "str"},
306 network_zone={"type": "str"},
307 labels={"type": "dict"},
308 delete_protection={"type": "bool"},
309 disable_public_interface={"type": "bool", "default": False},
310 state={
311 "choices": ["absent", "present"],
312 "default": "present",
313 },
314 **super().base_module_arguments(),
315 ),
316 required_one_of=[["id", "name"]],
317 mutually_exclusive=[["location", "network_zone"]],
318 supports_check_mode=True,
319 )
320
321
322 def main():
323 module = AnsibleHCloudLoadBalancer.define_module()
324
325 hcloud = AnsibleHCloudLoadBalancer(module)
326 state = module.params.get("state")
327 if state == "absent":
328 hcloud.delete_load_balancer()
329 elif state == "present":
330 hcloud.present_load_balancer()
331
332 module.exit_json(**hcloud.get_result())
333
334
335 if __name__ == "__main__":
336 main()