Debian Codegraph @

ansible_collections/community/general/plugins/modules/hwc_vpc_route.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_route
15 description:
16 - VPC route management.
17 short_description: Creates a resource of VPC/Route in Huawei Cloud
18 notes:
19 - If O(id) option is provided, it takes precedence over O(destination), O(vpc_id), O(type), and O(next_hop) for route selection.
20 - O(destination), O(vpc_id), O(type) and O(next_hop) are used for route selection. If more than one route 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 destination:
40 description:
41 - Specifies the destination IP address or CIDR block.
42 type: str
43 required: true
44 next_hop:
45 description:
46 - Specifies the next hop. The value is VPC peering connection ID.
47 type: str
48 required: true
49 vpc_id:
50 description:
51 - Specifies the VPC ID to which route is added.
52 type: str
53 required: true
54 type:
55 description:
56 - Specifies the type of route.
57 type: str
58 default: 'peering'
59 extends_documentation_fragment:
60 - community.general._hwc
61 - community.general._attributes
62 """
63
64 EXAMPLES = r"""
65 # create a peering connect
66 - name: Create a local vpc
67 hwc_network_vpc:
68 cidr: "192.168.0.0/16"
69 name: "ansible_network_vpc_test_local"
70 register: vpc1
71 - name: Create a peering vpc
72 hwc_network_vpc:
73 cidr: "192.168.0.0/16"
74 name: "ansible_network_vpc_test_peering"
75 register: vpc2
76 - name: Create a peering connect
77 hwc_vpc_peering_connect:
78 local_vpc_id: "{{ vpc1.id }}"
79 name: "ansible_network_peering_test"
80 filters:
81 - "name"
82 peering_vpc:
83 vpc_id: "{{ vpc2.id }}"
84 register: connect
85 - name: Create a route
86 community.general.hwc_vpc_route:
87 vpc_id: "{{ vpc1.id }}"
88 destination: "192.168.0.0/16"
89 next_hop: "{{ connect.id }}"
90 """
91
92 RETURN = r"""
93 id:
94 description:
95 - UUID of the route.
96 type: str
97 returned: success
98 destination:
99 description:
100 - Specifies the destination IP address or CIDR block.
101 type: str
102 returned: success
103 next_hop:
104 description:
105 - Specifies the next hop. The value is VPC peering connection ID.
106 type: str
107 returned: success
108 vpc_id:
109 description:
110 - Specifies the VPC ID to which route is added.
111 type: str
112 returned: success
113 type:
114 description:
115 - Specifies the type of route.
116 type: str
117 returned: success
118 """
119
120 from ansible_collections.community.general.plugins.module_utils._hwc_utils import (
121 Config,
122 HwcClientException,
123 HwcModule,
124 are_different_dicts,
125 build_path,
126 get_region,
127 is_empty_value,
128 navigate_value,
129 )
130
131
132 def build_module():
133 return HwcModule(
134 argument_spec=dict(
135 state=dict(default="present", choices=["present", "absent"], type="str"),
136 destination=dict(type="str", required=True),
137 next_hop=dict(type="str", required=True),
138 vpc_id=dict(type="str", required=True),
139 type=dict(type="str", default="peering"),
140 id=dict(type="str"),
141 ),
142 supports_check_mode=True,
143 )
144
145
146 def main():
147 """Main function"""
148
149 module = build_module()
150 config = Config(module, "vpc")
151
152 try:
153 resource = None
154 if module.params.get("id"):
155 resource = get_resource_by_id(config)
156 if module.params["state"] == "present":
157 opts = user_input_parameters(module)
158 if are_different_dicts(resource, opts):
159 raise Exception(
160 f"Cannot change option from ({resource}) to ({opts}) for an existing route.({config.module.params['id']})"
161 )
162 else:
163 v = search_resource(config)
164 if len(v) > 1:
165 raise Exception(f"Found more than one resource({', '.join([navigate_value(i, ['id']) for i in v])})")
166
167 if len(v) == 1:
168 resource = update_properties(module, {"read": v[0]}, None)
169 module.params["id"] = navigate_value(resource, ["id"])
170
171 result = {}
172 changed = False
173 if module.params["state"] == "present":
174 if resource is None:
175 if not module.check_mode:
176 resource = create(config)
177 changed = True
178
179 result = resource
180 else:
181 if resource:
182 if not module.check_mode:
183 delete(config)
184 changed = True
185
186 except Exception as ex:
187 module.fail_json(msg=str(ex))
188
189 else:
190 result["changed"] = changed
191 module.exit_json(**result)
192
193
194 def user_input_parameters(module):
195 return {
196 "destination": module.params.get("destination"),
197 "next_hop": module.params.get("next_hop"),
198 "type": module.params.get("type"),
199 "vpc_id": module.params.get("vpc_id"),
200 "id": module.params.get("id"),
201 }
202
203
204 def create(config):
205 module = config.module
206 client = config.client(get_region(module), "network", "project")
207 opts = user_input_parameters(module)
208
209 params = build_create_parameters(opts)
210 r = send_create_request(module, params, client)
211 module.params["id"] = navigate_value(r, ["route", "id"])
212
213 result = update_properties(module, {"read": fill_resp_body(r)}, None)
214 return result
215
216
217 def delete(config):
218 module = config.module
219 client = config.client(get_region(module), "network", "project")
220
221 send_delete_request(module, None, client)
222
223
224 def get_resource_by_id(config, exclude_output=False):
225 module = config.module
226 client = config.client(get_region(module), "network", "project")
227
228 res = {}
229
230 r = send_read_request(module, client)
231 res["read"] = fill_resp_body(r)
232
233 result = update_properties(module, res, None, exclude_output)
234 return result
235
236
237 def _build_query_link(opts):
238 query_params = []
239
240 v = navigate_value(opts, ["type"])
241 if v:
242 query_params.append(f"type={v}")
243
244 v = navigate_value(opts, ["destination"])
245 if v:
246 query_params.append(f"destination={v}")
247
248 v = navigate_value(opts, ["vpc_id"])
249 if v:
250 query_params.append(f"vpc_id={v}")
251
252 query_link = "?marker={marker}&limit=10"
253 if query_params:
254 query_link += f"&{'&'.join(query_params)}"
255
256 return query_link
257
258
259 def search_resource(config):
260 module = config.module
261 client = config.client(get_region(module), "network", "project")
262 opts = user_input_parameters(module)
263 identity_obj = _build_identity_object(opts)
264 query_link = _build_query_link(opts)
265 link = f"v2.0/vpc/routes{query_link}"
266
267 result = []
268 p = {"marker": ""}
269 while True:
270 url = link.format(**p)
271 r = send_list_request(module, client, url)
272 if not r:
273 break
274
275 for item in r:
276 item = fill_list_resp_body(item)
277 if not are_different_dicts(identity_obj, item):
278 result.append(item)
279
280 if len(result) > 1:
281 break
282
283 p["marker"] = r[-1].get("id")
284
285 return result
286
287
288 def build_create_parameters(opts):
289 params = dict()
290
291 v = navigate_value(opts, ["destination"], None)
292 if not is_empty_value(v):
293 params["destination"] = v
294
295 v = navigate_value(opts, ["next_hop"], None)
296 if not is_empty_value(v):
297 params["nexthop"] = v
298
299 v = navigate_value(opts, ["type"], None)
300 if not is_empty_value(v):
301 params["type"] = v
302
303 v = navigate_value(opts, ["vpc_id"], None)
304 if not is_empty_value(v):
305 params["vpc_id"] = v
306
307 if not params:
308 return params
309
310 params = {"route": params}
311
312 return params
313
314
315 def send_create_request(module, params, client):
316 url = "v2.0/vpc/routes"
317 try:
318 r = client.post(url, params)
319 except HwcClientException as ex:
320 msg = f"module(hwc_vpc_route): error running api(create), error: {ex}"
321 module.fail_json(msg=msg)
322
323 return r
324
325
326 def send_delete_request(module, params, client):
327 url = build_path(module, "v2.0/vpc/routes/{id}")
328
329 try:
330 r = client.delete(url, params)
331 except HwcClientException as ex:
332 msg = f"module(hwc_vpc_route): error running api(delete), error: {ex}"
333 module.fail_json(msg=msg)
334
335 return r
336
337
338 def send_read_request(module, client):
339 url = build_path(module, "v2.0/vpc/routes/{id}")
340
341 r = None
342 try:
343 r = client.get(url)
344 except HwcClientException as ex:
345 msg = f"module(hwc_vpc_route): error running api(read), error: {ex}"
346 module.fail_json(msg=msg)
347
348 return navigate_value(r, ["route"], None)
349
350
351 def fill_resp_body(body):
352 result = dict()
353
354 result["destination"] = body.get("destination")
355
356 result["id"] = body.get("id")
357
358 result["nexthop"] = body.get("nexthop")
359
360 result["type"] = body.get("type")
361
362 result["vpc_id"] = body.get("vpc_id")
363
364 return result
365
366
367 def update_properties(module, response, array_index, exclude_output=False):
368 r = user_input_parameters(module)
369
370 v = navigate_value(response, ["read", "destination"], array_index)
371 r["destination"] = v
372
373 v = navigate_value(response, ["read", "nexthop"], array_index)
374 r["next_hop"] = v
375
376 v = navigate_value(response, ["read", "type"], array_index)
377 r["type"] = v
378
379 v = navigate_value(response, ["read", "vpc_id"], array_index)
380 r["vpc_id"] = v
381
382 v = navigate_value(response, ["read", "id"], array_index)
383 r["id"] = v
384
385 return r
386
387
388 def send_list_request(module, client, url):
389 r = None
390 try:
391 r = client.get(url)
392 except HwcClientException as ex:
393 msg = f"module(hwc_vpc_route): error running api(list), error: {ex}"
394 module.fail_json(msg=msg)
395
396 return navigate_value(r, ["routes"], None)
397
398
399 def _build_identity_object(all_opts):
400 result = dict()
401
402 v = navigate_value(all_opts, ["destination"], None)
403 result["destination"] = v
404
405 v = navigate_value(all_opts, ["id"], None)
406 result["id"] = v
407
408 v = navigate_value(all_opts, ["next_hop"], None)
409 result["nexthop"] = v
410
411 v = navigate_value(all_opts, ["type"], None)
412 result["type"] = v
413
414 v = navigate_value(all_opts, ["vpc_id"], None)
415 result["vpc_id"] = v
416
417 return result
418
419
420 def fill_list_resp_body(body):
421 result = dict()
422
423 result["destination"] = body.get("destination")
424
425 result["id"] = body.get("id")
426
427 result["nexthop"] = body.get("nexthop")
428
429 result["type"] = body.get("type")
430
431 result["vpc_id"] = body.get("vpc_id")
432
433 return result
434
435
436 if __name__ == "__main__":
437 main()