Debian Codegraph @

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

raw
1 #!/usr/bin/python
2
3 # Copyright (c) 2017, Giovanni Sciortino (@giovannisciortino)
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: rhsm_repository
11 short_description: Manage RHSM repositories using the subscription-manager command
12 description:
13 - Manage (Enable/Disable) RHSM repositories to the Red Hat Subscription Management entitlement platform using the C(subscription-manager)
14 command.
15 author: Giovanni Sciortino (@giovannisciortino)
16 notes:
17 - In order to manage RHSM repositories the system must be already registered to RHSM manually or using the Ansible M(community.general.redhat_subscription)
18 module.
19 - It is possible to interact with C(subscription-manager) only as root, so root permissions are required to successfully
20 run this module.
21 requirements:
22 - subscription-manager
23 extends_documentation_fragment:
24 - community.general._attributes
25 attributes:
26 check_mode:
27 support: full
28 diff_mode:
29 support: full
30 options:
31 state:
32 description:
33 - If state is equal to present or disabled, indicates the desired repository state.
34 - In community.general 10.0.0 the states V(present) and V(absent) have been removed. Please use V(enabled) and V(disabled)
35 instead.
36 choices: [enabled, disabled]
37 default: "enabled"
38 type: str
39 name:
40 description:
41 - The ID of repositories to enable.
42 - To operate on several repositories this can accept a comma separated list or a YAML list.
43 required: true
44 type: list
45 elements: str
46 purge:
47 description:
48 - Disable all currently enabled repositories that are not not specified in O(name). Only set this to V(true) if passing
49 in a list of repositories to the O(name) field. Using this with C(loop) is likely not to have the desired result.
50 type: bool
51 default: false
52 """
53
54 EXAMPLES = r"""
55 - name: Enable a RHSM repository
56 community.general.rhsm_repository:
57 name: rhel-7-server-rpms
58
59 - name: Disable all RHSM repositories
60 community.general.rhsm_repository:
61 name: '*'
62 state: disabled
63
64 - name: Enable all repositories starting with rhel-6-server
65 community.general.rhsm_repository:
66 name: rhel-6-server*
67 state: enabled
68
69 - name: Disable all repositories except rhel-7-server-rpms
70 community.general.rhsm_repository:
71 name: rhel-7-server-rpms
72 purge: true
73 """
74
75 RETURN = r"""
76 repositories:
77 description:
78 - The list of RHSM repositories with their states.
79 - When this module is used to change the repository states, this list contains the updated states after the changes.
80 returned: success
81 type: list
82 """
83
84 import os
85 from copy import deepcopy
86 from fnmatch import fnmatch
87
88 from ansible.module_utils.basic import AnsibleModule
89
90
91 class Rhsm:
92 def __init__(self, module):
93 self.module = module
94 self.rhsm_bin = self.module.get_bin_path("subscription-manager", required=True)
95 self.rhsm_kwargs = {
96 "environ_update": dict(LANGUAGE="C", LC_ALL="C"),
97 "expand_user_and_vars": False,
98 "use_unsafe_shell": False,
99 }
100
101 def run_repos(self, arguments):
102 """
103 Execute `subscription-manager repos` with arguments and manage common errors
104 """
105 rc, out, err = self.module.run_command([self.rhsm_bin, "repos"] + arguments, **self.rhsm_kwargs)
106
107 if rc == 0 and out == "This system has no repositories available through subscriptions.\n":
108 self.module.fail_json(msg="This system has no repositories available through subscriptions")
109 elif rc == 1:
110 self.module.fail_json(msg=f"subscription-manager failed with the following error: {err}")
111 else:
112 return rc, out, err
113
114 def list_repositories(self):
115 """
116 Generate RHSM repository list and return a list of dict
117 """
118 rc, out, err = self.run_repos(["--list"])
119
120 repo_id = ""
121 repo_name = ""
122 repo_url = ""
123 repo_enabled = ""
124
125 repo_result = []
126 for line in out.splitlines():
127 # ignore lines that are:
128 # - empty
129 # - "+---------[...]" -- i.e. header
130 # - " Available Repositories [...]" -- i.e. header
131 if line == "" or line[0] == "+" or line[0] == " ":
132 continue
133
134 if line.startswith("Repo ID: "):
135 repo_id = line[9:].lstrip()
136 continue
137
138 if line.startswith("Repo Name: "):
139 repo_name = line[11:].lstrip()
140 continue
141
142 if line.startswith("Repo URL: "):
143 repo_url = line[10:].lstrip()
144 continue
145
146 if line.startswith("Enabled: "):
147 repo_enabled = line[9:].lstrip()
148
149 repo = {
150 "id": repo_id,
151 "name": repo_name,
152 "url": repo_url,
153 "enabled": True if repo_enabled == "1" else False,
154 }
155
156 repo_result.append(repo)
157
158 return repo_result
159
160
161 def repository_modify(module, rhsm, state, name, purge=False):
162 name = set(name)
163 current_repo_list = rhsm.list_repositories()
164 updated_repo_list = deepcopy(current_repo_list)
165 matched_existing_repo = {}
166 for repoid in name:
167 matched_existing_repo[repoid] = []
168 for idx, repo in enumerate(current_repo_list):
169 if fnmatch(repo["id"], repoid):
170 matched_existing_repo[repoid].append(repo)
171 # Update current_repo_list to return it as result variable
172 updated_repo_list[idx]["enabled"] = True if state == "enabled" else False
173
174 changed = False
175 results = []
176 diff_before = ""
177 diff_after = ""
178 rhsm_arguments = []
179
180 for repoid in matched_existing_repo:
181 if len(matched_existing_repo[repoid]) == 0:
182 results.append(f"{repoid} is not a valid repository ID")
183 module.fail_json(results=results, msg=f"{repoid} is not a valid repository ID")
184 for repo in matched_existing_repo[repoid]:
185 if state in ["disabled", "absent"]:
186 if repo["enabled"]:
187 changed = True
188 diff_before += f"Repository '{repo['id']}' is enabled for this system\n"
189 diff_after += f"Repository '{repo['id']}' is disabled for this system\n"
190 results.append(f"Repository '{repo['id']}' is disabled for this system")
191 rhsm_arguments += ["--disable", repo["id"]]
192 elif state in ["enabled", "present"]:
193 if not repo["enabled"]:
194 changed = True
195 diff_before += f"Repository '{repo['id']}' is disabled for this system\n"
196 diff_after += f"Repository '{repo['id']}' is enabled for this system\n"
197 results.append(f"Repository '{repo['id']}' is enabled for this system")
198 rhsm_arguments += ["--enable", repo["id"]]
199
200 # Disable all enabled repos on the system that are not in the task and not
201 # marked as disabled by the task
202 if purge:
203 enabled_repo_ids = {repo["id"] for repo in updated_repo_list if repo["enabled"]}
204 matched_repoids_set = set(matched_existing_repo.keys())
205 difference = enabled_repo_ids.difference(matched_repoids_set)
206 if len(difference) > 0:
207 for repoid in difference:
208 changed = True
209 diff_before.join(f"Repository '{repoid}'' is enabled for this system\n")
210 diff_after.join(f"Repository '{repoid}' is disabled for this system\n")
211 results.append(f"Repository '{repoid}' is disabled for this system")
212 rhsm_arguments.extend(["--disable", repoid])
213 for updated_repo in updated_repo_list:
214 if updated_repo["id"] in difference:
215 updated_repo["enabled"] = False
216
217 diff = {
218 "before": diff_before,
219 "after": diff_after,
220 "before_header": "RHSM repositories",
221 "after_header": "RHSM repositories",
222 }
223
224 if not module.check_mode and changed:
225 rc, out, err = rhsm.run_repos(rhsm_arguments)
226 results = out.splitlines()
227 module.exit_json(results=results, changed=changed, repositories=updated_repo_list, diff=diff)
228
229
230 def main():
231 module = AnsibleModule(
232 argument_spec=dict(
233 name=dict(type="list", elements="str", required=True),
234 state=dict(choices=["enabled", "disabled"], default="enabled"),
235 purge=dict(type="bool", default=False),
236 ),
237 supports_check_mode=True,
238 )
239
240 if os.getuid() != 0:
241 module.fail_json(msg="Interacting with subscription-manager requires root permissions ('become: true')")
242
243 rhsm = Rhsm(module)
244
245 name = module.params["name"]
246 state = module.params["state"]
247 purge = module.params["purge"]
248
249 repository_modify(module, rhsm, state, name, purge)
250
251
252 if __name__ == "__main__":
253 main()