Debian Codegraph @

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

raw
1 # Copyright (c) 2019, Guillaume Martinez ([email protected])
2 # Copyright (c) 2018, Marcus Watkins <[email protected]>
3 # GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
4 # SPDX-License-Identifier: GPL-3.0-or-later
5
6 # Note that this module util is **PRIVATE** to the collection. It can have breaking changes at any time.
7 # Do not use this from other collections or standalone plugins/modules!
8
9 from __future__ import annotations
10
11 import traceback
12 import typing as t
13 from urllib.parse import urljoin
14
15 from ansible.module_utils.basic import missing_required_lib
16
17 from ansible_collections.community.general.plugins.module_utils._version import LooseVersion
18
19 if t.TYPE_CHECKING:
20 from ansible.module_utils.basic import AnsibleModule
21
22
23 def _determine_list_all_kwargs(version: str) -> dict[str, t.Any]:
24 gitlab_version = LooseVersion(version)
25 if gitlab_version >= LooseVersion("4.0.0"):
26 # 4.0.0 removed 'as_list'
27 return {"iterator": True, "per_page": 100}
28 elif gitlab_version >= LooseVersion("3.7.0"):
29 # 3.7.0 added 'get_all'
30 return {"as_list": False, "get_all": True, "per_page": 100}
31 else:
32 return {"as_list": False, "all": True, "per_page": 100}
33
34
35 GITLAB_IMP_ERR: str | None = None
36 try:
37 import gitlab
38 import requests
39
40 HAS_GITLAB_PACKAGE = True
41 list_all_kwargs = _determine_list_all_kwargs(gitlab.__version__)
42 except Exception:
43 gitlab = None # type: ignore
44 GITLAB_IMP_ERR = traceback.format_exc()
45 HAS_GITLAB_PACKAGE = False
46 list_all_kwargs = {}
47
48
49 def auth_argument_spec(spec: dict[str, t.Any] | None = None) -> dict[str, t.Any]:
50 arg_spec = dict(
51 ca_path=dict(type="str"),
52 api_token=dict(type="str", no_log=True),
53 api_oauth_token=dict(type="str", no_log=True),
54 api_job_token=dict(type="str", no_log=True),
55 )
56 if spec:
57 arg_spec.update(spec)
58 return arg_spec
59
60
61 def find_project(gitlab_instance, identifier):
62 try:
63 project = gitlab_instance.projects.get(identifier)
64 except Exception:
65 current_user = gitlab_instance.user
66 try:
67 project = gitlab_instance.projects.get(f"{current_user.username}/{identifier}")
68 except Exception:
69 return None
70
71 return project
72
73
74 def find_group(gitlab_instance, identifier):
75 try:
76 group = gitlab_instance.groups.get(identifier)
77 except Exception:
78 return None
79
80 return group
81
82
83 def ensure_gitlab_package(module: AnsibleModule, min_version=None) -> None:
84 if not HAS_GITLAB_PACKAGE:
85 module.fail_json(
86 msg=missing_required_lib("python-gitlab", url="https://python-gitlab.readthedocs.io/en/stable/"),
87 exception=GITLAB_IMP_ERR,
88 )
89 gitlab_version = gitlab.__version__
90 if min_version is not None and LooseVersion(gitlab_version) < LooseVersion(min_version):
91 module.fail_json(
92 msg=(
93 f"This module requires python-gitlab Python module >= {min_version} (installed version: "
94 f"{gitlab_version}). Please upgrade python-gitlab to version {min_version} or above."
95 )
96 )
97
98
99 def gitlab_authentication(module: AnsibleModule, min_version=None) -> gitlab.Gitlab:
100 ensure_gitlab_package(module, min_version=min_version)
101
102 gitlab_url = module.params["api_url"]
103 validate_certs = module.params["validate_certs"]
104 ca_path = module.params["ca_path"]
105 gitlab_user = module.params["api_username"]
106 gitlab_password = module.params["api_password"]
107 gitlab_token = module.params["api_token"]
108 gitlab_oauth_token = module.params["api_oauth_token"]
109 gitlab_job_token = module.params["api_job_token"]
110
111 verify = ca_path if validate_certs and ca_path else validate_certs
112
113 try:
114 # We can create an oauth_token using a username and password
115 # https://docs.gitlab.com/ee/api/oauth2.html#authorization-code-flow
116 if gitlab_user:
117 data = {"grant_type": "password", "username": gitlab_user, "password": gitlab_password}
118 resp = requests.post(urljoin(gitlab_url, "oauth/token"), data=data, verify=verify)
119 resp_data = resp.json()
120 gitlab_oauth_token = resp_data["access_token"]
121
122 gitlab_instance = gitlab.Gitlab(
123 url=gitlab_url,
124 ssl_verify=verify,
125 private_token=gitlab_token,
126 oauth_token=gitlab_oauth_token,
127 job_token=gitlab_job_token,
128 api_version="4",
129 )
130 gitlab_instance.auth()
131 except (gitlab.exceptions.GitlabAuthenticationError, gitlab.exceptions.GitlabGetError) as e:
132 module.fail_json(msg=f"Failed to connect to GitLab server: {e}")
133 except gitlab.exceptions.GitlabHttpError as e:
134 module.fail_json(
135 msg=(
136 f"Failed to connect to GitLab server: {e}. GitLab remove Session API now "
137 "that private tokens are removed from user API endpoints since version 10.2."
138 )
139 )
140
141 return gitlab_instance
142
143
144 def filter_returned_variables(gitlab_variables) -> list[dict[str, t.Any]]:
145 # pop properties we don't know
146 existing_variables = [dict(x.attributes) for x in gitlab_variables]
147 KNOWN = [
148 "key",
149 "value",
150 "description",
151 "masked",
152 "hidden",
153 "protected",
154 "variable_type",
155 "environment_scope",
156 "raw",
157 ]
158 for item in existing_variables:
159 for key in list(item.keys()):
160 if key not in KNOWN:
161 item.pop(key)
162 return existing_variables
163
164
165 def vars_to_variables(
166 vars: dict[str, str | int | float | dict[str, t.Any]], module: AnsibleModule
167 ) -> list[dict[str, t.Any]]:
168 # transform old vars to new variables structure
169 variables = []
170 for item, value in vars.items():
171 if isinstance(value, (str, int, float)):
172 variables.append(
173 {
174 "name": item,
175 "value": str(value),
176 "description": None,
177 "masked": False,
178 "protected": False,
179 "hidden": False,
180 "raw": False,
181 "variable_type": "env_var",
182 }
183 )
184
185 elif isinstance(value, dict):
186 new_item = {
187 "name": item,
188 "value": value.get("value"),
189 "description": value.get("description"),
190 "masked": value.get("masked"),
191 "hidden": value.get("hidden"),
192 "protected": value.get("protected"),
193 "raw": value.get("raw"),
194 "variable_type": value.get("variable_type"),
195 }
196
197 if value.get("environment_scope"):
198 new_item["environment_scope"] = value.get("environment_scope")
199
200 variables.append(new_item)
201
202 else:
203 module.fail_json(msg="value must be of type string, integer, float or dict")
204
205 return variables