Debian Codegraph @

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

raw
1 #!/usr/bin/python
2 #
3 # Copyright (C) 2019 Huawei
4 # GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
5 # SPDX-License-Identifier: GPL-3.0-or-later
6
7 from __future__ import annotations
8
9 ###############################################################################
10 # Documentation
11 ###############################################################################
12
13 DOCUMENTATION = r"""
14 module: hwc_vpc_security_group_rule
15 description:
16 - VPC security group management.
17 short_description: Creates a resource of VPC/SecurityGroupRule in Huawei Cloud
18 notes:
19 - If O(id) option is provided, it takes precedence over O(security_group_id) for security group rule selection.
20 - O(security_group_id) is used for security group rule selection. If more than one security group rule with this options
21 exists, execution is aborted.
22 - No parameter support updating. If one of option is changed, the module creates a new resource.
23 version_added: '0.2.0'
24 author: Huawei Inc. (@huaweicloud)
25 requirements:
26 - keystoneauth1 >= 3.6.0
27 attributes:
28 check_mode:
29 support: full
30 diff_mode:
31 support: none
32 options:
33 state:
34 description:
35 - Whether the given object should exist in Huawei Cloud.
36 type: str
37 choices: ['present', 'absent']
38 default: 'present'
39 direction:
40 description:
41 - Specifies the direction of access control. The value can be egress or ingress.
42 type: str
43 required: true
44 security_group_id:
45 description:
46 - Specifies the security group rule ID, which uniquely identifies the security group rule.
47 type: str
48 required: true
49 description:
50 description:
51 - Provides supplementary information about the security group rule. The value is a string of no more than 255 characters
52 that can contain letters and digits.
53 type: str
54 ethertype:
55 description:
56 - Specifies the IP protocol version. The value can be IPv4 or IPv6. If you do not set this parameter, IPv4 is used by
57 default.
58 type: str
59 port_range_max:
60 description:
61 - Specifies the end port number. The value ranges from 1 to 65535. If the protocol is not icmp, the value cannot be
62 smaller than the port_range_min value. An empty value indicates all ports.
63 type: int
64 port_range_min:
65 description:
66 - Specifies the start port number. The value ranges from 1 to 65535. The value cannot be greater than the port_range_max
67 value. An empty value indicates all ports.
68 type: int
69 protocol:
70 description:
71 - Specifies the protocol type. The value can be icmp, tcp, or udp. If the parameter is left blank, the security group
72 supports all protocols.
73 type: str
74 remote_group_id:
75 description:
76 - Specifies the ID of the peer security group. The value is exclusive with parameter remote_ip_prefix.
77 type: str
78 remote_ip_prefix:
79 description:
80 - Specifies the remote IP address. If the access control direction is set to egress, the parameter specifies the source
81 IP address. If the access control direction is set to ingress, the parameter specifies the destination IP address.
82 The value can be in the CIDR format or IP addresses. The parameter is exclusive with parameter remote_group_id.
83 type: str
84 extends_documentation_fragment:
85 - community.general._hwc
86 - community.general._attributes
87 """
88
89 EXAMPLES = r"""
90 # create a security group rule
91 - name: Create a security group
92 hwc_vpc_security_group:
93 name: "ansible_network_security_group_test"
94 register: sg
95 - name: Create a security group rule
96 community.general.hwc_vpc_security_group_rule:
97 direction: "ingress"
98 protocol: "tcp"
99 ethertype: "IPv4"
100 port_range_max: 22
101 security_group_id: "{{ sg.id }}"
102 port_range_min: 22
103 remote_ip_prefix: "0.0.0.0/0"
104 """
105
106 RETURN = r"""
107 direction:
108 description:
109 - Specifies the direction of access control. The value can be egress or ingress.
110 type: str
111 returned: success
112 security_group_id:
113 description:
114 - Specifies the security group rule ID, which uniquely identifies the security group rule.
115 type: str
116 returned: success
117 description:
118 description:
119 - Provides supplementary information about the security group rule. The value is a string of no more than 255 characters
120 that can contain letters and digits.
121 type: str
122 returned: success
123 ethertype:
124 description:
125 - Specifies the IP protocol version. The value can be IPv4 or IPv6. If you do not set this parameter, IPv4 is used by
126 default.
127 type: str
128 returned: success
129 port_range_max:
130 description:
131 - Specifies the end port number. The value ranges from 1 to 65535. If the protocol is not icmp, the value cannot be smaller
132 than the port_range_min value. An empty value indicates all ports.
133 type: int
134 returned: success
135 port_range_min:
136 description:
137 - Specifies the start port number. The value ranges from 1 to 65535. The value cannot be greater than the port_range_max
138 value. An empty value indicates all ports.
139 type: int
140 returned: success
141 protocol:
142 description:
143 - Specifies the protocol type. The value can be icmp, tcp, or udp. If the parameter is left blank, the security group
144 supports all protocols.
145 type: str
146 returned: success
147 remote_group_id:
148 description:
149 - Specifies the ID of the peer security group. The value is exclusive with parameter remote_ip_prefix.
150 type: str
151 returned: success
152 remote_ip_prefix:
153 description:
154 - Specifies the remote IP address. If the access control direction is set to egress, the parameter specifies the source
155 IP address. If the access control direction is set to ingress, the parameter specifies the destination IP address. The
156 value can be in the CIDR format or IP addresses. The parameter is exclusive with parameter remote_group_id.
157 type: str
158 returned: success
159 """
160
161 from ansible_collections.community.general.plugins.module_utils._hwc_utils import (
162 Config,
163 HwcClientException,
164 HwcModule,
165 are_different_dicts,
166 build_path,
167 get_region,
168 is_empty_value,
169 navigate_value,
170 )
171
172
173 def build_module():
174 return HwcModule(
175 argument_spec=dict(
176 state=dict(default="present", choices=["present", "absent"], type="str"),
177 direction=dict(type="str", required=True),
178 security_group_id=dict(type="str", required=True),
179 description=dict(type="str"),
180 ethertype=dict(type="str"),
181 port_range_max=dict(type="int"),
182 port_range_min=dict(type="int"),
183 protocol=dict(type="str"),
184 remote_group_id=dict(type="str"),
185 remote_ip_prefix=dict(type="str"),
186 ),
187 supports_check_mode=True,
188 )
189
190
191 def main():
192 """Main function"""
193
194 module = build_module()
195 config = Config(module, "vpc")
196
197 try:
198 resource = None
199 if module.params["id"]:
200 resource = True
201 else:
202 v = search_resource(config)
203 if len(v) > 1:
204 raise Exception(f"Found more than one resource({', '.join([navigate_value(i, ['id']) for i in v])})")
205
206 if len(v) == 1:
207 resource = v[0]
208 module.params["id"] = navigate_value(resource, ["id"])
209
210 result = {}
211 changed = False
212 if module.params["state"] == "present":
213 if resource is None:
214 if not module.check_mode:
215 create(config)
216 changed = True
217
218 current = read_resource(config, exclude_output=True)
219 expect = user_input_parameters(module)
220 if are_different_dicts(expect, current):
221 raise Exception(
222 f"Cannot change option from ({current}) to ({expect}) for an existing security group({module.params.get('id')})."
223 )
224 result = read_resource(config)
225 result["id"] = module.params.get("id")
226 else:
227 if resource:
228 if not module.check_mode:
229 delete(config)
230 changed = True
231
232 except Exception as ex:
233 module.fail_json(msg=str(ex))
234
235 else:
236 result["changed"] = changed
237 module.exit_json(**result)
238
239
240 def user_input_parameters(module):
241 return {
242 "description": module.params.get("description"),
243 "direction": module.params.get("direction"),
244 "ethertype": module.params.get("ethertype"),
245 "port_range_max": module.params.get("port_range_max"),
246 "port_range_min": module.params.get("port_range_min"),
247 "protocol": module.params.get("protocol"),
248 "remote_group_id": module.params.get("remote_group_id"),
249 "remote_ip_prefix": module.params.get("remote_ip_prefix"),
250 "security_group_id": module.params.get("security_group_id"),
251 }
252
253
254 def create(config):
255 module = config.module
256 client = config.client(get_region(module), "vpc", "project")
257 opts = user_input_parameters(module)
258
259 params = build_create_parameters(opts)
260 r = send_create_request(module, params, client)
261 module.params["id"] = navigate_value(r, ["security_group_rule", "id"])
262
263
264 def delete(config):
265 module = config.module
266 client = config.client(get_region(module), "vpc", "project")
267
268 send_delete_request(module, None, client)
269
270
271 def read_resource(config, exclude_output=False):
272 module = config.module
273 client = config.client(get_region(module), "vpc", "project")
274
275 res = {}
276
277 r = send_read_request(module, client)
278 res["read"] = fill_read_resp_body(r)
279
280 return update_properties(module, res, None, exclude_output)
281
282
283 def _build_query_link(opts):
284 query_link = "?marker={marker}&limit=10"
285 v = navigate_value(opts, ["security_group_id"])
286 if v:
287 query_link += f"&security_group_id={v}"
288
289 return query_link
290
291
292 def search_resource(config):
293 module = config.module
294 client = config.client(get_region(module), "vpc", "project")
295 opts = user_input_parameters(module)
296 identity_obj = _build_identity_object(opts)
297 query_link = _build_query_link(opts)
298 link = f"security-group-rules{query_link}"
299
300 result = []
301 p = {"marker": ""}
302 while True:
303 url = link.format(**p)
304 r = send_list_request(module, client, url)
305 if not r:
306 break
307
308 for item in r:
309 item = fill_list_resp_body(item)
310 if not are_different_dicts(identity_obj, item):
311 result.append(item)
312
313 if len(result) > 1:
314 break
315
316 p["marker"] = r[-1].get("id")
317
318 return result
319
320
321 def build_create_parameters(opts):
322 params = dict()
323
324 v = navigate_value(opts, ["description"], None)
325 if not is_empty_value(v):
326 params["description"] = v
327
328 v = navigate_value(opts, ["direction"], None)
329 if not is_empty_value(v):
330 params["direction"] = v
331
332 v = navigate_value(opts, ["ethertype"], None)
333 if not is_empty_value(v):
334 params["ethertype"] = v
335
336 v = navigate_value(opts, ["port_range_max"], None)
337 if not is_empty_value(v):
338 params["port_range_max"] = v
339
340 v = navigate_value(opts, ["port_range_min"], None)
341 if not is_empty_value(v):
342 params["port_range_min"] = v
343
344 v = navigate_value(opts, ["protocol"], None)
345 if not is_empty_value(v):
346 params["protocol"] = v
347
348 v = navigate_value(opts, ["remote_group_id"], None)
349 if not is_empty_value(v):
350 params["remote_group_id"] = v
351
352 v = navigate_value(opts, ["remote_ip_prefix"], None)
353 if not is_empty_value(v):
354 params["remote_ip_prefix"] = v
355
356 v = navigate_value(opts, ["security_group_id"], None)
357 if not is_empty_value(v):
358 params["security_group_id"] = v
359
360 if not params:
361 return params
362
363 params = {"security_group_rule": params}
364
365 return params
366
367
368 def send_create_request(module, params, client):
369 url = "security-group-rules"
370 try:
371 r = client.post(url, params)
372 except HwcClientException as ex:
373 msg = f"module(hwc_vpc_security_group_rule): error running api(create), error: {ex}"
374 module.fail_json(msg=msg)
375
376 return r
377
378
379 def send_delete_request(module, params, client):
380 url = build_path(module, "security-group-rules/{id}")
381
382 try:
383 r = client.delete(url, params)
384 except HwcClientException as ex:
385 msg = f"module(hwc_vpc_security_group_rule): error running api(delete), error: {ex}"
386 module.fail_json(msg=msg)
387
388 return r
389
390
391 def send_read_request(module, client):
392 url = build_path(module, "security-group-rules/{id}")
393
394 r = None
395 try:
396 r = client.get(url)
397 except HwcClientException as ex:
398 msg = f"module(hwc_vpc_security_group_rule): error running api(read), error: {ex}"
399 module.fail_json(msg=msg)
400
401 return navigate_value(r, ["security_group_rule"], None)
402
403
404 def fill_read_resp_body(body):
405 result = dict()
406
407 result["description"] = body.get("description")
408
409 result["direction"] = body.get("direction")
410
411 result["ethertype"] = body.get("ethertype")
412
413 result["id"] = body.get("id")
414
415 result["port_range_max"] = body.get("port_range_max")
416
417 result["port_range_min"] = body.get("port_range_min")
418
419 result["protocol"] = body.get("protocol")
420
421 result["remote_address_group_id"] = body.get("remote_address_group_id")
422
423 result["remote_group_id"] = body.get("remote_group_id")
424
425 result["remote_ip_prefix"] = body.get("remote_ip_prefix")
426
427 result["security_group_id"] = body.get("security_group_id")
428
429 return result
430
431
432 def update_properties(module, response, array_index, exclude_output=False):
433 r = user_input_parameters(module)
434
435 v = navigate_value(response, ["read", "description"], array_index)
436 r["description"] = v
437
438 v = navigate_value(response, ["read", "direction"], array_index)
439 r["direction"] = v
440
441 v = navigate_value(response, ["read", "ethertype"], array_index)
442 r["ethertype"] = v
443
444 v = navigate_value(response, ["read", "port_range_max"], array_index)
445 r["port_range_max"] = v
446
447 v = navigate_value(response, ["read", "port_range_min"], array_index)
448 r["port_range_min"] = v
449
450 v = navigate_value(response, ["read", "protocol"], array_index)
451 r["protocol"] = v
452
453 v = navigate_value(response, ["read", "remote_group_id"], array_index)
454 r["remote_group_id"] = v
455
456 v = navigate_value(response, ["read", "remote_ip_prefix"], array_index)
457 r["remote_ip_prefix"] = v
458
459 v = navigate_value(response, ["read", "security_group_id"], array_index)
460 r["security_group_id"] = v
461
462 return r
463
464
465 def send_list_request(module, client, url):
466 r = None
467 try:
468 r = client.get(url)
469 except HwcClientException as ex:
470 msg = f"module(hwc_vpc_security_group_rule): error running api(list), error: {ex}"
471 module.fail_json(msg=msg)
472
473 return navigate_value(r, ["security_group_rules"], None)
474
475
476 def _build_identity_object(all_opts):
477 result = dict()
478
479 v = navigate_value(all_opts, ["description"], None)
480 result["description"] = v
481
482 v = navigate_value(all_opts, ["direction"], None)
483 result["direction"] = v
484
485 v = navigate_value(all_opts, ["ethertype"], None)
486 result["ethertype"] = v
487
488 result["id"] = None
489
490 v = navigate_value(all_opts, ["port_range_max"], None)
491 result["port_range_max"] = v
492
493 v = navigate_value(all_opts, ["port_range_min"], None)
494 result["port_range_min"] = v
495
496 v = navigate_value(all_opts, ["protocol"], None)
497 result["protocol"] = v
498
499 result["remote_address_group_id"] = None
500
501 v = navigate_value(all_opts, ["remote_group_id"], None)
502 result["remote_group_id"] = v
503
504 v = navigate_value(all_opts, ["remote_ip_prefix"], None)
505 result["remote_ip_prefix"] = v
506
507 v = navigate_value(all_opts, ["security_group_id"], None)
508 result["security_group_id"] = v
509
510 return result
511
512
513 def fill_list_resp_body(body):
514 result = dict()
515
516 result["description"] = body.get("description")
517
518 result["direction"] = body.get("direction")
519
520 result["ethertype"] = body.get("ethertype")
521
522 result["id"] = body.get("id")
523
524 result["port_range_max"] = body.get("port_range_max")
525
526 result["port_range_min"] = body.get("port_range_min")
527
528 result["protocol"] = body.get("protocol")
529
530 result["remote_address_group_id"] = body.get("remote_address_group_id")
531
532 result["remote_group_id"] = body.get("remote_group_id")
533
534 result["remote_ip_prefix"] = body.get("remote_ip_prefix")
535
536 result["security_group_id"] = body.get("security_group_id")
537
538 return result
539
540
541 if __name__ == "__main__":
542 main()