| 1 |
#!/usr/bin/python |
| 2 |
# -*- coding: utf-8 -*- |
| 3 |
|
| 4 |
# Copyright: Contributors to the Ansible project |
| 5 |
# Apache License, Version 2.0 (see LICENSE or https://www.apache.org/licenses/LICENSE-2.0) |
| 6 |
|
| 7 |
|
| 8 |
from __future__ import (absolute_import, division, print_function) |
| 9 |
|
| 10 |
__metaclass__ = type |
| 11 |
|
| 12 |
DOCUMENTATION = r''' |
| 13 |
--- |
| 14 |
module: alpaca_system |
| 15 |
|
| 16 |
short_description: Manage ALPACA Operator systems via REST API |
| 17 |
|
| 18 |
version_added: "1.0.0" |
| 19 |
|
| 20 |
extends_documentation_fragment: |
| 21 |
- pcg.alpaca_operator.api_connection |
| 22 |
|
| 23 |
description: > |
| 24 |
This module allows you to create, update or delete ALPACA Operator systems using the REST API. |
| 25 |
In addition to general system properties, it supports assigning agents and variables. |
| 26 |
Communication is handled using token-based authentication. |
| 27 |
|
| 28 |
options: |
| 29 |
name: |
| 30 |
description: Unique name (hostname) of the system. |
| 31 |
version_added: '1.0.0' |
| 32 |
required: true |
| 33 |
type: str |
| 34 |
new_name: |
| 35 |
description: > |
| 36 |
Optional new name for the system. If the system specified in O(name) exists, |
| 37 |
it will be renamed to this value. If the system does not exist, a new system will |
| 38 |
be created using this value. |
| 39 |
version_added: '1.0.0' |
| 40 |
required: false |
| 41 |
type: str |
| 42 |
description: |
| 43 |
description: Description of the system. |
| 44 |
version_added: '1.0.0' |
| 45 |
required: false |
| 46 |
type: str |
| 47 |
magic_number: |
| 48 |
description: > |
| 49 |
Custom numeric field between 0 and 59. Can be used for arbitrary logic in your setup. |
| 50 |
version_added: '2.0.0' |
| 51 |
required: false |
| 52 |
type: int |
| 53 |
choices: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, |
| 54 |
20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, |
| 55 |
40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59] |
| 56 |
checks_disabled: |
| 57 |
description: Disable automatic system health checks. |
| 58 |
version_added: '2.0.0' |
| 59 |
required: false |
| 60 |
type: bool |
| 61 |
group_name: |
| 62 |
description: Name of the group to which the system should belong. |
| 63 |
version_added: '2.0.0' |
| 64 |
required: false |
| 65 |
type: str |
| 66 |
group_id: |
| 67 |
description: ID of the group (used if O(group_name) is not provided). |
| 68 |
version_added: '2.0.0' |
| 69 |
required: false |
| 70 |
type: int |
| 71 |
rfc_connection: |
| 72 |
description: Connection details for accessing the ALPACA Operator API. |
| 73 |
version_added: '2.0.0' |
| 74 |
required: false |
| 75 |
type: dict |
| 76 |
suboptions: |
| 77 |
type: |
| 78 |
description: Type of RFC connection. Can be V(none), V(instance), or V(messageServer). |
| 79 |
version_added: '1.0.0' |
| 80 |
required: false |
| 81 |
choices: [none, instance, messageServer] |
| 82 |
type: str |
| 83 |
host: |
| 84 |
description: Hostname or IP address of the RFC target system. |
| 85 |
version_added: '1.0.0' |
| 86 |
required: false |
| 87 |
type: str |
| 88 |
instance_number: |
| 89 |
description: Instance number of the RFC connection. |
| 90 |
version_added: '2.0.0' |
| 91 |
required: false |
| 92 |
type: int |
| 93 |
choices: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, |
| 94 |
20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, |
| 95 |
40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, |
| 96 |
60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, |
| 97 |
80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99] |
| 98 |
sid: |
| 99 |
description: SAP system ID (SID), consisting of 3 uppercase alphanumeric characters (A-Z, 0-9). |
| 100 |
version_added: '1.0.0' |
| 101 |
required: false |
| 102 |
type: str |
| 103 |
logon_group: |
| 104 |
description: Logon group (used with V(messageServer) type). |
| 105 |
version_added: '2.0.0' |
| 106 |
required: false |
| 107 |
type: str |
| 108 |
username: |
| 109 |
description: Username for RFC connection. |
| 110 |
version_added: '1.0.0' |
| 111 |
required: false |
| 112 |
type: str |
| 113 |
password: |
| 114 |
description: > |
| 115 |
Password for the RFC connection. |
| 116 |
|
| 117 |
IMPORTANT: If you specify the password in your playbook, the module will ALWAYS report a change (changed=true) on every run, |
| 118 |
even if nothing has changed. This happens because the API does not return the current password for security reasons, |
| 119 |
making it impossible to compare the desired password with the current one. The module cannot determine if the password |
| 120 |
needs to be updated or not. |
| 121 |
|
| 122 |
To maintain idempotency, comment out or remove the O(rfc_connection.password) parameter after the initial setup, and only uncomment it |
| 123 |
when you actually need to change the password. |
| 124 |
version_added: '1.0.0' |
| 125 |
required: false |
| 126 |
type: str |
| 127 |
client: |
| 128 |
description: Client for RFC connection. |
| 129 |
version_added: '1.0.0' |
| 130 |
required: false |
| 131 |
type: str |
| 132 |
sap_router_string: |
| 133 |
description: SAProuter string used to establish the RFC connection. |
| 134 |
version_added: '2.0.0' |
| 135 |
required: false |
| 136 |
type: str |
| 137 |
snc_enabled: |
| 138 |
description: Enable or disable SNC. |
| 139 |
version_added: '2.0.0' |
| 140 |
required: false |
| 141 |
type: bool |
| 142 |
agents: |
| 143 |
description: | |
| 144 |
A list of agents to assign to the system. |
| 145 |
|
| 146 |
Each entry must include: |
| 147 |
- `name` (string): The agent's name. |
| 148 |
|
| 149 |
version_added: '1.0.0' |
| 150 |
required: false |
| 151 |
type: list |
| 152 |
elements: dict |
| 153 |
suboptions: |
| 154 |
name: |
| 155 |
description: Name of the agent. |
| 156 |
version_added: '1.0.0' |
| 157 |
required: true |
| 158 |
type: str |
| 159 |
variables: |
| 160 |
description: | |
| 161 |
A list of variables to assign to the system. |
| 162 |
|
| 163 |
Each entry must include: |
| 164 |
- `name` (string): The name of the variable. |
| 165 |
- `value` (string): The value to assign to the variable. |
| 166 |
|
| 167 |
version_added: '1.0.0' |
| 168 |
required: false |
| 169 |
type: list |
| 170 |
elements: dict |
| 171 |
suboptions: |
| 172 |
name: |
| 173 |
description: Name of variable. |
| 174 |
version_added: '1.0.0' |
| 175 |
required: true |
| 176 |
type: str |
| 177 |
value: |
| 178 |
description: Value of variable. |
| 179 |
version_added: '1.0.0' |
| 180 |
required: true |
| 181 |
type: raw |
| 182 |
variables_mode: |
| 183 |
description: | |
| 184 |
Controls how variables are handled when updating the system. |
| 185 |
|
| 186 |
V(update): Add missing variables and update existing ones. |
| 187 |
V(replace): Add missing variables, update existing ones, and remove variables not defined in the playbook. |
| 188 |
|
| 189 |
version_added: '1.0.0' |
| 190 |
required: false |
| 191 |
default: update |
| 192 |
choices: [update, replace] |
| 193 |
type: str |
| 194 |
state: |
| 195 |
description: Desired state of the system. |
| 196 |
version_added: '1.0.0' |
| 197 |
required: false |
| 198 |
default: present |
| 199 |
choices: [present, absent] |
| 200 |
type: str |
| 201 |
|
| 202 |
requirements: |
| 203 |
- ALPACA Operator >= 5.6.0 |
| 204 |
|
| 205 |
attributes: |
| 206 |
check_mode: |
| 207 |
description: > |
| 208 |
Can run in check_mode and return changed status prediction without modifying target. |
| 209 |
Note: If O(rfc_connection.password) is specified, the module will always report changed=true, |
| 210 |
even in check mode, because the current password cannot be retrieved for comparison. |
| 211 |
support: full |
| 212 |
|
| 213 |
author: |
| 214 |
- Jan-Karsten Hansmeyer (@pcg) |
| 215 |
''' |
| 216 |
|
| 217 |
EXAMPLES = r''' |
| 218 |
- name: Ensure system exists |
| 219 |
pcg.alpaca_operator.alpaca_system: |
| 220 |
name: system01 |
| 221 |
description: My Test System |
| 222 |
magic_number: 42 |
| 223 |
checks_disabled: false |
| 224 |
group_name: test-group |
| 225 |
rfc_connection: |
| 226 |
type: instance |
| 227 |
host: test-host |
| 228 |
instance_number: 30 |
| 229 |
sid: ABC |
| 230 |
logon_group: my-logon-group |
| 231 |
username: rfc_myUser |
| 232 |
password: rfc_myPasswd |
| 233 |
client: 123 |
| 234 |
sap_router_string: rfc_SAPRouter |
| 235 |
snc_enabled: false |
| 236 |
agents: |
| 237 |
- name: localhost |
| 238 |
- name: testjan01-agent |
| 239 |
variables: |
| 240 |
- name: "<BKP_DATA_CLEANUP_INT>" |
| 241 |
value: "19" |
| 242 |
- name: "<BKP_DATA_CLEANUP_INT2>" |
| 243 |
value: "this is a string" |
| 244 |
- name: "<BKP_DATA_DEST2>" |
| 245 |
value: "11" |
| 246 |
state: present |
| 247 |
api_connection: |
| 248 |
host: localhost |
| 249 |
port: 8443 |
| 250 |
protocol: https |
| 251 |
username: secret |
| 252 |
password: secret |
| 253 |
tls_verify: false |
| 254 |
|
| 255 |
- name: Ensure system is absent |
| 256 |
pcg.alpaca_operator.alpaca_system: |
| 257 |
name: system01 |
| 258 |
state: absent |
| 259 |
api_connection: |
| 260 |
host: localhost |
| 261 |
port: 8443 |
| 262 |
protocol: https |
| 263 |
username: secret |
| 264 |
password: secret |
| 265 |
tls_verify: false |
| 266 |
|
| 267 |
- name: Rename an existing system |
| 268 |
pcg.alpaca_operator.alpaca_system: |
| 269 |
name: system01 |
| 270 |
new_name: system_renamed |
| 271 |
api_connection: |
| 272 |
host: localhost |
| 273 |
port: 8443 |
| 274 |
protocol: https |
| 275 |
username: secret |
| 276 |
password: secret |
| 277 |
tls_verify: false |
| 278 |
''' |
| 279 |
|
| 280 |
RETURN = r''' |
| 281 |
system: |
| 282 |
description: System details |
| 283 |
version_added: '1.0.0' |
| 284 |
type: dict |
| 285 |
returned: when state is present |
| 286 |
msg: |
| 287 |
description: Status message |
| 288 |
version_added: '1.0.0' |
| 289 |
type: str |
| 290 |
returned: always |
| 291 |
changed: |
| 292 |
description: Whether any change was made |
| 293 |
version_added: '1.0.0' |
| 294 |
type: bool |
| 295 |
returned: always |
| 296 |
''' |
| 297 |
|
| 298 |
from ansible_collections.pcg.alpaca_operator.plugins.module_utils._alpaca_api import get_token, api_call, lookup_resource, get_api_connection_argument_spec |
| 299 |
from ansible.module_utils.basic import AnsibleModule |
| 300 |
import re |
| 301 |
|
| 302 |
|
| 303 |
def get_system_details(api_url, headers, system_id, verify): |
| 304 |
"""Get system details by ID""" |
| 305 |
general = api_call("GET", "{0}/systems/{1}".format(api_url, system_id), headers=headers, verify=verify).json() |
| 306 |
agents = api_call("GET", "{0}/systems/{1}/agents".format(api_url, system_id), headers=headers, verify=verify).json() |
| 307 |
variables = api_call("GET", "{0}/systems/{1}/variables".format(api_url, system_id), headers=headers, verify=verify).json() |
| 308 |
|
| 309 |
# Clean up description: Current workaround for trailing whitespace returned by API --- #0001 |
| 310 |
if "description" in general: |
| 311 |
general["description"] = re.sub(r'\s+', ' ', general["description"]).strip() |
| 312 |
# ------------------------------------------------------------------------------------------ |
| 313 |
|
| 314 |
return {"general": general, "agents": agents, "variables": variables} |
| 315 |
|
| 316 |
|
| 317 |
def build_system_payload(params, current_system_details): |
| 318 |
""" |
| 319 |
Constructs a configuration payload by prioritizing values from the desired configuration |
| 320 |
dictionary. If a value is not provided in the desired configuration, the function falls |
| 321 |
back to using the corresponding value from the existing configuration (if available). |
| 322 |
|
| 323 |
Returns: |
| 324 |
dict: A combined configuration payload dictionary. |
| 325 |
""" |
| 326 |
|
| 327 |
payload = { |
| 328 |
"name": params.get('new_name', None) or params.get('name', None), |
| 329 |
"description": params.get('description', '').strip() if params.get('description', None) is not None else (current_system_details.get('general') or {}).get('description', '').strip() if current_system_details else None, #0001 |
| 330 |
"magicNumber": params.get('magic_number', None) if params.get('magic_number', None) is not None else (current_system_details.get('general') or {}).get('magicNumber', None) if current_system_details else None, |
| 331 |
"schedulingDisabled": params.get('checks_disabled', None) if params.get('checks_disabled', None) is not None else (current_system_details.get('general') or {}).get('schedulingDisabled', None) if current_system_details else None, |
| 332 |
"groupId": params.get('group_id', None) if params.get('group_id', None) is not None else (current_system_details.get('general') or {}).get('groupId', None) if current_system_details else None, |
| 333 |
"rfcConnection": { |
| 334 |
"type": params.get('rfc_connection', {}).get('type', None) if params.get('rfc_connection', {}).get('type', None) is not None else ((current_system_details.get('general') or {}).get('rfcConnection') or {}).get('type', None) if current_system_details else None, |
| 335 |
"host": params.get('rfc_connection', {}).get('host', None) if params.get('rfc_connection', {}).get('host', None) is not None else ((current_system_details.get('general') or {}).get('rfcConnection') or {}).get('host', None) if current_system_details else None, |
| 336 |
"instanceNumber": params.get('rfc_connection', {}).get('instance_number', None) if params.get('rfc_connection', {}).get('instance_number', None) is not None else ((current_system_details.get('general') or {}).get('rfcConnection') or {}).get('instanceNumber', None) if current_system_details else None, |
| 337 |
"sid": params.get('rfc_connection', {}).get('sid', None) if params.get('rfc_connection', {}).get('sid', None) is not None else ((current_system_details.get('general') or {}).get('rfcConnection') or {}).get('sid', None) if current_system_details else None, |
| 338 |
"logonGroup": params.get('rfc_connection', {}).get('logon_group', None) if params.get('rfc_connection', {}).get('logon_group', None) is not None else ((current_system_details.get('general') or {}).get('rfcConnection') or {}).get('logonGroup', None) if current_system_details else None, |
| 339 |
"username": params.get('rfc_connection', {}).get('username', None) if params.get('rfc_connection', {}).get('username', None) is not None else ((current_system_details.get('general') or {}).get('rfcConnection') or {}).get('username', None) if current_system_details else None, |
| 340 |
"client": params.get('rfc_connection', {}).get('client', None) if params.get('rfc_connection', {}).get('client', None) is not None else ((current_system_details.get('general') or {}).get('rfcConnection') or {}).get('client', None) if current_system_details else None, |
| 341 |
"sapRouterString": params.get('rfc_connection', {}).get('sap_router_string', None) if params.get('rfc_connection', {}).get('sap_router_string', None) is not None else ((current_system_details.get('general') or {}).get('rfcConnection') or {}).get('sapRouterString', None) if current_system_details else None, |
| 342 |
"sncEnabled": params.get('rfc_connection', {}).get('snc_enabled', None) if params.get('rfc_connection', {}).get('snc_enabled', None) is not None else ((current_system_details.get('general') or {}).get('rfcConnection') or {}).get('sncEnabled', None) if current_system_details else None |
| 343 |
} |
| 344 |
} |
| 345 |
|
| 346 |
# Only include 'password' if its present in params to avoid unwanted emptying #0002 |
| 347 |
if params.get('rfc_connection', {}).get('password', None) is not None: |
| 348 |
if 'rfcConnection' not in payload: |
| 349 |
payload['rfcConnection'] = {} |
| 350 |
payload['rfcConnection']['password'] = params['rfc_connection']['password'] |
| 351 |
|
| 352 |
return payload |
| 353 |
|
| 354 |
|
| 355 |
def build_variable_payload(api_url, headers, module, desired_vars): |
| 356 |
payload = [] |
| 357 |
for variable in desired_vars or []: |
| 358 |
api_variable = lookup_resource(api_url, headers, "variables", "name", variable['name'], module.params['api_connection']['tls_verify']) |
| 359 |
if not api_variable: |
| 360 |
module.fail_json(msg="Variable '{0}' not found. Please ensure variable exists first.".format(variable['name'])) |
| 361 |
|
| 362 |
payload.append({"id": api_variable.get('id'), "value": variable.get('value')}) |
| 363 |
|
| 364 |
return payload |
| 365 |
|
| 366 |
|
| 367 |
def main(): |
| 368 |
module = AnsibleModule( |
| 369 |
argument_spec=dict( |
| 370 |
name=dict(type='str', required=True), |
| 371 |
new_name=dict(type='str', required=False), |
| 372 |
description=dict(type='str', required=False), |
| 373 |
magic_number=dict(type='int', required=False, choices=list(range(0, 60))), |
| 374 |
checks_disabled=dict(type='bool', required=False), |
| 375 |
group_id=dict(type='int', required=False), |
| 376 |
group_name=dict(type='str', required=False), |
| 377 |
rfc_connection=dict( |
| 378 |
type='dict', |
| 379 |
required=False, |
| 380 |
options=dict( |
| 381 |
type=dict(type='str', required=False, choices=["none", "instance", "messageServer"]), |
| 382 |
host=dict(type='str', required=False), |
| 383 |
instance_number=dict(type='int', required=False, choices=list(range(0, 100))), |
| 384 |
sid=dict(type='str', required=False), |
| 385 |
logon_group=dict(type='str', required=False), |
| 386 |
username=dict(type='str', required=False, no_log=True), |
| 387 |
password=dict(type='str', required=False, no_log=True), |
| 388 |
client=dict(type='str', required=False), |
| 389 |
sap_router_string=dict(type='str', required=False), |
| 390 |
snc_enabled=dict(type='bool', required=False), |
| 391 |
) |
| 392 |
), |
| 393 |
agents=dict( |
| 394 |
type='list', |
| 395 |
elements='dict', |
| 396 |
required=False, |
| 397 |
options=dict( |
| 398 |
name=dict(type='str', required=True) |
| 399 |
) |
| 400 |
), |
| 401 |
variables=dict( |
| 402 |
type='list', |
| 403 |
elements='dict', |
| 404 |
required=False, |
| 405 |
options=dict( |
| 406 |
name=dict(type='str', required=True), |
| 407 |
value=dict(type='raw', required=True) |
| 408 |
) |
| 409 |
), |
| 410 |
variables_mode=dict(type='str', required=False, default='update', choices=['update', 'replace']), |
| 411 |
state=dict(type='str', required=False, default='present', choices=['present', 'absent']), |
| 412 |
api_connection=get_api_connection_argument_spec() |
| 413 |
), |
| 414 |
supports_check_mode=True, |
| 415 |
) |
| 416 |
|
| 417 |
api_url = "{0}://{1}:{2}/api".format(module.params['api_connection']['protocol'], module.params['api_connection']['host'], module.params['api_connection']['port']) |
| 418 |
token = get_token(api_url, module.params['api_connection']['username'], module.params['api_connection']['password'], module.params['api_connection']['tls_verify']) |
| 419 |
headers = {"Authorization": "Bearer {0}".format(token)} |
| 420 |
|
| 421 |
# Validate rfc SID against pattern |
| 422 |
if 'rfc_connection' not in module.params or module.params['rfc_connection'] is None: |
| 423 |
module.params['rfc_connection'] = {} |
| 424 |
|
| 425 |
try: |
| 426 |
rfc_sid = module.params.get('rfc_connection', {}).get('sid') if module.params.get('rfc_connection') else None |
| 427 |
if rfc_sid and not re.fullmatch(r'^[A-Z0-9]{3}$', rfc_sid): |
| 428 |
module.fail_json(msg="Invalid value for 'sid'. Must be exactly 3 uppercase alphanumeric characters (A-Z, 0-9).") |
| 429 |
except ImportError: |
| 430 |
if module: |
| 431 |
module.fail_json(msg="Python module 're' could not be found") |
| 432 |
raise |
| 433 |
|
| 434 |
current_system = lookup_resource(api_url, headers, "systems", "name", module.params['name'], module.params['api_connection']['tls_verify']) |
| 435 |
if not current_system and module.params.get('new_name', None): |
| 436 |
current_system = lookup_resource(api_url, headers, "systems", "name", module.params['new_name'], module.params['api_connection']['tls_verify']) |
| 437 |
|
| 438 |
system_details = get_system_details(api_url, headers, current_system['id'], module.params['api_connection']['tls_verify']) if current_system else None |
| 439 |
|
| 440 |
if module.params['state'] == 'present': |
| 441 |
# Lookup group id if needed |
| 442 |
if module.params.get('group_name'): |
| 443 |
group = lookup_resource(api_url, headers, "groups", "name", module.params['group_name'], module.params['api_connection']['tls_verify']) |
| 444 |
if not group: |
| 445 |
module.fail_json(msg="Group '{0}' not found.".format(module.params['group_name'])) |
| 446 |
module.params['group_id'] = group['id'] |
| 447 |
|
| 448 |
# Check if group_id is valid |
| 449 |
if module.params.get('group_id'): |
| 450 |
group = lookup_resource(api_url, headers, "groups", "id", module.params['group_id'], module.params['api_connection']['tls_verify']) |
| 451 |
if not group: |
| 452 |
module.fail_json(msg="Group with ID '{0}' not found. Please ensure group is created first.".format(module.params['group_id'])) |
| 453 |
|
| 454 |
# Build payload for general system configuration |
| 455 |
system_payload = build_system_payload(module.params, system_details) |
| 456 |
|
| 457 |
# Check if system already exists |
| 458 |
if current_system: |
| 459 |
# Compare current system configuration with the desired system configuration if it already exists) |
| 460 |
diff = {} |
| 461 |
for key in system_payload: |
| 462 |
if key not in ['rfc_connection']: |
| 463 |
if system_payload.get(key, None) != (system_details.get('general') or {}).get(key, None): |
| 464 |
if 'general' not in diff: |
| 465 |
diff['general'] = {} |
| 466 |
diff['general'][key] = { |
| 467 |
'current': (system_details.get('general') or {}).get(key, None), |
| 468 |
'desired': system_payload.get(key, None) |
| 469 |
} |
| 470 |
if key in ['rfc_connection']: |
| 471 |
for sub_key in system_payload.get(key, {}): |
| 472 |
if sub_key not in ['password']: #0002 |
| 473 |
if system_payload.get(key, {}).get(sub_key, None) != ((system_details.get('general') or {}).get(key) or {}).get(sub_key, None): |
| 474 |
if 'general' not in diff: |
| 475 |
diff['general'] = {} |
| 476 |
if key not in diff['general']: |
| 477 |
diff['general'][key] = {} |
| 478 |
diff['general'][key][sub_key] = { |
| 479 |
'current': ((system_details.get('general') or {}).get(key) or {}).get(sub_key, None), |
| 480 |
'desired': system_payload.get(key, {}).get(sub_key, None) |
| 481 |
} |
| 482 |
|
| 483 |
# Check if agent assignments need to be updated |
| 484 |
if 'agents' in module.params and module.params['agents'] is not None: |
| 485 |
desired_agents = sorted([agent['name'] for agent in module.params['agents'] if 'name' in agent]) if module.params.get('agents') else [] |
| 486 |
current_agents = sorted([agent['name'] for agent in system_details.get('agents', []) if 'name' in agent]) |
| 487 |
|
| 488 |
if desired_agents != current_agents: |
| 489 |
diff['agents'] = { |
| 490 |
'current': current_agents, |
| 491 |
'desired': desired_agents |
| 492 |
} |
| 493 |
|
| 494 |
# Check if variable assignments need to be updated |
| 495 |
if 'variables' in module.params and module.params['variables'] is not None: |
| 496 |
current_vars = sorted( |
| 497 |
[{"name": v['name'], "value": str(v['value'])} for v in system_details.get('variables', [])], |
| 498 |
key=lambda x: x['name'] |
| 499 |
) |
| 500 |
|
| 501 |
if module.params['variables_mode'] == 'replace': |
| 502 |
# Replace mode: use only the variables from module.params |
| 503 |
desired_vars = sorted( |
| 504 |
[{"name": v['name'], "value": str(v['value'])} for v in module.params['variables']], |
| 505 |
key=lambda x: x['name'] |
| 506 |
) if module.params.get('variables') else [] |
| 507 |
else: |
| 508 |
# Update mode: merge current_vars with module.params['variables'], giving priority to module.params |
| 509 |
merged_vars = {var['name']: var['value'] for var in current_vars} |
| 510 |
|
| 511 |
if module.params.get('variables'): |
| 512 |
for var in module.params['variables']: |
| 513 |
merged_vars[var['name']] = str(var['value']) |
| 514 |
|
| 515 |
desired_vars = sorted( |
| 516 |
[{"name": name, "value": value} for name, value in merged_vars.items()], |
| 517 |
key=lambda x: x['name'] |
| 518 |
) |
| 519 |
|
| 520 |
if desired_vars != current_vars: |
| 521 |
diff['variables'] = { |
| 522 |
'current': current_vars, |
| 523 |
'desired': desired_vars |
| 524 |
} |
| 525 |
|
| 526 |
if diff: |
| 527 |
if module.check_mode: |
| 528 |
module.exit_json(changed=True, msg="System would be updated.", changes=diff) |
| 529 |
|
| 530 |
# Update system |
| 531 |
if 'general' in diff: |
| 532 |
current_system = api_call(method="PUT", url="{0}/systems/{1}".format(api_url, system_details['general']['id']), headers=headers, json=system_payload, verify=module.params['api_connection']['tls_verify'], module=module, fail_msg="Failed to update system.").json() |
| 533 |
|
| 534 |
# Update agents |
| 535 |
if 'agents' in diff: |
| 536 |
# for system_agent in system_details['agents']: (When #0004 is resolved, this part can used again) |
| 537 |
# if system_agent['name'] not in desired_agents: |
| 538 |
# # Unassign agent if it's not in the desired list |
| 539 |
# agent = lookup_resource(api_url, headers, "agents", "hostname", system_agent['name'], module.params['api_connection']['tls_verify']) |
| 540 |
# if not agent: |
| 541 |
# module.fail_json(msg="Agent '{0}' not found. Please ensure agent exists.".format(param_agent['name'])) |
| 542 |
# api_call(method="DELETE", url="{0}/systems/{1}/agents/{2}".format(api_url, current_system['id'], agent['id']), headers=headers, verify=module.params['api_connection']['tls_verify'], module=module, fail_msg="Failed to unassign agent from system.") |
| 543 |
|
| 544 |
# Try to unassign agents as long as needed. Workaround for #0004 ---- |
| 545 |
while True: |
| 546 |
# Get currently assigned agents |
| 547 |
current_agents = api_call("GET", "{0}/systems/{1}/agents".format(api_url, current_system['id']), headers=headers, verify=module.params['api_connection']['tls_verify']).json() |
| 548 |
|
| 549 |
# Filter agents that should be unassigned |
| 550 |
agents_to_remove = [agent for agent in current_agents if agent['name'] not in desired_agents] |
| 551 |
|
| 552 |
# Break if there's nothing to remove |
| 553 |
if not agents_to_remove: |
| 554 |
break |
| 555 |
|
| 556 |
# Unassign agents |
| 557 |
for agent in agents_to_remove: |
| 558 |
api_agent = lookup_resource(api_url, headers, "agents", "hostname", agent['name'], module.params['api_connection']['tls_verify']) |
| 559 |
if not api_agent: |
| 560 |
module.fail_json(msg="Agent '{0}' not found. Please ensure agent exists.".format(agent['name'])) |
| 561 |
api_call(method="DELETE", url="{0}/systems/{1}/agents/{2}".format(api_url, current_system['id'], api_agent['id']), headers=headers, verify=module.params['api_connection']['tls_verify'], module=module, fail_msg="Failed to unassign agent from system.") |
| 562 |
# End of workaround for #0004 --------------------------------------- |
| 563 |
|
| 564 |
# Assign agents |
| 565 |
if module.params.get('agents'): |
| 566 |
for agent in module.params.get('agents', []) or []: |
| 567 |
if agent not in current_agents: |
| 568 |
# Assign desired agent |
| 569 |
api_agent = lookup_resource(api_url, headers, "agents", "hostname", agent['name'], module.params['api_connection']['tls_verify']) |
| 570 |
if not api_agent: |
| 571 |
module.fail_json(msg="Agent '{0}' not found. Please ensure agent exists first.".format(agent['name'])) |
| 572 |
api_call(method="POST", url="{0}/systems/{1}/agents".format(api_url, current_system['id']), headers=headers, json={'id': api_agent['id']}, verify=module.params['api_connection']['tls_verify'], module=module, fail_msg="Failed to assign agent to system.") |
| 573 |
|
| 574 |
# Update variables |
| 575 |
if 'variables' in diff: |
| 576 |
variable_payload = build_variable_payload(api_url, headers, module, desired_vars) |
| 577 |
api_call(method="POST", url="{0}/systems/{1}/variables".format(api_url, current_system['id']), headers=headers, json=variable_payload, verify=module.params['api_connection']['tls_verify'], module=module, fail_msg="Failed to assign variables to system.") |
| 578 |
|
| 579 |
module.exit_json(changed=True, msg="System updated.", api_response=current_system, changes=diff) |
| 580 |
|
| 581 |
module.exit_json(changed=False, msg="System already exists with the desired configuration", system_details=system_details) |
| 582 |
|
| 583 |
else: |
| 584 |
if module.check_mode: |
| 585 |
module.exit_json(changed=True, msg="System would be created.") |
| 586 |
|
| 587 |
# Create system |
| 588 |
current_system = api_call(method="POST", url="{0}/systems".format(api_url), headers=headers, json=system_payload, verify=module.params['api_connection']['tls_verify'], module=module, fail_msg="Failed to create system.").json() |
| 589 |
|
| 590 |
# Assign agents |
| 591 |
if module.params.get('agents'): |
| 592 |
for agent in module.params.get('agents', []) or []: |
| 593 |
# Assign desired agent |
| 594 |
api_agent = lookup_resource(api_url, headers, "agents", "hostname", agent['name'], module.params['api_connection']['tls_verify']) |
| 595 |
if not api_agent: |
| 596 |
module.fail_json(msg="Agent '{0}' not found. Please ensure agent exists first.".format(agent['name'])) |
| 597 |
api_call(method="POST", url="{0}/systems/{1}/agents".format(api_url, current_system['id']), headers=headers, json={'id': api_agent['id']}, verify=module.params['api_connection']['tls_verify'], module=module, fail_msg="Failed to assign agent to system.") |
| 598 |
|
| 599 |
# Assign variables |
| 600 |
variable_payload = build_variable_payload(api_url, headers, module, module.params.get('variables')) |
| 601 |
api_call(method="POST", url="{0}/systems/{1}/variables".format(api_url, current_system['id']), headers=headers, json=variable_payload, verify=module.params['api_connection']['tls_verify'], module=module, fail_msg="Failed to assign variables to system.") |
| 602 |
|
| 603 |
module.exit_json(changed=True, msg="System created.", api_response=current_system) |
| 604 |
|
| 605 |
elif module.params['state'] == 'absent': |
| 606 |
if not current_system: |
| 607 |
module.exit_json(changed=False, msg="System already absent.") |
| 608 |
|
| 609 |
if module.check_mode: |
| 610 |
module.exit_json(changed=True, msg="System would be deleted.", id=current_system['config']["id"]) |
| 611 |
|
| 612 |
# Unassign all agents (When #0004 is resolved, this part can used again) |
| 613 |
# for system_agent in system_details['agents']: |
| 614 |
# agent = lookup_resource(api_url, headers, "agents", "hostname", system_agent['name'], module.params['api_connection']['tls_verify']) |
| 615 |
# if not agent: |
| 616 |
# module.fail_json(msg="Agent '{0}' not found. Please ensure agent exists.".format(param_agent['name'])) |
| 617 |
# api_call(method="DELETE", url="{0}/systems/{1}/agents/{2}".format(api_url, current_system['id'], agent['id']), headers=headers, verify=module.params['api_connection']['tls_verify'], module=module, fail_msg="Failed to unassign agent from system") |
| 618 |
|
| 619 |
# Try to unassign agents as long as needed. Workaround for #0004 ---- |
| 620 |
while True: |
| 621 |
agents = api_call("GET", "{0}/systems/{1}/agents".format(api_url, current_system['id']), headers=headers, verify=module.params['api_connection']['tls_verify']).json() |
| 622 |
|
| 623 |
if not agents: |
| 624 |
break |
| 625 |
|
| 626 |
for system_agent in agents: |
| 627 |
agent = lookup_resource(api_url, headers, "agents", "hostname", system_agent['name'], module.params['api_connection']['tls_verify']) |
| 628 |
if not agent: |
| 629 |
module.fail_json(msg="Agent '{0}' not found. Please ensure agent exists.".format(system_agent['name'])) |
| 630 |
api_call(method="DELETE", url="{0}/systems/{1}/agents/{2}".format(api_url, current_system['id'], agent['id']), headers=headers, verify=module.params['api_connection']['tls_verify'], module=module, fail_msg="Failed to unassign agent from system") |
| 631 |
# End of workaround for #0004 --------------------------------------- |
| 632 |
|
| 633 |
# Unassign all variables |
| 634 |
api_call(method="POST", url="{0}/systems/{1}/variables".format(api_url, current_system['id']), headers=headers, json=[], verify=module.params['api_connection']['tls_verify'], module=module, fail_msg="Failed to unassign variables from system.") |
| 635 |
|
| 636 |
# Delete system |
| 637 |
api_call(method="DELETE", url="{0}/systems/{1}".format(api_url, current_system['id']), headers=headers, verify=module.params['api_connection']['tls_verify'], module=module, fail_msg="Failed to delete system") |
| 638 |
|
| 639 |
module.exit_json(changed=True, msg="System deleted.", system_details=system_details) |
| 640 |
|
| 641 |
module.exit_json(changed=True, msg="System state processed.") |
| 642 |
|
| 643 |
|
| 644 |
if __name__ == '__main__': |
| 645 |
main() |