| 1 |
#!/usr/bin/python |
| 2 |
|
| 3 |
# Copyright (c) James Laska ([email protected]) |
| 4 |
# |
| 5 |
# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt) |
| 6 |
# SPDX-License-Identifier: GPL-3.0-or-later |
| 7 |
|
| 8 |
from __future__ import annotations |
| 9 |
|
| 10 |
DOCUMENTATION = r""" |
| 11 |
module: redhat_subscription |
| 12 |
short_description: Manage registration and subscriptions to RHSM using C(subscription-manager) |
| 13 |
description: |
| 14 |
- Manage registration and subscription to the Red Hat Subscription Management entitlement platform using the C(subscription-manager) |
| 15 |
command, registering using D-Bus if possible. |
| 16 |
author: "Barnaby Court (@barnabycourt)" |
| 17 |
notes: |
| 18 |
- 'The module tries to use the D-Bus C(rhsm) service (part of C(subscription-manager)) to register, starting from community.general |
| 19 |
6.5.0: this is done so credentials (username, password, activation keys) can be passed to C(rhsm) in a secure way. C(subscription-manager) |
| 20 |
itself gets credentials only as arguments of command line parameters, which is I(not) secure, as they can be easily stolen |
| 21 |
by checking the process listing on the system. Due to limitations of the D-Bus interface of C(rhsm), the module does I(not) |
| 22 |
use D-Bus for registration when trying either to register using O(token), or when specifying O(environment), or when the |
| 23 |
system is old (typically RHEL 7 older than 7.4, RHEL 6, and older).' |
| 24 |
- In order to register a system, subscription-manager requires either a username and password, or an activationkey and an |
| 25 |
Organization ID. |
| 26 |
- Since 2.5 values for O(server_hostname), O(server_insecure), O(rhsm_baseurl), O(server_proxy_hostname), O(server_proxy_port), |
| 27 |
O(server_proxy_user) and O(server_proxy_password) are no longer taken from the C(/etc/rhsm/rhsm.conf) config file and |
| 28 |
default to V(null). |
| 29 |
- It is possible to interact with C(subscription-manager) only as root, so root permissions are required to successfully |
| 30 |
run this module. |
| 31 |
- Since community.general 6.5.0, credentials (that is, O(username) and O(password), O(activationkey), or O(token)) are needed |
| 32 |
only in case the system is not registered, or O(force_register) is specified; this makes it possible to use the module |
| 33 |
to tweak an already registered system, for example attaching pools to it (using O(pool_ids)), and modifying the C(syspurpose) |
| 34 |
attributes (using O(syspurpose)). |
| 35 |
requirements: |
| 36 |
- subscription-manager |
| 37 |
- Optionally the C(dbus) Python library; this is usually included in the OS as it is used by C(subscription-manager). |
| 38 |
extends_documentation_fragment: |
| 39 |
- community.general._attributes |
| 40 |
attributes: |
| 41 |
check_mode: |
| 42 |
support: none |
| 43 |
diff_mode: |
| 44 |
support: none |
| 45 |
options: |
| 46 |
state: |
| 47 |
description: |
| 48 |
- Whether to register and subscribe (V(present)), or unregister (V(absent)) a system. |
| 49 |
choices: ["present", "absent"] |
| 50 |
default: "present" |
| 51 |
type: str |
| 52 |
username: |
| 53 |
description: |
| 54 |
- Access.redhat.com or Red Hat Satellite or Katello username. |
| 55 |
type: str |
| 56 |
password: |
| 57 |
description: |
| 58 |
- Access.redhat.com or Red Hat Satellite or Katello password. |
| 59 |
type: str |
| 60 |
token: |
| 61 |
description: |
| 62 |
- Sso.redhat.com API access token. |
| 63 |
type: str |
| 64 |
version_added: 6.3.0 |
| 65 |
server_hostname: |
| 66 |
description: |
| 67 |
- Specify an alternative Red Hat Subscription Management or Red Hat Satellite or Katello server. |
| 68 |
type: str |
| 69 |
server_insecure: |
| 70 |
description: |
| 71 |
- Enable or disable https server certificate verification when connecting to O(server_hostname). |
| 72 |
type: str |
| 73 |
server_prefix: |
| 74 |
description: |
| 75 |
- Specify the prefix when registering to the Red Hat Subscription Management or Red Hat Satellite or Katello server. |
| 76 |
type: str |
| 77 |
version_added: 3.3.0 |
| 78 |
server_port: |
| 79 |
description: |
| 80 |
- Specify the port when registering to the Red Hat Subscription Management or Red Hat Satellite or Katello server. |
| 81 |
type: str |
| 82 |
version_added: 3.3.0 |
| 83 |
rhsm_baseurl: |
| 84 |
description: |
| 85 |
- Specify CDN baseurl. |
| 86 |
type: str |
| 87 |
rhsm_repo_ca_cert: |
| 88 |
description: |
| 89 |
- Specify an alternative location for a CA certificate for CDN. |
| 90 |
type: str |
| 91 |
server_proxy_hostname: |
| 92 |
description: |
| 93 |
- Specify an HTTP proxy hostname. |
| 94 |
type: str |
| 95 |
server_proxy_scheme: |
| 96 |
description: |
| 97 |
- Specify an HTTP proxy scheme, for example V(http) or V(https). |
| 98 |
type: str |
| 99 |
version_added: 6.2.0 |
| 100 |
server_proxy_port: |
| 101 |
description: |
| 102 |
- Specify an HTTP proxy port. |
| 103 |
type: str |
| 104 |
server_proxy_user: |
| 105 |
description: |
| 106 |
- Specify a user for HTTP proxy with basic authentication. |
| 107 |
type: str |
| 108 |
server_proxy_password: |
| 109 |
description: |
| 110 |
- Specify a password for HTTP proxy with basic authentication. |
| 111 |
type: str |
| 112 |
auto_attach: |
| 113 |
description: |
| 114 |
- Upon successful registration, auto-consume available subscriptions. |
| 115 |
- Please note that the alias O(ignore:autosubscribe) was removed in community.general 9.0.0. |
| 116 |
type: bool |
| 117 |
activationkey: |
| 118 |
description: |
| 119 |
- Supply an activation key for use with registration. |
| 120 |
type: str |
| 121 |
org_id: |
| 122 |
description: |
| 123 |
- Organization ID to use in conjunction with activationkey. |
| 124 |
type: str |
| 125 |
environment: |
| 126 |
description: |
| 127 |
- Register with a specific environment in the destination org. Used with Red Hat Satellite or Katello. |
| 128 |
type: str |
| 129 |
pool_ids: |
| 130 |
description: |
| 131 |
- Specify subscription pool IDs to consume. |
| 132 |
- 'A pool ID may be specified as a C(string) - just the pool ID (for example V(0123456789abcdef0123456789abcdef)), or |
| 133 |
as a C(dict) with the pool ID as the key, and a quantity as the value (for example V(0123456789abcdef0123456789abcdef: |
| 134 |
2). If the quantity is provided, it is used to consume multiple entitlements from a pool (the pool must support this).' |
| 135 |
default: [] |
| 136 |
type: list |
| 137 |
elements: raw |
| 138 |
consumer_type: |
| 139 |
description: |
| 140 |
- The type of unit to register, defaults to system. |
| 141 |
type: str |
| 142 |
consumer_name: |
| 143 |
description: |
| 144 |
- Name of the system to register, defaults to the hostname. |
| 145 |
type: str |
| 146 |
consumer_id: |
| 147 |
description: |
| 148 |
- References an existing consumer ID to resume using a previous registration for this system. If the system's identity |
| 149 |
certificate is lost or corrupted, this option allows it to resume using its previous identity and subscriptions. The |
| 150 |
default is to not specify a consumer ID so a new ID is created. |
| 151 |
type: str |
| 152 |
force_register: |
| 153 |
description: |
| 154 |
- Register the system even if it is already registered. |
| 155 |
type: bool |
| 156 |
default: false |
| 157 |
release: |
| 158 |
description: |
| 159 |
- Set a release version. |
| 160 |
type: str |
| 161 |
syspurpose: |
| 162 |
description: |
| 163 |
- Set syspurpose attributes in file C(/etc/rhsm/syspurpose/syspurpose.json) and synchronize these attributes with RHSM |
| 164 |
server. Syspurpose attributes help attach the most appropriate subscriptions to the system automatically. When C(syspurpose.json) |
| 165 |
file already contains some attributes, then new attributes overwrite existing attributes. When some attribute is not |
| 166 |
listed in the new list of attributes, the existing attribute is removed from C(syspurpose.json) file. Unknown attributes |
| 167 |
are ignored. |
| 168 |
type: dict |
| 169 |
suboptions: |
| 170 |
usage: |
| 171 |
description: Syspurpose attribute usage. |
| 172 |
type: str |
| 173 |
role: |
| 174 |
description: Syspurpose attribute role. |
| 175 |
type: str |
| 176 |
service_level_agreement: |
| 177 |
description: Syspurpose attribute service_level_agreement. |
| 178 |
type: str |
| 179 |
addons: |
| 180 |
description: Syspurpose attribute addons. |
| 181 |
type: list |
| 182 |
elements: str |
| 183 |
sync: |
| 184 |
description: |
| 185 |
- When this option is V(true), then syspurpose attributes are synchronized with RHSM server immediately. When this |
| 186 |
option is V(false), then syspurpose attributes are synchronized with RHSM server by rhsmcertd daemon. |
| 187 |
type: bool |
| 188 |
default: false |
| 189 |
""" |
| 190 |
|
| 191 |
EXAMPLES = r""" |
| 192 |
- name: Register as user (joe_user) with password (somepass) and auto-subscribe to available content. |
| 193 |
community.general.redhat_subscription: |
| 194 |
state: present |
| 195 |
username: joe_user |
| 196 |
password: somepass |
| 197 |
auto_attach: true |
| 198 |
|
| 199 |
- name: Same as above but subscribe to a specific pool by ID. |
| 200 |
community.general.redhat_subscription: |
| 201 |
state: present |
| 202 |
username: joe_user |
| 203 |
password: somepass |
| 204 |
pool_ids: 0123456789abcdef0123456789abcdef |
| 205 |
|
| 206 |
- name: Register and subscribe to multiple pools. |
| 207 |
community.general.redhat_subscription: |
| 208 |
state: present |
| 209 |
username: joe_user |
| 210 |
password: somepass |
| 211 |
pool_ids: |
| 212 |
- 0123456789abcdef0123456789abcdef |
| 213 |
- 1123456789abcdef0123456789abcdef |
| 214 |
|
| 215 |
- name: Same as above but consume multiple entitlements. |
| 216 |
community.general.redhat_subscription: |
| 217 |
state: present |
| 218 |
username: joe_user |
| 219 |
password: somepass |
| 220 |
pool_ids: |
| 221 |
- 0123456789abcdef0123456789abcdef: 2 |
| 222 |
- 1123456789abcdef0123456789abcdef: 4 |
| 223 |
|
| 224 |
- name: Register and pull existing system data. |
| 225 |
community.general.redhat_subscription: |
| 226 |
state: present |
| 227 |
username: joe_user |
| 228 |
password: somepass |
| 229 |
consumer_id: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx |
| 230 |
|
| 231 |
- name: Register as user credentials into given environment (against Red Hat Satellite or Katello), and auto-subscribe. |
| 232 |
community.general.redhat_subscription: |
| 233 |
state: present |
| 234 |
username: joe_user |
| 235 |
password: somepass |
| 236 |
environment: Library |
| 237 |
auto_attach: true |
| 238 |
|
| 239 |
- name: Register as user (joe_user) with password (somepass) and a specific release |
| 240 |
community.general.redhat_subscription: |
| 241 |
state: present |
| 242 |
username: joe_user |
| 243 |
password: somepass |
| 244 |
release: 7.4 |
| 245 |
|
| 246 |
- name: Register as user (joe_user) with password (somepass), set syspurpose attributes and synchronize them with server |
| 247 |
community.general.redhat_subscription: |
| 248 |
state: present |
| 249 |
username: joe_user |
| 250 |
password: somepass |
| 251 |
auto_attach: true |
| 252 |
syspurpose: |
| 253 |
usage: "Production" |
| 254 |
role: "Red Hat Enterprise Server" |
| 255 |
service_level_agreement: "Premium" |
| 256 |
addons: |
| 257 |
- addon1 |
| 258 |
- addon2 |
| 259 |
sync: true |
| 260 |
""" |
| 261 |
|
| 262 |
RETURN = r""" |
| 263 |
subscribed_pool_ids: |
| 264 |
description: List of pool IDs to which system is now subscribed. |
| 265 |
returned: success |
| 266 |
type: dict |
| 267 |
sample: {"8a85f9815ab905d3015ab928c7005de4": "1"} |
| 268 |
""" |
| 269 |
|
| 270 |
import configparser |
| 271 |
import json |
| 272 |
import re |
| 273 |
import shutil |
| 274 |
import tempfile |
| 275 |
from os import getuid, unlink |
| 276 |
from os.path import isfile |
| 277 |
|
| 278 |
from ansible.module_utils import distro |
| 279 |
from ansible.module_utils.basic import AnsibleModule |
| 280 |
from ansible.module_utils.common.text.converters import to_native |
| 281 |
|
| 282 |
SUBMAN_CMD = None |
| 283 |
|
| 284 |
|
| 285 |
class Rhsm: |
| 286 |
REDHAT_REPO = "/etc/yum.repos.d/redhat.repo" |
| 287 |
|
| 288 |
def __init__(self, module): |
| 289 |
self.module = module |
| 290 |
|
| 291 |
def update_plugin_conf(self, plugin, enabled=True): |
| 292 |
plugin_conf = f"/etc/yum/pluginconf.d/{plugin}.conf" |
| 293 |
|
| 294 |
if isfile(plugin_conf): |
| 295 |
tmpfd, tmpfile = tempfile.mkstemp() |
| 296 |
shutil.copy2(plugin_conf, tmpfile) |
| 297 |
cfg = configparser.ConfigParser() |
| 298 |
cfg.read([tmpfile]) |
| 299 |
|
| 300 |
if enabled: |
| 301 |
cfg.set("main", "enabled", "1") |
| 302 |
else: |
| 303 |
cfg.set("main", "enabled", "0") |
| 304 |
|
| 305 |
with open(tmpfile, "w+") as fd: |
| 306 |
cfg.write(fd) |
| 307 |
self.module.atomic_move(tmpfile, plugin_conf) |
| 308 |
|
| 309 |
def enable(self): |
| 310 |
""" |
| 311 |
Enable the system to receive updates from subscription-manager. |
| 312 |
This involves updating affected yum plugins and removing any |
| 313 |
conflicting yum repositories. |
| 314 |
""" |
| 315 |
# Remove any existing redhat.repo |
| 316 |
if isfile(self.REDHAT_REPO): |
| 317 |
unlink(self.REDHAT_REPO) |
| 318 |
self.update_plugin_conf("rhnplugin", False) |
| 319 |
self.update_plugin_conf("subscription-manager", True) |
| 320 |
|
| 321 |
def configure(self, **kwargs): |
| 322 |
""" |
| 323 |
Configure the system as directed for registration with RHSM |
| 324 |
Raises: |
| 325 |
* Exception - if error occurs while running command |
| 326 |
""" |
| 327 |
|
| 328 |
args = [SUBMAN_CMD, "config"] |
| 329 |
|
| 330 |
# Pass supplied **kwargs as parameters to subscription-manager. Ignore |
| 331 |
# non-configuration parameters and replace '_' with '.'. For example, |
| 332 |
# 'server_hostname' becomes '--server.hostname'. |
| 333 |
options = [] |
| 334 |
for k, v in sorted(kwargs.items()): |
| 335 |
if re.search(r"^(server|rhsm)_", k) and v is not None: |
| 336 |
options.append(f"--{k.replace('_', '.', 1)}={v}") |
| 337 |
|
| 338 |
# When there is nothing to configure, then it is not necessary |
| 339 |
# to run config command, because it only returns current |
| 340 |
# content of current configuration file |
| 341 |
if len(options) == 0: |
| 342 |
return |
| 343 |
|
| 344 |
args.extend(options) |
| 345 |
|
| 346 |
self.module.run_command(args, check_rc=True) |
| 347 |
|
| 348 |
@property |
| 349 |
def is_registered(self): |
| 350 |
""" |
| 351 |
Determine whether the current system |
| 352 |
Returns: |
| 353 |
* Boolean - whether the current system is currently registered to |
| 354 |
RHSM. |
| 355 |
""" |
| 356 |
|
| 357 |
args = [SUBMAN_CMD, "identity"] |
| 358 |
rc, stdout, stderr = self.module.run_command(args, check_rc=False) |
| 359 |
return rc == 0 |
| 360 |
|
| 361 |
def _has_dbus_interface(self): |
| 362 |
""" |
| 363 |
Checks whether subscription-manager has a D-Bus interface. |
| 364 |
|
| 365 |
:returns: bool -- whether subscription-manager has a D-Bus interface. |
| 366 |
""" |
| 367 |
|
| 368 |
def str2int(s, default=0): |
| 369 |
try: |
| 370 |
return int(s) |
| 371 |
except ValueError: |
| 372 |
return default |
| 373 |
|
| 374 |
distro_id = distro.id() |
| 375 |
distro_version = tuple(str2int(p) for p in distro.version_parts()) |
| 376 |
|
| 377 |
# subscription-manager in any supported Fedora version has the interface. |
| 378 |
if distro_id == "fedora": |
| 379 |
return True |
| 380 |
# Any other distro: assume it is EL; |
| 381 |
# the D-Bus interface was added to subscription-manager in RHEL 7.4. |
| 382 |
return (distro_version[0] == 7 and distro_version[1] >= 4) or distro_version[0] >= 8 |
| 383 |
|
| 384 |
def _can_connect_to_dbus(self): |
| 385 |
""" |
| 386 |
Checks whether it is possible to connect to the system D-Bus bus. |
| 387 |
|
| 388 |
:returns: bool -- whether it is possible to connect to the system D-Bus bus. |
| 389 |
""" |
| 390 |
|
| 391 |
try: |
| 392 |
# Technically speaking, subscription-manager uses dbus-python |
| 393 |
# as D-Bus library, so this ought to work; better be safe than |
| 394 |
# sorry, I guess... |
| 395 |
import dbus |
| 396 |
except ImportError: |
| 397 |
self.module.debug("dbus Python module not available, will use CLI") |
| 398 |
return False |
| 399 |
|
| 400 |
try: |
| 401 |
bus = dbus.SystemBus() |
| 402 |
msg = dbus.lowlevel.SignalMessage("/", "com.example", "test") |
| 403 |
bus.send_message(msg) |
| 404 |
bus.flush() |
| 405 |
|
| 406 |
except dbus.exceptions.DBusException as e: |
| 407 |
self.module.debug(f"Failed to connect to system D-Bus bus, will use CLI: {e}") |
| 408 |
return False |
| 409 |
|
| 410 |
self.module.debug("Verified system D-Bus bus as usable") |
| 411 |
return True |
| 412 |
|
| 413 |
def register( |
| 414 |
self, |
| 415 |
was_registered, |
| 416 |
username, |
| 417 |
password, |
| 418 |
token, |
| 419 |
auto_attach, |
| 420 |
activationkey, |
| 421 |
org_id, |
| 422 |
consumer_type, |
| 423 |
consumer_name, |
| 424 |
consumer_id, |
| 425 |
force_register, |
| 426 |
environment, |
| 427 |
release, |
| 428 |
): |
| 429 |
""" |
| 430 |
Register the current system to the provided RHSM or Red Hat Satellite |
| 431 |
or Katello server |
| 432 |
|
| 433 |
Raises: |
| 434 |
* Exception - if any error occurs during the registration |
| 435 |
""" |
| 436 |
# There is no support for token-based registration in the D-Bus API |
| 437 |
# of rhsm, so always use the CLI in that case; |
| 438 |
# also, since the specified environments are names, and the D-Bus APIs |
| 439 |
# require IDs for the environments, use the CLI also in that case |
| 440 |
if not token and not environment and self._has_dbus_interface() and self._can_connect_to_dbus(): |
| 441 |
self._register_using_dbus( |
| 442 |
was_registered, |
| 443 |
username, |
| 444 |
password, |
| 445 |
auto_attach, |
| 446 |
activationkey, |
| 447 |
org_id, |
| 448 |
consumer_type, |
| 449 |
consumer_name, |
| 450 |
consumer_id, |
| 451 |
force_register, |
| 452 |
environment, |
| 453 |
release, |
| 454 |
) |
| 455 |
return |
| 456 |
self._register_using_cli( |
| 457 |
username, |
| 458 |
password, |
| 459 |
token, |
| 460 |
auto_attach, |
| 461 |
activationkey, |
| 462 |
org_id, |
| 463 |
consumer_type, |
| 464 |
consumer_name, |
| 465 |
consumer_id, |
| 466 |
force_register, |
| 467 |
environment, |
| 468 |
release, |
| 469 |
) |
| 470 |
|
| 471 |
def _register_using_cli( |
| 472 |
self, |
| 473 |
username, |
| 474 |
password, |
| 475 |
token, |
| 476 |
auto_attach, |
| 477 |
activationkey, |
| 478 |
org_id, |
| 479 |
consumer_type, |
| 480 |
consumer_name, |
| 481 |
consumer_id, |
| 482 |
force_register, |
| 483 |
environment, |
| 484 |
release, |
| 485 |
): |
| 486 |
""" |
| 487 |
Register using the 'subscription-manager' command |
| 488 |
|
| 489 |
Raises: |
| 490 |
* Exception - if error occurs while running command |
| 491 |
""" |
| 492 |
args = [SUBMAN_CMD, "register"] |
| 493 |
|
| 494 |
# Generate command arguments |
| 495 |
if force_register: |
| 496 |
args.extend(["--force"]) |
| 497 |
|
| 498 |
if org_id: |
| 499 |
args.extend(["--org", org_id]) |
| 500 |
|
| 501 |
if auto_attach: |
| 502 |
args.append("--auto-attach") |
| 503 |
|
| 504 |
if consumer_type: |
| 505 |
args.extend(["--type", consumer_type]) |
| 506 |
|
| 507 |
if consumer_name: |
| 508 |
args.extend(["--name", consumer_name]) |
| 509 |
|
| 510 |
if consumer_id: |
| 511 |
args.extend(["--consumerid", consumer_id]) |
| 512 |
|
| 513 |
if environment: |
| 514 |
args.extend(["--environment", environment]) |
| 515 |
|
| 516 |
if activationkey: |
| 517 |
args.extend(["--activationkey", activationkey]) |
| 518 |
elif token: |
| 519 |
args.extend(["--token", token]) |
| 520 |
else: |
| 521 |
if username: |
| 522 |
args.extend(["--username", username]) |
| 523 |
if password: |
| 524 |
args.extend(["--password", password]) |
| 525 |
|
| 526 |
if release: |
| 527 |
args.extend(["--release", release]) |
| 528 |
|
| 529 |
rc, stderr, stdout = self.module.run_command(args, check_rc=True, expand_user_and_vars=False) |
| 530 |
|
| 531 |
def _register_using_dbus( |
| 532 |
self, |
| 533 |
was_registered, |
| 534 |
username, |
| 535 |
password, |
| 536 |
auto_attach, |
| 537 |
activationkey, |
| 538 |
org_id, |
| 539 |
consumer_type, |
| 540 |
consumer_name, |
| 541 |
consumer_id, |
| 542 |
force_register, |
| 543 |
environment, |
| 544 |
release, |
| 545 |
): |
| 546 |
""" |
| 547 |
Register using D-Bus (connecting to the rhsm service) |
| 548 |
|
| 549 |
Raises: |
| 550 |
* Exception - if error occurs during the D-Bus communication |
| 551 |
""" |
| 552 |
import dbus |
| 553 |
|
| 554 |
SUBSCRIPTION_MANAGER_LOCALE = "C" |
| 555 |
# Seconds to wait for Registration to complete over DBus; |
| 556 |
# 10 minutes should be a pretty generous timeout. |
| 557 |
REGISTRATION_TIMEOUT = 600 |
| 558 |
|
| 559 |
def str2int(s, default=0): |
| 560 |
try: |
| 561 |
return int(s) |
| 562 |
except ValueError: |
| 563 |
return default |
| 564 |
|
| 565 |
distro_id = distro.id() |
| 566 |
distro_version_parts = distro.version_parts() |
| 567 |
distro_version = tuple(str2int(p) for p in distro_version_parts) |
| 568 |
|
| 569 |
# Stop the rhsm service when using systemd (which means Fedora or |
| 570 |
# RHEL 7+): this is because the service may not use new configuration bits |
| 571 |
# - with subscription-manager < 1.26.5-1 (in RHEL < 8.2); |
| 572 |
# fixed later by https://github.com/candlepin/subscription-manager/pull/2175 |
| 573 |
# - sporadically: https://bugzilla.redhat.com/show_bug.cgi?id=2049296 |
| 574 |
if distro_id == "fedora" or distro_version[0] >= 7: |
| 575 |
cmd = ["systemctl", "stop", "rhsm"] |
| 576 |
self.module.run_command(cmd, check_rc=True, expand_user_and_vars=False) |
| 577 |
|
| 578 |
# While there is a 'force' options for the registration, it is actually |
| 579 |
# not implemented (and thus it does not work) |
| 580 |
# - in RHEL 7 and earlier |
| 581 |
# - in RHEL 8 before 8.8: https://bugzilla.redhat.com/show_bug.cgi?id=2118486 |
| 582 |
# - in RHEL 9 before 9.2: https://bugzilla.redhat.com/show_bug.cgi?id=2121350 |
| 583 |
# Hence, use it only when implemented, manually unregistering otherwise. |
| 584 |
# Match it on RHEL, since we know about it; other distributions |
| 585 |
# will need their own logic. |
| 586 |
dbus_force_option_works = False |
| 587 |
if distro_id == "rhel" and ( |
| 588 |
(distro_version[0] == 8 and distro_version[1] >= 8) |
| 589 |
or (distro_version[0] == 9 and distro_version[1] >= 2) |
| 590 |
or distro_version[0] > 9 |
| 591 |
): |
| 592 |
dbus_force_option_works = True |
| 593 |
# We need to use the 'enable_content' D-Bus option to ensure that |
| 594 |
# content is enabled; sadly the option is available depending on the |
| 595 |
# version of the distro, and also depending on which API/method is used |
| 596 |
# for registration. |
| 597 |
dbus_has_enable_content_option = False |
| 598 |
if activationkey: |
| 599 |
|
| 600 |
def supports_enable_content_for_activation_keys(): |
| 601 |
# subscription-manager in Fedora >= 41 has the new option. |
| 602 |
if distro_id == "fedora" and distro_version[0] >= 41: |
| 603 |
return True |
| 604 |
# Assume EL distros here. |
| 605 |
if distro_version[0] >= 10: # noqa: SIM103 |
| 606 |
return True |
| 607 |
return False |
| 608 |
|
| 609 |
dbus_has_enable_content_option = supports_enable_content_for_activation_keys() |
| 610 |
else: |
| 611 |
|
| 612 |
def supports_enable_content_for_credentials(): |
| 613 |
# subscription-manager in any supported Fedora version |
| 614 |
# has the new option. |
| 615 |
if distro_id == "fedora": |
| 616 |
return True |
| 617 |
# Check for RHEL 8 >= 8.6, or RHEL >= 9. |
| 618 |
if distro_id == "rhel" and ( |
| 619 |
(distro_version[0] == 8 and distro_version[1] >= 6) or distro_version[0] >= 9 |
| 620 |
): |
| 621 |
return True |
| 622 |
# CentOS: similar checks as for RHEL, with one extra bit: |
| 623 |
# if the 2nd part of the version is empty, it means it is |
| 624 |
# CentOS Stream, and thus we can assume it has the latest |
| 625 |
# version of subscription-manager. |
| 626 |
if distro_id == "centos" and ( # noqa: SIM103 |
| 627 |
(distro_version[0] == 8 and (distro_version[1] >= 6 or distro_version_parts[1] == "")) |
| 628 |
or distro_version[0] >= 9 |
| 629 |
): |
| 630 |
return True |
| 631 |
# Unknown or old distro: assume it does not support |
| 632 |
# the new option. |
| 633 |
return False |
| 634 |
|
| 635 |
dbus_has_enable_content_option = supports_enable_content_for_credentials() |
| 636 |
|
| 637 |
if force_register and not dbus_force_option_works and was_registered: |
| 638 |
self.unregister() |
| 639 |
|
| 640 |
register_opts = {} |
| 641 |
if consumer_type: |
| 642 |
# The option for the consumer type used to be 'type' in versions |
| 643 |
# of RHEL before 9 & in RHEL 9 before 9.2, and then it changed to |
| 644 |
# 'consumer_type'; since the Register*() D-Bus functions reject |
| 645 |
# unknown options, we have to pass the right option depending on |
| 646 |
# the version -- funky. |
| 647 |
def supports_option_consumer_type(): |
| 648 |
# subscription-manager in any supported Fedora version |
| 649 |
# has the new option. |
| 650 |
if distro_id == "fedora": |
| 651 |
return True |
| 652 |
# Check for RHEL 9 >= 9.2, or RHEL >= 10. |
| 653 |
if distro_id == "rhel" and ( |
| 654 |
(distro_version[0] == 9 and distro_version[1] >= 2) or distro_version[0] >= 10 |
| 655 |
): |
| 656 |
return True |
| 657 |
# CentOS: since the change was only done in EL 9, then there is |
| 658 |
# only CentOS Stream for 9, and thus we can assume it has the |
| 659 |
# latest version of subscription-manager. |
| 660 |
if distro_id == "centos" and distro_version[0] >= 9: # noqa: SIM103 |
| 661 |
return True |
| 662 |
# Unknown or old distro: assume it does not support |
| 663 |
# the new option. |
| 664 |
return False |
| 665 |
|
| 666 |
consumer_type_key = "type" |
| 667 |
if supports_option_consumer_type(): |
| 668 |
consumer_type_key = "consumer_type" |
| 669 |
register_opts[consumer_type_key] = consumer_type |
| 670 |
if consumer_name: |
| 671 |
register_opts["name"] = consumer_name |
| 672 |
if consumer_id: |
| 673 |
register_opts["consumerid"] = consumer_id |
| 674 |
if environment: |
| 675 |
# The option for environments used to be 'environment' in versions |
| 676 |
# of RHEL before 8.6, and then it changed to 'environments'; since |
| 677 |
# the Register*() D-Bus functions reject unknown options, we have |
| 678 |
# to pass the right option depending on the version -- funky. |
| 679 |
def supports_option_environments(): |
| 680 |
# subscription-manager in any supported Fedora version |
| 681 |
# has the new option. |
| 682 |
if distro_id == "fedora": |
| 683 |
return True |
| 684 |
# Check for RHEL 8 >= 8.6, or RHEL >= 9. |
| 685 |
if distro_id == "rhel" and ( |
| 686 |
(distro_version[0] == 8 and distro_version[1] >= 6) or distro_version[0] >= 9 |
| 687 |
): |
| 688 |
return True |
| 689 |
# CentOS: similar checks as for RHEL, with one extra bit: |
| 690 |
# if the 2nd part of the version is empty, it means it is |
| 691 |
# CentOS Stream, and thus we can assume it has the latest |
| 692 |
# version of subscription-manager. |
| 693 |
if distro_id == "centos" and ( # noqa: SIM103 |
| 694 |
(distro_version[0] == 8 and (distro_version[1] >= 6 or distro_version_parts[1] == "")) |
| 695 |
or distro_version[0] >= 9 |
| 696 |
): |
| 697 |
return True |
| 698 |
# Unknown or old distro: assume it does not support |
| 699 |
# the new option. |
| 700 |
return False |
| 701 |
|
| 702 |
environment_key = "environment" |
| 703 |
if supports_option_environments(): |
| 704 |
environment_key = "environments" |
| 705 |
register_opts[environment_key] = environment |
| 706 |
if force_register and dbus_force_option_works and was_registered: |
| 707 |
register_opts["force"] = True |
| 708 |
if dbus_has_enable_content_option: |
| 709 |
register_opts["enable_content"] = "1" |
| 710 |
# Wrap it as proper D-Bus dict |
| 711 |
register_opts = dbus.Dictionary(register_opts, signature="sv", variant_level=1) |
| 712 |
|
| 713 |
connection_opts = {} |
| 714 |
# Wrap it as proper D-Bus dict |
| 715 |
connection_opts = dbus.Dictionary(connection_opts, signature="sv", variant_level=1) |
| 716 |
|
| 717 |
bus = dbus.SystemBus() |
| 718 |
register_server = bus.get_object("com.redhat.RHSM1", "/com/redhat/RHSM1/RegisterServer") |
| 719 |
address = register_server.Start( |
| 720 |
SUBSCRIPTION_MANAGER_LOCALE, |
| 721 |
dbus_interface="com.redhat.RHSM1.RegisterServer", |
| 722 |
) |
| 723 |
|
| 724 |
try: |
| 725 |
# Use the private bus to register the system |
| 726 |
self.module.debug("Connecting to the private DBus") |
| 727 |
private_bus = dbus.connection.Connection(address) |
| 728 |
|
| 729 |
try: |
| 730 |
if activationkey: |
| 731 |
args = ( |
| 732 |
org_id, |
| 733 |
[activationkey], |
| 734 |
register_opts, |
| 735 |
connection_opts, |
| 736 |
SUBSCRIPTION_MANAGER_LOCALE, |
| 737 |
) |
| 738 |
private_bus.call_blocking( |
| 739 |
"com.redhat.RHSM1", |
| 740 |
"/com/redhat/RHSM1/Register", |
| 741 |
"com.redhat.RHSM1.Register", |
| 742 |
"RegisterWithActivationKeys", |
| 743 |
"sasa{sv}a{sv}s", |
| 744 |
args, |
| 745 |
timeout=REGISTRATION_TIMEOUT, |
| 746 |
) |
| 747 |
else: |
| 748 |
args = ( |
| 749 |
org_id or "", |
| 750 |
username, |
| 751 |
password, |
| 752 |
register_opts, |
| 753 |
connection_opts, |
| 754 |
SUBSCRIPTION_MANAGER_LOCALE, |
| 755 |
) |
| 756 |
private_bus.call_blocking( |
| 757 |
"com.redhat.RHSM1", |
| 758 |
"/com/redhat/RHSM1/Register", |
| 759 |
"com.redhat.RHSM1.Register", |
| 760 |
"Register", |
| 761 |
"sssa{sv}a{sv}s", |
| 762 |
args, |
| 763 |
timeout=REGISTRATION_TIMEOUT, |
| 764 |
) |
| 765 |
|
| 766 |
except dbus.exceptions.DBusException as e: |
| 767 |
# Sometimes we get NoReply but the registration has succeeded. |
| 768 |
# Check the registration status before deciding if this is an error. |
| 769 |
if e.get_dbus_name() == "org.freedesktop.DBus.Error.NoReply": |
| 770 |
if not self.is_registered(): |
| 771 |
# Host is not registered so re-raise the error |
| 772 |
raise |
| 773 |
else: |
| 774 |
raise |
| 775 |
# Host was registered so continue |
| 776 |
finally: |
| 777 |
# Always shut down the private bus |
| 778 |
self.module.debug("Shutting down private DBus instance") |
| 779 |
register_server.Stop( |
| 780 |
SUBSCRIPTION_MANAGER_LOCALE, |
| 781 |
dbus_interface="com.redhat.RHSM1.RegisterServer", |
| 782 |
) |
| 783 |
|
| 784 |
# Make sure to refresh all the local data: this will fetch all the |
| 785 |
# certificates, update redhat.repo, etc. |
| 786 |
self.module.run_command([SUBMAN_CMD, "refresh"], check_rc=True, expand_user_and_vars=False) |
| 787 |
|
| 788 |
if auto_attach: |
| 789 |
args = [SUBMAN_CMD, "attach", "--auto"] |
| 790 |
self.module.run_command(args, check_rc=True, expand_user_and_vars=False) |
| 791 |
|
| 792 |
# There is no support for setting the release via D-Bus, so invoke |
| 793 |
# the CLI for this. |
| 794 |
if release: |
| 795 |
args = [SUBMAN_CMD, "release", "--set", release] |
| 796 |
self.module.run_command(args, check_rc=True, expand_user_and_vars=False) |
| 797 |
|
| 798 |
def unsubscribe(self, serials=None): |
| 799 |
""" |
| 800 |
Unsubscribe a system from subscribed channels |
| 801 |
Args: |
| 802 |
serials(list or None): list of serials to unsubscribe. If |
| 803 |
serials is none or an empty list, then |
| 804 |
all subscribed channels will be removed. |
| 805 |
Raises: |
| 806 |
* Exception - if error occurs while running command |
| 807 |
""" |
| 808 |
items = [] |
| 809 |
if serials is not None and serials: |
| 810 |
items = [f"--serial={s}" for s in serials] |
| 811 |
if serials is None: |
| 812 |
items = ["--all"] |
| 813 |
|
| 814 |
if items: |
| 815 |
args = [SUBMAN_CMD, "remove"] + items |
| 816 |
rc, stderr, stdout = self.module.run_command(args, check_rc=True) |
| 817 |
return serials |
| 818 |
|
| 819 |
def unregister(self): |
| 820 |
""" |
| 821 |
Unregister a currently registered system |
| 822 |
Raises: |
| 823 |
* Exception - if error occurs while running command |
| 824 |
""" |
| 825 |
args = [SUBMAN_CMD, "unregister"] |
| 826 |
rc, stderr, stdout = self.module.run_command(args, check_rc=True) |
| 827 |
self.update_plugin_conf("rhnplugin", False) |
| 828 |
self.update_plugin_conf("subscription-manager", False) |
| 829 |
|
| 830 |
def subscribe_by_pool_ids(self, pool_ids): |
| 831 |
""" |
| 832 |
Try to subscribe to the list of pool IDs |
| 833 |
""" |
| 834 |
available_pools = RhsmPools(self.module) |
| 835 |
|
| 836 |
available_pool_ids = [p.get_pool_id() for p in available_pools] |
| 837 |
|
| 838 |
for pool_id, quantity in sorted(pool_ids.items()): |
| 839 |
if pool_id in available_pool_ids: |
| 840 |
args = [SUBMAN_CMD, "attach", "--pool", pool_id] |
| 841 |
if quantity is not None: |
| 842 |
args.extend(["--quantity", to_native(quantity)]) |
| 843 |
rc, stderr, stdout = self.module.run_command(args, check_rc=True) |
| 844 |
else: |
| 845 |
self.module.fail_json(msg=f"Pool ID: {pool_id} not in list of available pools") |
| 846 |
return pool_ids |
| 847 |
|
| 848 |
def update_subscriptions_by_pool_ids(self, pool_ids): |
| 849 |
changed = False |
| 850 |
consumed_pools = RhsmPools(self.module, consumed=True) |
| 851 |
|
| 852 |
existing_pools = {} |
| 853 |
serials_to_remove = [] |
| 854 |
for p in consumed_pools: |
| 855 |
pool_id = p.get_pool_id() |
| 856 |
quantity_used = p.get_quantity_used() |
| 857 |
existing_pools[pool_id] = quantity_used |
| 858 |
|
| 859 |
quantity = pool_ids.get(pool_id, 0) |
| 860 |
if quantity is not None and quantity != quantity_used: |
| 861 |
serials_to_remove.append(p.Serial) |
| 862 |
|
| 863 |
serials = self.unsubscribe(serials=serials_to_remove) |
| 864 |
|
| 865 |
missing_pools = {} |
| 866 |
for pool_id, quantity in sorted(pool_ids.items()): |
| 867 |
quantity_used = existing_pools.get(pool_id, 0) |
| 868 |
if quantity is None and quantity_used == 0 or quantity not in (None, 0, quantity_used): |
| 869 |
missing_pools[pool_id] = quantity |
| 870 |
|
| 871 |
self.subscribe_by_pool_ids(missing_pools) |
| 872 |
|
| 873 |
if missing_pools or serials: |
| 874 |
changed = True |
| 875 |
return {"changed": changed, "subscribed_pool_ids": list(missing_pools.keys()), "unsubscribed_serials": serials} |
| 876 |
|
| 877 |
def sync_syspurpose(self): |
| 878 |
""" |
| 879 |
Try to synchronize syspurpose attributes with server |
| 880 |
""" |
| 881 |
args = [SUBMAN_CMD, "status"] |
| 882 |
rc, stdout, stderr = self.module.run_command(args, check_rc=False) |
| 883 |
|
| 884 |
|
| 885 |
class RhsmPool: |
| 886 |
""" |
| 887 |
Convenience class for housing subscription information |
| 888 |
""" |
| 889 |
|
| 890 |
def __init__(self, module, **kwargs): |
| 891 |
self.module = module |
| 892 |
for k, v in kwargs.items(): |
| 893 |
setattr(self, k, v) |
| 894 |
|
| 895 |
def __str__(self): |
| 896 |
return str(self.__getattribute__("_name")) |
| 897 |
|
| 898 |
def get_pool_id(self): |
| 899 |
return getattr(self, "PoolId", self.PoolID) |
| 900 |
|
| 901 |
def get_quantity_used(self): |
| 902 |
return int(self.QuantityUsed) |
| 903 |
|
| 904 |
def subscribe(self): |
| 905 |
args = f"subscription-manager attach --pool {self.get_pool_id()}" |
| 906 |
rc, stdout, stderr = self.module.run_command(args, check_rc=True) |
| 907 |
return rc == 0 |
| 908 |
|
| 909 |
|
| 910 |
class RhsmPools: |
| 911 |
""" |
| 912 |
This class is used for manipulating pools subscriptions with RHSM |
| 913 |
""" |
| 914 |
|
| 915 |
def __init__(self, module, consumed=False): |
| 916 |
self.module = module |
| 917 |
self.products = self._load_product_list(consumed) |
| 918 |
|
| 919 |
def __iter__(self): |
| 920 |
return self.products.__iter__() |
| 921 |
|
| 922 |
def _load_product_list(self, consumed=False): |
| 923 |
""" |
| 924 |
Loads list of all available or consumed pools for system in data structure |
| 925 |
|
| 926 |
Args: |
| 927 |
consumed(bool): if True list consumed pools, else list available pools (default False) |
| 928 |
""" |
| 929 |
args = "subscription-manager list" |
| 930 |
if consumed: |
| 931 |
args += " --consumed" |
| 932 |
else: |
| 933 |
args += " --available" |
| 934 |
lang_env = dict(LANGUAGE="C", LC_ALL="C") |
| 935 |
rc, stdout, stderr = self.module.run_command(args, check_rc=True, environ_update=lang_env) |
| 936 |
|
| 937 |
products = [] |
| 938 |
for line in stdout.split("\n"): |
| 939 |
# Remove leading+trailing whitespace |
| 940 |
line = line.strip() |
| 941 |
# An empty line implies the end of a output group |
| 942 |
if len(line) == 0: |
| 943 |
continue |
| 944 |
# If a colon ':' is found, parse |
| 945 |
elif ":" in line: |
| 946 |
(key, value) = line.split(":", 1) |
| 947 |
key = key.strip().replace(" ", "") # To unify |
| 948 |
value = value.strip() |
| 949 |
if key in ["ProductName", "SubscriptionName"]: |
| 950 |
# Remember the name for later processing |
| 951 |
products.append(RhsmPool(self.module, _name=value, key=value)) |
| 952 |
elif products: |
| 953 |
# Associate value with most recently recorded product |
| 954 |
products[-1].__setattr__(key, value) |
| 955 |
# FIXME - log some warning? |
| 956 |
# else: |
| 957 |
# warnings.warn("Unhandled subscription key/value: %s/%s" % (key,value)) |
| 958 |
return products |
| 959 |
|
| 960 |
def filter_pools(self, regexp="^$"): |
| 961 |
""" |
| 962 |
Return a list of RhsmPools whose pool id matches the provided regular expression |
| 963 |
""" |
| 964 |
r = re.compile(regexp) |
| 965 |
for product in self.products: |
| 966 |
if r.search(product.get_pool_id()): |
| 967 |
yield product |
| 968 |
|
| 969 |
def filter_products(self, regexp="^$"): |
| 970 |
""" |
| 971 |
Return a list of RhsmPools whose product name matches the provided regular expression |
| 972 |
""" |
| 973 |
r = re.compile(regexp) |
| 974 |
for product in self.products: |
| 975 |
if r.search(product._name): |
| 976 |
yield product |
| 977 |
|
| 978 |
|
| 979 |
class SysPurpose: |
| 980 |
""" |
| 981 |
This class is used for reading and writing to syspurpose.json file |
| 982 |
""" |
| 983 |
|
| 984 |
SYSPURPOSE_FILE_PATH = "/etc/rhsm/syspurpose/syspurpose.json" |
| 985 |
|
| 986 |
ALLOWED_ATTRIBUTES = ["role", "usage", "service_level_agreement", "addons"] |
| 987 |
|
| 988 |
def __init__(self, path=None): |
| 989 |
""" |
| 990 |
Initialize class used for reading syspurpose json file |
| 991 |
""" |
| 992 |
self.path = path or self.SYSPURPOSE_FILE_PATH |
| 993 |
|
| 994 |
def update_syspurpose(self, new_syspurpose): |
| 995 |
""" |
| 996 |
Try to update current syspurpose with new attributes from new_syspurpose |
| 997 |
""" |
| 998 |
syspurpose = {} |
| 999 |
syspurpose_changed = False |
| 1000 |
for key, value in new_syspurpose.items(): |
| 1001 |
if key in self.ALLOWED_ATTRIBUTES: |
| 1002 |
if value is not None: |
| 1003 |
syspurpose[key] = value |
| 1004 |
elif key == "sync": |
| 1005 |
pass |
| 1006 |
else: |
| 1007 |
raise KeyError(f"Attribute: {key} not in list of allowed attributes: {self.ALLOWED_ATTRIBUTES}") |
| 1008 |
current_syspurpose = self._read_syspurpose() |
| 1009 |
if current_syspurpose != syspurpose: |
| 1010 |
syspurpose_changed = True |
| 1011 |
# Update current syspurpose with new values |
| 1012 |
current_syspurpose.update(syspurpose) |
| 1013 |
# When some key is not listed in new syspurpose, then delete it from current syspurpose |
| 1014 |
# and ignore custom attributes created by user (e.g. "foo": "bar") |
| 1015 |
for key in list(current_syspurpose): |
| 1016 |
if key in self.ALLOWED_ATTRIBUTES and key not in syspurpose: |
| 1017 |
del current_syspurpose[key] |
| 1018 |
self._write_syspurpose(current_syspurpose) |
| 1019 |
return syspurpose_changed |
| 1020 |
|
| 1021 |
def _write_syspurpose(self, new_syspurpose): |
| 1022 |
""" |
| 1023 |
This function tries to update current new_syspurpose attributes to |
| 1024 |
json file. |
| 1025 |
""" |
| 1026 |
with open(self.path, "w") as fp: |
| 1027 |
fp.write(json.dumps(new_syspurpose, indent=2, ensure_ascii=False, sort_keys=True)) |
| 1028 |
|
| 1029 |
def _read_syspurpose(self): |
| 1030 |
""" |
| 1031 |
Read current syspurpuse from json file. |
| 1032 |
""" |
| 1033 |
current_syspurpose = {} |
| 1034 |
try: |
| 1035 |
with open(self.path) as fp: |
| 1036 |
content = fp.read() |
| 1037 |
except OSError: |
| 1038 |
pass |
| 1039 |
else: |
| 1040 |
current_syspurpose = json.loads(content) |
| 1041 |
return current_syspurpose |
| 1042 |
|
| 1043 |
|
| 1044 |
def main(): |
| 1045 |
# Note: the default values for parameters are: |
| 1046 |
# 'type': 'str', 'default': None, 'required': False |
| 1047 |
# So there is no need to repeat these values for each parameter. |
| 1048 |
module = AnsibleModule( |
| 1049 |
argument_spec={ |
| 1050 |
"state": {"default": "present", "choices": ["present", "absent"]}, |
| 1051 |
"username": {}, |
| 1052 |
"password": {"no_log": True}, |
| 1053 |
"token": {"no_log": True}, |
| 1054 |
"server_hostname": {}, |
| 1055 |
"server_insecure": {}, |
| 1056 |
"server_prefix": {}, |
| 1057 |
"server_port": {}, |
| 1058 |
"rhsm_baseurl": {}, |
| 1059 |
"rhsm_repo_ca_cert": {}, |
| 1060 |
"auto_attach": {"type": "bool"}, |
| 1061 |
"activationkey": {"no_log": True}, |
| 1062 |
"org_id": {}, |
| 1063 |
"environment": {}, |
| 1064 |
"pool_ids": {"default": [], "type": "list", "elements": "raw"}, |
| 1065 |
"consumer_type": {}, |
| 1066 |
"consumer_name": {}, |
| 1067 |
"consumer_id": {}, |
| 1068 |
"force_register": {"default": False, "type": "bool"}, |
| 1069 |
"server_proxy_hostname": {}, |
| 1070 |
"server_proxy_scheme": {}, |
| 1071 |
"server_proxy_port": {}, |
| 1072 |
"server_proxy_user": {}, |
| 1073 |
"server_proxy_password": {"no_log": True}, |
| 1074 |
"release": {}, |
| 1075 |
"syspurpose": { |
| 1076 |
"type": "dict", |
| 1077 |
"options": { |
| 1078 |
"role": {}, |
| 1079 |
"usage": {}, |
| 1080 |
"service_level_agreement": {}, |
| 1081 |
"addons": {"type": "list", "elements": "str"}, |
| 1082 |
"sync": {"type": "bool", "default": False}, |
| 1083 |
}, |
| 1084 |
}, |
| 1085 |
}, |
| 1086 |
required_together=[ |
| 1087 |
["username", "password"], |
| 1088 |
["server_proxy_hostname", "server_proxy_port"], |
| 1089 |
["server_proxy_user", "server_proxy_password"], |
| 1090 |
], |
| 1091 |
mutually_exclusive=[ |
| 1092 |
["activationkey", "username"], |
| 1093 |
["activationkey", "token"], |
| 1094 |
["token", "username"], |
| 1095 |
["activationkey", "consumer_id"], |
| 1096 |
["activationkey", "environment"], |
| 1097 |
["activationkey", "auto_attach"], |
| 1098 |
], |
| 1099 |
required_if=[["force_register", True, ["username", "activationkey", "token"], True]], |
| 1100 |
) |
| 1101 |
|
| 1102 |
if getuid() != 0: |
| 1103 |
module.fail_json(msg="Interacting with subscription-manager requires root permissions ('become: true')") |
| 1104 |
|
| 1105 |
# Load RHSM configuration from file |
| 1106 |
rhsm = Rhsm(module) |
| 1107 |
|
| 1108 |
state = module.params["state"] |
| 1109 |
username = module.params["username"] |
| 1110 |
password = module.params["password"] |
| 1111 |
token = module.params["token"] |
| 1112 |
server_hostname = module.params["server_hostname"] |
| 1113 |
# TODO - no longer used? module.params["server_insecure"] |
| 1114 |
# TODO - no longer used? module.params["server_prefix"] |
| 1115 |
# TODO - no longer used? module.params["server_port"] |
| 1116 |
# TODO - no longer used? module.params["rhsm_baseurl"] |
| 1117 |
# TODO - no longer used? module.params["rhsm_repo_ca_cert"] |
| 1118 |
auto_attach = module.params["auto_attach"] |
| 1119 |
activationkey = module.params["activationkey"] |
| 1120 |
org_id = module.params["org_id"] |
| 1121 |
if activationkey and not org_id: |
| 1122 |
module.fail_json(msg="org_id is required when using activationkey") |
| 1123 |
environment = module.params["environment"] |
| 1124 |
pool_ids = {} |
| 1125 |
for value in module.params["pool_ids"]: |
| 1126 |
if isinstance(value, dict): |
| 1127 |
if len(value) != 1: |
| 1128 |
module.fail_json(msg="Unable to parse pool_ids option.") |
| 1129 |
pool_id, quantity = list(value.items())[0] |
| 1130 |
else: |
| 1131 |
pool_id, quantity = value, None |
| 1132 |
pool_ids[pool_id] = quantity |
| 1133 |
consumer_type = module.params["consumer_type"] |
| 1134 |
consumer_name = module.params["consumer_name"] |
| 1135 |
consumer_id = module.params["consumer_id"] |
| 1136 |
force_register = module.params["force_register"] |
| 1137 |
# TODO - no longer used? module.params["server_proxy_hostname"] |
| 1138 |
# TODO - no longer used? module.params["server_proxy_port"] |
| 1139 |
# TODO - no longer used? module.params["server_proxy_user"] |
| 1140 |
# TODO - no longer used? module.params["server_proxy_password"] |
| 1141 |
release = module.params["release"] |
| 1142 |
syspurpose = module.params["syspurpose"] |
| 1143 |
|
| 1144 |
global SUBMAN_CMD |
| 1145 |
SUBMAN_CMD = module.get_bin_path("subscription-manager", True) |
| 1146 |
|
| 1147 |
syspurpose_changed = False |
| 1148 |
if syspurpose is not None: |
| 1149 |
try: |
| 1150 |
syspurpose_changed = SysPurpose().update_syspurpose(syspurpose) |
| 1151 |
except Exception as err: |
| 1152 |
module.fail_json(msg=f"Failed to update syspurpose attributes: {err}") |
| 1153 |
|
| 1154 |
# Ensure system is registered |
| 1155 |
if state == "present": |
| 1156 |
# Cache the status of the system before the changes |
| 1157 |
was_registered = rhsm.is_registered |
| 1158 |
|
| 1159 |
# Register system |
| 1160 |
if was_registered and not force_register: |
| 1161 |
if syspurpose and "sync" in syspurpose and syspurpose["sync"] is True: |
| 1162 |
try: |
| 1163 |
rhsm.sync_syspurpose() |
| 1164 |
except Exception as e: |
| 1165 |
module.fail_json(msg=f"Failed to synchronize syspurpose attributes: {e}") |
| 1166 |
if pool_ids: |
| 1167 |
try: |
| 1168 |
result = rhsm.update_subscriptions_by_pool_ids(pool_ids) |
| 1169 |
except Exception as e: |
| 1170 |
module.fail_json(msg=f"Failed to update subscriptions for '{server_hostname}': {e}") |
| 1171 |
else: |
| 1172 |
module.exit_json(**result) |
| 1173 |
else: |
| 1174 |
if syspurpose_changed is True: |
| 1175 |
module.exit_json(changed=True, msg="Syspurpose attributes changed.") |
| 1176 |
else: |
| 1177 |
module.exit_json(changed=False, msg="System already registered.") |
| 1178 |
else: |
| 1179 |
if not username and not activationkey and not token: |
| 1180 |
module.fail_json( |
| 1181 |
msg="state is present but any of the following are missing: username, activationkey, token" |
| 1182 |
) |
| 1183 |
try: |
| 1184 |
rhsm.enable() |
| 1185 |
rhsm.configure(**module.params) |
| 1186 |
rhsm.register( |
| 1187 |
was_registered, |
| 1188 |
username, |
| 1189 |
password, |
| 1190 |
token, |
| 1191 |
auto_attach, |
| 1192 |
activationkey, |
| 1193 |
org_id, |
| 1194 |
consumer_type, |
| 1195 |
consumer_name, |
| 1196 |
consumer_id, |
| 1197 |
force_register, |
| 1198 |
environment, |
| 1199 |
release, |
| 1200 |
) |
| 1201 |
if syspurpose and "sync" in syspurpose and syspurpose["sync"] is True: |
| 1202 |
rhsm.sync_syspurpose() |
| 1203 |
if pool_ids: |
| 1204 |
subscribed_pool_ids = rhsm.subscribe_by_pool_ids(pool_ids) |
| 1205 |
else: |
| 1206 |
subscribed_pool_ids = [] |
| 1207 |
except Exception as e: |
| 1208 |
module.fail_json(msg=f"Failed to register with '{server_hostname}': {e}") |
| 1209 |
else: |
| 1210 |
module.exit_json( |
| 1211 |
changed=True, |
| 1212 |
msg=f"System successfully registered to '{server_hostname}'.", |
| 1213 |
subscribed_pool_ids=subscribed_pool_ids, |
| 1214 |
) |
| 1215 |
|
| 1216 |
# Ensure system is *not* registered |
| 1217 |
if state == "absent": |
| 1218 |
if not rhsm.is_registered: |
| 1219 |
module.exit_json(changed=False, msg="System already unregistered.") |
| 1220 |
else: |
| 1221 |
try: |
| 1222 |
rhsm.unregister() |
| 1223 |
except Exception as e: |
| 1224 |
module.fail_json(msg=f"Failed to unregister: {e}") |
| 1225 |
else: |
| 1226 |
module.exit_json(changed=True, msg=f"System successfully unregistered from {server_hostname}.") |
| 1227 |
|
| 1228 |
|
| 1229 |
if __name__ == "__main__": |
| 1230 |
main() |