Debian Codegraph @

ansible_collections/community/general/plugins/module_utils/_rundeck.py

raw
1 # Copyright (c) 2021, Phillipe Smith <[email protected]>
2 # GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
3 # SPDX-License-Identifier: GPL-3.0-or-later
4
5 # Note that this module util is **PRIVATE** to the collection. It can have breaking changes at any time.
6 # Do not use this from other collections or standalone plugins/modules!
7
8 from __future__ import annotations
9
10 import json
11 import traceback
12 import typing as t
13 from http import HTTPStatus
14
15 from ansible.module_utils.urls import fetch_url, url_argument_spec
16
17 if t.TYPE_CHECKING:
18 from ansible.module_utils.basic import AnsibleModule
19
20
21 def api_argument_spec() -> dict[str, t.Any]:
22 """
23 Creates an argument spec that can be used with any module
24 that will be requesting content via Rundeck API
25 """
26 api_argument_spec = url_argument_spec()
27 api_argument_spec.update(
28 dict(
29 url=dict(required=True, type="str"),
30 api_version=dict(type="int", default=39),
31 api_token=dict(required=True, type="str", no_log=True),
32 )
33 )
34
35 return api_argument_spec
36
37
38 def api_request(
39 module: AnsibleModule,
40 endpoint: str,
41 data: t.Any | None = None,
42 method: str = "GET",
43 content_type: str = "application/json",
44 ) -> tuple[t.Any, dict[str, t.Any]]:
45 """Manages Rundeck API requests via HTTP(S)
46
47 :arg module: The AnsibleModule (used to get url, api_version, api_token, etc).
48 :arg endpoint: The API endpoint to be used.
49 :kwarg data: The data to be sent (in case of POST/PUT).
50 :kwarg method: "POST", "PUT", etc.
51
52 :returns: A tuple of (**response**, **info**). Use ``response.read()`` to read the data.
53 The **info** contains the 'status' and other meta data. When a HttpError (status >= 400)
54 occurred then ``info['body']`` contains the error response data::
55
56 Example::
57
58 data={...}
59 resp, info = fetch_url(module,
60 "http://rundeck.example.org",
61 data=module.jsonify(data),
62 method="POST")
63 status_code = info["status"]
64 body = resp.read()
65 if status_code >= 400 :
66 body = info['body']
67 """
68
69 response, info = fetch_url(
70 module=module,
71 url=f"{module.params['url']}/api/{module.params['api_version']}/{endpoint}",
72 data=json.dumps(data),
73 method=method,
74 headers={
75 "Content-Type": content_type,
76 "Accept": "application/json",
77 "X-Rundeck-Auth-Token": module.params["api_token"],
78 },
79 )
80
81 _status = HTTPStatus(info["status"])
82
83 if _status == HTTPStatus.FORBIDDEN:
84 module.fail_json(msg="Token authorization failed", execution_info=json.loads(info["body"]))
85 elif _status == HTTPStatus.NOT_FOUND:
86 return None, info
87 elif _status == HTTPStatus.CONFLICT:
88 module.fail_json(msg="Job executions limit reached", execution_info=json.loads(info["body"]))
89 elif _status >= HTTPStatus.INTERNAL_SERVER_ERROR: # 5xx errors
90 module.fail_json(msg="Rundeck API error", execution_info=json.loads(info["body"]))
91
92 try:
93 content = response.read()
94
95 if not content:
96 return None, info
97 else:
98 json_response = json.loads(content)
99 return json_response, info
100 except AttributeError as error:
101 module.fail_json(
102 msg=f"Rundeck API request error: {error}", exception=traceback.format_exc(), execution_info=info
103 )
104 except ValueError as error:
105 module.fail_json(
106 msg=f"No valid JSON response: {error}", exception=traceback.format_exc(), execution_info=content
107 )