Debian Codegraph @

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

raw
1 #!/usr/bin/python
2
3 # Copyright (c) 2021, Álvaro Torres Cogollo
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 DOCUMENTATION = r"""
10 module: github_repo
11 short_description: Manage your repositories on Github
12 version_added: 2.2.0
13 description:
14 - Manages Github repositories using PyGithub library.
15 - Authentication can be done with O(access_token) or with O(username) and O(password).
16 extends_documentation_fragment:
17 - community.general._attributes
18 attributes:
19 check_mode:
20 support: full
21 diff_mode:
22 support: none
23 options:
24 username:
25 description:
26 - Username used for authentication.
27 - This is only needed when not using O(access_token).
28 type: str
29 password:
30 description:
31 - Password used for authentication.
32 - This is only needed when not using O(access_token).
33 type: str
34 access_token:
35 description:
36 - Token parameter for authentication.
37 - This is only needed when not using O(username) and O(password).
38 type: str
39 name:
40 description:
41 - Repository name.
42 type: str
43 required: true
44 description:
45 description:
46 - Description for the repository.
47 - Defaults to empty if O(force_defaults=true), which is the default in this module.
48 - Defaults to empty if O(force_defaults=false) when creating a new repository.
49 - This is only used when O(state) is V(present).
50 type: str
51 private:
52 description:
53 - Whether the repository should be private or not.
54 - Defaults to V(false) if O(force_defaults=true), which is the default in this module.
55 - Defaults to V(false) if O(force_defaults=false) when creating a new repository.
56 - This is only used when O(state=present).
57 type: bool
58 state:
59 description:
60 - Whether the repository should exist or not.
61 type: str
62 default: present
63 choices: [absent, present]
64 organization:
65 description:
66 - Organization for the repository.
67 - When O(state=present), the repository is created in the current user profile.
68 type: str
69 api_url:
70 description:
71 - URL to the GitHub API if not using github.com but you own instance.
72 type: str
73 default: 'https://api.github.com'
74 version_added: "3.5.0"
75 force_defaults:
76 description:
77 - If V(true), overwrite current O(description) and O(private) attributes with defaults.
78 - The default value changed from V(true) to V(false) in community.general 13.0.0.
79 type: bool
80 default: false
81 version_added: 4.1.0
82 requirements:
83 - PyGithub>=1.54
84 notes:
85 - For Python 3, PyGithub>=1.54 should be used.
86 author:
87 - Álvaro Torres Cogollo (@atorrescogollo)
88 """
89
90 EXAMPLES = r"""
91 - name: Create a Github repository
92 community.general.github_repo:
93 access_token: mytoken
94 organization: MyOrganization
95 name: myrepo
96 description: "Just for fun"
97 private: true
98 state: present
99 force_defaults: false
100 register: result
101
102 - name: Delete the repository
103 community.general.github_repo:
104 username: octocat
105 password: password
106 organization: MyOrganization
107 name: myrepo
108 state: absent
109 register: result
110 """
111
112 RETURN = r"""
113 repo:
114 description: Repository information as JSON. See U(https://docs.github.com/en/rest/reference/repos#get-a-repository).
115 returned: success and O(state=present)
116 type: dict
117 """
118
119 import traceback
120
121 from ansible.module_utils.basic import AnsibleModule, missing_required_lib
122
123 GITHUB_IMP_ERR = None
124 try:
125 from github import Github, GithubException, GithubObject
126 from github.GithubException import UnknownObjectException
127
128 HAS_GITHUB_PACKAGE = True
129 except Exception:
130 GITHUB_IMP_ERR = traceback.format_exc()
131 HAS_GITHUB_PACKAGE = False
132
133
134 def authenticate(username=None, password=None, access_token=None, api_url=None):
135 if not api_url:
136 return None
137
138 if access_token:
139 return Github(base_url=api_url, login_or_token=access_token)
140 else:
141 return Github(base_url=api_url, login_or_token=username, password=password)
142
143
144 def create_repo(gh, name, organization=None, private=None, description=None, check_mode=False):
145 result = dict(changed=False, repo=dict())
146 if organization:
147 target = gh.get_organization(organization)
148 else:
149 target = gh.get_user()
150
151 repo = None
152 try:
153 repo = target.get_repo(name=name)
154 result["repo"] = repo.raw_data
155 except UnknownObjectException:
156 if not check_mode:
157 repo = target.create_repo(
158 name=name,
159 private=GithubObject.NotSet if private is None else private,
160 description=GithubObject.NotSet if description is None else description,
161 )
162 result["repo"] = repo.raw_data
163
164 result["changed"] = True
165
166 changes = {}
167 if private is not None:
168 if repo is None or repo.raw_data["private"] != private:
169 changes["private"] = private
170 if description is not None:
171 if repo is None or repo.raw_data["description"] not in (description, description or None):
172 changes["description"] = description
173
174 if changes:
175 if not check_mode:
176 repo.edit(**changes)
177
178 result["repo"].update(
179 {
180 "private": repo._private.value if not check_mode else private,
181 "description": repo._description.value if not check_mode else description,
182 }
183 )
184 result["changed"] = True
185
186 return result
187
188
189 def delete_repo(gh, name, organization=None, check_mode=False):
190 result = dict(changed=False)
191 if organization:
192 target = gh.get_organization(organization)
193 else:
194 target = gh.get_user()
195 try:
196 repo = target.get_repo(name=name)
197 if not check_mode:
198 repo.delete()
199 result["changed"] = True
200 except UnknownObjectException:
201 pass
202
203 return result
204
205
206 def run_module(params, check_mode=False):
207 if params["force_defaults"]:
208 params["description"] = params["description"] or ""
209 params["private"] = params["private"] or False
210
211 gh = authenticate(
212 username=params["username"],
213 password=params["password"],
214 access_token=params["access_token"],
215 api_url=params["api_url"],
216 )
217 if params["state"] == "absent":
218 return delete_repo(gh=gh, name=params["name"], organization=params["organization"], check_mode=check_mode)
219 else:
220 return create_repo(
221 gh=gh,
222 name=params["name"],
223 organization=params["organization"],
224 private=params["private"],
225 description=params["description"],
226 check_mode=check_mode,
227 )
228
229
230 def main():
231 module_args = dict(
232 username=dict(type="str"),
233 password=dict(type="str", no_log=True),
234 access_token=dict(type="str", no_log=True),
235 name=dict(type="str", required=True),
236 state=dict(type="str", default="present", choices=["present", "absent"]),
237 organization=dict(
238 type="str",
239 ),
240 private=dict(type="bool"),
241 description=dict(type="str"),
242 api_url=dict(type="str", default="https://api.github.com"),
243 force_defaults=dict(type="bool", default=False),
244 )
245 module = AnsibleModule(
246 argument_spec=module_args,
247 supports_check_mode=True,
248 required_together=[("username", "password")],
249 required_one_of=[("username", "access_token")],
250 mutually_exclusive=[("username", "access_token")],
251 )
252
253 if not HAS_GITHUB_PACKAGE:
254 module.fail_json(msg=missing_required_lib("PyGithub"), exception=GITHUB_IMP_ERR)
255
256 try:
257 result = run_module(module.params, module.check_mode)
258 module.exit_json(**result)
259 except GithubException as e:
260 module.fail_json(msg=f"Github error. {e}")
261 except Exception as e:
262 module.fail_json(msg=f"Unexpected error. {e}")
263
264
265 if __name__ == "__main__":
266 main()