Debian Codegraph @

ansible_collections/pcg/alpaca_operator/plugins/modules/alpaca_command.py

raw
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_command
15
16 short_description: Manage a single ALPACA Operator command 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 Ansible module manages a single ALPACA Operator command. It provides fine-grained control over individual command properties.
25 Use this module when you need to configure or modify one specific command, such as changing its timeout, toggling disabled, or setting a new schedule.
26 Each command is uniquely identified by the combination of its name (description) and the assigned agentHostname.
27 Note: Renaming a command or reassigning it to a different agent is not supported by this module, as these properties are used for identification.
28
29 Update behavior:
30 If the desired command already exists, only the fields required for unique identification need to be provided (i.e., either O(system.system_id) or O(system.system_name), and either O(command.agent_id) or O(command.agent_name).
31 Any options not explicitly set in the module call or the playbook will retain their existing values from the current configuration.
32
33 options:
34 system:
35 description: Dictionary containing system identification. Either O(system.system_id) or O(system.system_name) must be provided.
36 version_added: '1.0.0'
37 required: true
38 type: dict
39 suboptions:
40 system_id:
41 description: Numeric ID of the target system. Optional if O(system.system_name) is provided.
42 version_added: '2.0.0'
43 required: false
44 type: int
45 system_name:
46 description: Name of the target system. Optional if O(system.system_id) is provided.
47 version_added: '2.0.0'
48 required: false
49 type: str
50 command:
51 description: Definition of the desired command. The definition can include fields such as O(command.name), O(command.agent_id) or O(command.agent_name), O(command.process_id), O(command.parameters), O(command.schedule), O(command.history), O(command.escalation), etc.
52 version_added: '1.0.0'
53 required: true
54 type: dict
55 suboptions:
56 name:
57 description: Name or description of the command.
58 version_added: '1.0.0'
59 required: false
60 type: str
61 state:
62 description: Desired state of the command.
63 version_added: '1.0.0'
64 required: false
65 type: str
66 default: present
67 choices: [present, absent]
68 agent_id:
69 description: >
70 Numeric ID of the agent. Optional if O(command.agent_name) is provided.
71 Note: This agent must also be assigned to the corresponding system if the system is managed via Ansible.
72 version_added: '2.0.0'
73 required: false
74 type: int
75 agent_name:
76 description: >
77 Name of the agent. Optional if O(command.agent_id) is provided.
78 Note: This agent must also be assigned to the corresponding system if the system is managed via Ansible.
79 version_added: '2.0.0'
80 required: false
81 type: str
82 process_id:
83 description: >
84 ID of the process to be executed. Optional if O(command.process_central_id) is provided.
85 version_added: '2.0.0'
86 required: false
87 type: int
88 process_central_id:
89 description: >
90 Central ID / Global ID of the process to be executed. Optional if O(command.process_id) is provided.
91 version_added: '2.0.0'
92 required: false
93 type: int
94 parameters:
95 description: Parameters for the process.
96 version_added: '1.0.0'
97 required: false
98 type: str
99 parameters_needed:
100 description: Whether the execution of the command requires additional parameters.
101 version_added: '2.0.0'
102 required: false
103 type: bool
104 disabled:
105 description: Whether the command is currently disabled.
106 version_added: '1.0.0'
107 required: false
108 type: bool
109 critical:
110 description: Whether the command is marked as critical.
111 version_added: '1.0.0'
112 required: false
113 type: bool
114 schedule:
115 description: Scheduling configuration.
116 version_added: '1.0.0'
117 required: false
118 type: dict
119 suboptions:
120 period:
121 description: Scheduling period.
122 version_added: '1.0.0'
123 type: str
124 required: false
125 choices: [every_5min, one_per_day, hourly, manually, fixed_time, hourly_with_mn, every_minute, even_hours_with_mn, odd_hours_with_mn, even_hours, odd_hours, fixed_time_once, fixed_time_immediate, cron_expression, disabled, start_fixed_time_and_hourly_mn]
126 time:
127 description: Execution time in HH:mm:ss. Required when O(command.schedule.period) is V(fixed_time), V(fixed_time_once), or V(start_fixed_time_and_hourly_mn).
128 version_added: '1.0.0'
129 type: str
130 required: false
131 cron_expression:
132 description: Quartz-compatible cron expression. Required when O(command.schedule.period) is V(cron_expression).
133 version_added: '2.0.0'
134 type: str
135 required: false
136 days_of_week:
137 description: List of weekdays for execution.
138 version_added: '2.0.0'
139 type: list
140 elements: str
141 required: false
142 choices: [monday, tuesday, wednesday, thursday, friday, saturday, sunday]
143 history:
144 description: Command history retention settings.
145 version_added: '1.0.0'
146 required: false
147 type: dict
148 suboptions:
149 document_all_runs:
150 description: Whether to document all executions.
151 version_added: '2.0.0'
152 type: bool
153 required: false
154 retention:
155 description: Retention time in seconds.
156 version_added: '1.0.0'
157 type: int
158 required: false
159 auto_deploy:
160 description: Whether to automatically deploy the command.
161 version_added: '2.0.0'
162 required: false
163 type: bool
164 timeout:
165 description: Timeout configuration for command execution.
166 version_added: '1.0.0'
167 required: false
168 type: dict
169 suboptions:
170 type:
171 description: Type of timeout. Can be V(none), V(default), or V(custom).
172 version_added: '1.0.0'
173 type: str
174 required: false
175 choices: [none, default, custom]
176 value:
177 description: Timeout value in seconds (for V(custom) type).
178 version_added: '1.0.0'
179 type: int
180 required: false
181 escalation:
182 description: Escalation configuration.
183 version_added: '1.0.0'
184 required: false
185 type: dict
186 suboptions:
187 mail_enabled:
188 description: Whether email alerts are enabled.
189 version_added: '2.0.0'
190 type: bool
191 required: false
192 sms_enabled:
193 description: Whether SMS alerts are enabled.
194 version_added: '2.0.0'
195 type: bool
196 required: false
197 mail_address:
198 description: Email address for alerts.
199 version_added: '2.0.0'
200 type: str
201 required: false
202 sms_address:
203 description: SMS number for alerts.
204 version_added: '2.0.0'
205 type: str
206 required: false
207 min_failure_count:
208 description: Minimum number of failures before escalation.
209 version_added: '2.0.0'
210 type: int
211 required: false
212 triggers:
213 description: Trigger types for escalation.
214 version_added: '1.0.0'
215 type: dict
216 required: false
217 suboptions:
218 every_change:
219 description: Currently no description available
220 version_added: '2.0.0'
221 type: bool
222 required: false
223 to_red:
224 description: Currently no description available
225 version_added: '2.0.0'
226 type: bool
227 required: false
228 to_yellow:
229 description: Currently no description available
230 version_added: '2.0.0'
231 type: bool
232 required: false
233 to_green:
234 description: Currently no description available
235 version_added: '2.0.0'
236 type: bool
237 required: false
238
239 requirements:
240 - ALPACA Operator >= 5.6.0
241
242 attributes:
243 check_mode:
244 description: Can run in check_mode and return changed status prediction without modifying target.
245 support: full
246
247 author:
248 - Jan-Karsten Hansmeyer (@pcg)
249 '''
250
251 EXAMPLES = r'''
252 - name: Ensure a specific system command exist
253 pcg.alpaca_operator.alpaca_command:
254 system:
255 system_name: system01
256 command:
257 name: "BKP: DB log sync"
258 state: present
259 agent_name: agent01
260 parameters: "-p GLTarch -s <BKP_LOG_SRC> -l 4 -d <BKP_LOG_DEST1> -r <BKP_LOG_DEST2> -b <BKP_LOG_CLEANUP_INT> -t <BKP_LOG_CLEANUP_INT2> -h DB_HOST"
261 process_id: 801
262 schedule:
263 period: manually
264 time: "01:00:00"
265 days_of_week:
266 - monday
267 - sunday
268 parameters_needed: false
269 disabled: false
270 critical: true
271 history:
272 document_all_runs: true
273 retention: 900
274 auto_deploy: false
275 timeout:
276 type: default
277 value: 30
278 escalation:
279 mail_enabled: true
280 sms_enabled: true
281 mail_address: "[email protected]"
282 sms_address: "0123456789"
283 min_failure_count: 1
284 triggers:
285 every_change: true
286 to_red: false
287 to_yellow: false
288 to_green: true
289 api_connection:
290 host: "{{ ALPACA_Operator_API_Host }}"
291 protocol: "{{ ALPACA_Operator_API_Protocol }}"
292 port: "{{ ALPACA_Operator_API_Port }}"
293 username: "{{ ALPACA_Operator_API_Username }}"
294 password: "{{ ALPACA_Operator_API_Password }}"
295 tls_verify: "{{ ALPACA_Operator_API_Validate_Certs }}"
296
297 - name: Delete a specific command
298 pcg.alpaca_operator.alpaca_command:
299 system:
300 system_name: system01
301 command:
302 name: "BKP: DB log sync"
303 agent_name: agent01
304 state: absent
305 api_connection:
306 host: "{{ ALPACA_Operator_API_Host }}"
307 protocol: "{{ ALPACA_Operator_API_Protocol }}"
308 port: "{{ ALPACA_Operator_API_Port }}"
309 username: "{{ ALPACA_Operator_API_Username }}"
310 password: "{{ ALPACA_Operator_API_Password }}"
311 tls_verify: "{{ ALPACA_Operator_API_Validate_Certs }}"
312 '''
313
314 RETURN = r'''
315 msg:
316 description: Status message describing what the module did
317 version_added: '1.0.0'
318 returned: always
319 type: str
320 sample: Command updated in system 42.
321
322 changed:
323 description: Whether any changes were made
324 version_added: '1.0.0'
325 returned: always
326 type: bool
327
328 changes:
329 description: >
330 Dictionary containing the differences between the current and desired command configuration.
331 Only returned when a change is detected or would occur in check mode.
332 version_added: '1.0.0'
333 returned: when changes are detected (or would be applied in check_mode)
334 type: dict
335 contains:
336 parameters:
337 description: Changed parameters of the command (if any)
338 version_added: '1.0.0'
339 type: dict
340 sample:
341 current: "-p foo -s A -d B"
342 desired: "-p foo -s A -d B -t X"
343 schedule:
344 description: Changed schedule section (if any)
345 version_added: '1.0.0'
346 type: dict
347 sample:
348 period:
349 current: "manually"
350 desired: "every_minute"
351 escalation:
352 description: Changed escalation section (if any)
353 version_added: '1.0.0'
354 type: dict
355 sample:
356 min_failure_count:
357 current: 0
358 desired: 1
359
360 payload:
361 description: Full payload that would be sent to the API (in check_mode) or that was sent (when changed)
362 version_added: '1.0.0'
363 returned: when state is present and change occurred or would occur
364 type: dict
365
366 command:
367 description: Information about the deleted command
368 version_added: '1.0.0'
369 returned: when state=absent and command was deleted
370 type: dict
371 sample:
372 id: 123
373 name: "Backup Job"
374 agentHostname: "agent-01"
375 '''
376
377 from ansible_collections.pcg.alpaca_operator.plugins.module_utils._alpaca_api import api_call, get_token, lookup_resource, lookup_processId, get_api_connection_argument_spec
378 from ansible.module_utils.basic import AnsibleModule
379
380
381 def build_payload(desired_command, system_command):
382 """
383 Constructs a configuration payload by prioritizing values from the desired configuration
384 dictionary. If a value is not provided in the desired configuration, the function falls
385 back to using the corresponding value from the existing configuration (if available).
386
387 Parameters:
388 desired_command (dict): A dictionary containing the desired configuration values.
389 system_command (dict): A dictionary with existing configuration values.
390
391 Returns:
392 dict: A combined configuration payload dictionary.
393 """
394 payload = {
395 "name": desired_command.get('name', None) if desired_command.get('name') is not None else system_command.get('name', None),
396 "agentId": desired_command.get('agent_id', None) if desired_command.get('agent_id') is not None else system_command.get('agentId', 0),
397 "processId": desired_command.get('process_id', None) if desired_command.get('process_id') is not None else system_command.get('processId', 0),
398 "parameters": desired_command.get('parameters', None) if desired_command.get('parameters') is not None else system_command.get('parameters', None),
399 "schedule": {
400 "period": (desired_command.get('schedule') or {}).get('period', None) if (desired_command.get('schedule') or {}).get('period', None) is not None else (system_command.get('schedule') or {}).get('period', 'undefined'),
401 "time": (desired_command.get('schedule') or {}).get('time', None) if (desired_command.get('schedule') or {}).get('time', None) is not None else (system_command.get('schedule') or {}).get('time', None),
402 "cronExpression": (desired_command.get('schedule') or {}).get('cron_expression', None) if (desired_command.get('schedule') or {}).get('cron_expression', None) and (desired_command.get('schedule') or {}).get('period', None) == 'cron_expression' else (system_command.get('schedule') or {}).get('cronExpression', ''),
403 "daysOfWeek": sorted(
404 (desired_command.get('schedule') or {}).get('days_of_week', []) if (desired_command.get('schedule') or {}).get('days_of_week', None) is not None else (system_command.get('schedule') or {}).get('daysOfWeek', []),
405 key=lambda x: ['monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday'].index(x.lower())
406 )
407 },
408 "parametersNeeded": desired_command.get('parameters_needed', None) if desired_command.get('parameters_needed') is not None else system_command.get('parametersNeeded', True),
409 "disabled": desired_command.get('disabled', None) if desired_command.get('disabled') is not None else system_command.get('disabled', True),
410 "critical": desired_command.get('critical', None) if desired_command.get('critical') is not None else system_command.get('critical', True),
411 "history": {
412 "documentAllRuns": (desired_command.get('history') or {}).get('document_all_runs', None) if (desired_command.get('history') or {}).get('document_all_runs', None) is not None else (system_command.get('history') or {}).get('documentAllRuns', True),
413 "retention": (desired_command.get('history') or {}).get('retention', None) if (desired_command.get('history') or {}).get('retention', None) is not None else (system_command.get('history') or {}).get('retention', 0)
414 },
415 "autoDeploy": desired_command.get('auto_deploy', None) if desired_command.get('auto_deploy') is not None else system_command.get('autoDeploy', True),
416 "timeout": {
417 "type": (desired_command.get('timeout') or {}).get('type', None).upper() if (desired_command.get('timeout') or {}).get('type', None) is not None else (system_command.get('timeout') or {}).get('type', 'None').upper(),
418 "value": (desired_command.get('timeout') or {}).get('value', None) if (desired_command.get('timeout') or {}).get('value', None) is not None else (system_command.get('timeout') or {}).get('value', 0)
419 },
420 "escalation": {
421 "mailEnabled": (desired_command.get('escalation') or {}).get('mail_enabled', None) if (desired_command.get('escalation') or {}).get('mail_enabled', None) is not None else (system_command.get('escalation') or {}).get('mailEnabled', False),
422 "smsEnabled": (desired_command.get('escalation') or {}).get('sms_enabled', None) if (desired_command.get('escalation') or {}).get('sms_enabled', None) is not None else (system_command.get('escalation') or {}).get('smsEnabled', False),
423 "mailAddress": (desired_command.get('escalation') or {}).get('mail_address', None) if (desired_command.get('escalation') or {}).get('mail_address', None) is not None else (system_command.get('escalation') or {}).get('mailAddress', None),
424 "smsAddress": (desired_command.get('escalation') or {}).get('sms_address', None) if (desired_command.get('escalation') or {}).get('sms_address', None) is not None else (system_command.get('escalation') or {}).get('smsAddress', None),
425 "minFailureCount": (desired_command.get('escalation') or {}).get('min_failure_count', None) if (desired_command.get('escalation') or {}).get('min_failure_count', None) is not None else (system_command.get('escalation') or {}).get('minFailureCount', 0),
426 "triggers": {
427 "everyChange": (desired_command.get('escalation') or {}).get('triggers', {}).get('every_change', None) if (desired_command.get('escalation') or {}).get('triggers', {}).get('every_change', None) is not None else (system_command.get('escalation') or {}).get('triggers', {}).get('everyChange', True),
428 "toRed": (desired_command.get('escalation') or {}).get('triggers', {}).get('to_red', None) if (desired_command.get('escalation') or {}).get('triggers', {}).get('to_red', None) is not None else (system_command.get('escalation') or {}).get('triggers', {}).get('toRed', True),
429 "toYellow": (desired_command.get('escalation') or {}).get('triggers', {}).get('to_yellow', None) if (desired_command.get('escalation') or {}).get('triggers', {}).get('to_yellow', None) is not None else (system_command.get('escalation') or {}).get('triggers', {}).get('toYellow', True),
430 "toGreen": (desired_command.get('escalation') or {}).get('triggers', {}).get('to_green', None) if (desired_command.get('escalation') or {}).get('triggers', {}).get('to_green', None) is not None else (system_command.get('escalation') or {}).get('triggers', {}).get('toGreen', True)
431 }
432 }
433 }
434
435 if (payload.get('timeout') or {}).get('type') == 'NONE' or (payload.get('timeout') or {}).get('type') == 'DEFAULT':
436 payload['timeout']['value'] = None
437
438 return payload
439
440
441 def main():
442 module = AnsibleModule(
443 argument_spec=dict(
444 system=dict(
445 type='dict',
446 required=True,
447 options=dict(
448 system_id=dict(type='int', required=False),
449 system_name=dict(type='str', required=False)
450 )
451 ),
452 command=dict(
453 type='dict',
454 required=True,
455 options=dict(
456 name=dict(type='str', required=False),
457 agent_id=dict(type='int', required=False),
458 agent_name=dict(type='str', required=False),
459 process_id=dict(type='int', required=False),
460 process_central_id=dict(type='int', required=False),
461 parameters=dict(type='str', required=False),
462 schedule=dict(
463 type='dict',
464 required=False,
465 options=dict(
466 period=dict(type='str', required=False, choices=[
467 'every_5min', 'one_per_day', 'hourly', 'manually', 'fixed_time',
468 'hourly_with_mn', 'every_minute', 'even_hours_with_mn', 'odd_hours_with_mn',
469 'even_hours', 'odd_hours', 'fixed_time_once', 'fixed_time_immediate',
470 'cron_expression', 'disabled', 'start_fixed_time_and_hourly_mn'
471 ]),
472 time=dict(type='str', required=False),
473 cron_expression=dict(type='str', required=False),
474 days_of_week=dict(type='list', required=False, elements='str', choices=[
475 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday'
476 ])
477 )
478 ),
479 parameters_needed=dict(type='bool', required=False),
480 disabled=dict(type='bool', required=False),
481 critical=dict(type='bool', required=False),
482 history=dict(
483 type='dict',
484 required=False,
485 options=dict(
486 document_all_runs=dict(type='bool', required=False),
487 retention=dict(type='int', required=False)
488 )
489 ),
490 auto_deploy=dict(type='bool', required=False),
491 timeout=dict(
492 type='dict',
493 required=False,
494 options=dict(
495 type=dict(type='str', required=False, choices=[
496 'none', 'default', 'custom'
497 ]),
498 value=dict(type='int', required=False)
499 )
500 ),
501 escalation=dict(
502 type='dict',
503 required=False,
504 options=dict(
505 mail_enabled=dict(type='bool', required=False),
506 sms_enabled=dict(type='bool', required=False),
507 mail_address=dict(type='str', required=False),
508 sms_address=dict(type='str', required=False),
509 min_failure_count=dict(type='int', required=False),
510 triggers=dict(
511 type='dict',
512 required=False,
513 options=dict(
514 every_change=dict(type='bool', required=False),
515 to_red=dict(type='bool', required=False),
516 to_yellow=dict(type='bool', required=False),
517 to_green=dict(type='bool', required=False)
518 )
519 )
520 )
521 ),
522 state=dict(type='str', required=False, default='present', choices=['present', 'absent'])
523 )
524 ),
525 api_connection=get_api_connection_argument_spec()
526 ),
527 supports_check_mode=True,
528 )
529
530 api_url = "{0}://{1}:{2}/api".format(module.params['api_connection']['protocol'], module.params['api_connection']['host'], module.params['api_connection']['port'])
531 token = get_token(api_url, module.params['api_connection']['username'], module.params['api_connection']['password'], module.params['api_connection']['tls_verify'])
532 headers = {"Authorization": "Bearer {0}".format(token)}
533 command_payload = None
534
535 # Check if either a system ID or a system name is provided
536 if not module.params.get('system', {}).get('system_name', None) and not module.params.get('system', {}).get('system_id', None):
537 module.fail_json(msg="Either a system_name or system_id must be provided")
538
539 # Resolve system id if needed
540 if module.params.get('system', {}).get('system_name', None):
541 system = lookup_resource(api_url, headers, "systems", "name", module.params['system']['system_name'], module.params['api_connection']['tls_verify'])
542 if not system and module.params.get('command', {}).get('state') == "present":
543 module.fail_json(msg="System '{0}' not found.".format(module.params['system']['system_name']))
544 elif not system and module.params.get('command', {}).get('state') == "absent":
545 module.exit_json(changed=False, msg="Command already absent because system was not found.")
546 module.params['system']['system_id'] = system['id']
547
548 # Check if system_id is valid
549 if module.params.get('system', {}).get('system_id', None):
550 system = lookup_resource(api_url, headers, "systems", "id", module.params['system']['system_id'], module.params['api_connection']['tls_verify'])
551 if not system and module.params.get('command', {}).get('state') == "present":
552 module.fail_json(msg="System with ID '{0}' not found. Please ensure system is created first.".format(module.params['system']['system_id']))
553 elif not system and module.params.get('command', {}).get('state') == "absent":
554 module.exit_json(changed=False, msg="Command already absent because system was not found.")
555
556 # Check if either a agent ID or a agent name is provided
557 if not module.params.get('command', {}).get('agent_name', None) and not module.params.get('command', {}).get('agent_id', None):
558 module.fail_json(msg="Either agent_name or agent_id must be provided")
559
560 # Resolve agent id if needed
561 if module.params.get('command', {}).get('agent_name', None):
562 agent = lookup_resource(api_url, headers, "agents", "hostname", module.params['command']['agent_name'], module.params['api_connection']['tls_verify'])
563 if not agent and module.params.get('command', {}).get('state') == "present":
564 module.fail_json(msg="Agent '{0}' not found.".format(module.params['command']['agent_name']))
565 elif not agent and module.params.get('command', {}).get('state') == "absent":
566 module.exit_json(changed=False, msg="Command already absent because agent was not found.")
567 module.params['command']['agent_id'] = agent['id']
568
569 # Check if agent_id is valid
570 if module.params.get('command', {}).get('agent_id', None):
571 agent = lookup_resource(api_url, headers, "agents", "id", module.params['command']['agent_id'], module.params['api_connection']['tls_verify'])
572 if not agent and module.params.get('command', {}).get('state') == "present":
573 module.fail_json(msg="Agent with ID '{0}' not found. Please ensure agent is created first.".format(module.params['command']['agent_id']))
574 elif not agent and module.params.get('command', {}).get('state') == "absent":
575 module.exit_json(changed=False, msg="Command already absent because agent was not found.")
576
577 # Check if either a process ID or the processes central ID is provided
578 if not module.params.get('command', {}).get('process_central_id', None) and not module.params.get('command', {}).get('process_id', None) and module.params.get('command', {}).get('state') == "present":
579 module.fail_json(msg="Either process_central_id or process_id must be provided")
580
581 # Resolve process_id if needed
582 if module.params.get('command', {}).get('process_central_id', None) and not module.params.get('command', {}).get('process_id', None) and module.params.get('command', {}).get('state') == "present":
583 process_id = lookup_processId(api_url, headers, "globalId", module.params.get('command', {}).get('process_central_id'), module.params['api_connection']['tls_verify'],)
584 if not process_id:
585 module.fail_json(msg="Process ID lookup for Central ID '{0}' not found".format(module.params['command']['process_central_id']))
586 module.params['command']['process_id'] = process_id
587
588 # Get currently configured system commands
589 system_commands = api_call("GET", "{0}/systems/{1}/commands".format(api_url, module.params['system']['system_id']), headers=headers, verify=module.params['api_connection']['tls_verify']).json()
590
591 # Check, if command already exists using a combination of 'agentHostname' and 'name' for a comparison (the description field of the command in the ALPACA Operator UI) for the identification
592 if system_commands:
593 for system_command in system_commands:
594 if system_command.get('name', None) == module.params.get('command', {}).get('name', None) and system_command.get('agentHostname', None) == agent.get('hostname', None):
595 system_command = api_call("GET", "{0}/systems/{1}/commands/{2}".format(api_url, module.params['system']['system_id'], system_command.get('id', None)), headers=headers, verify=module.params['api_connection']['tls_verify']).json()
596 if not system_command:
597 module.fail_json(msg="Failed to retrieve command details of command ID '{0}' in system ID '{1}'".format(module.params['command']['agent_id'], module.params['system']['system_id']))
598 break
599 else:
600 system_command = {}
601 else:
602 system_command = {}
603
604 if module.params['command']['state'] == 'present':
605 command_payload = build_payload(module.params.get('command', {}), system_command)
606
607 if system_command:
608 # Compare current command configuration with the desired command configuration if it already exists
609 diff = {}
610 for key in command_payload:
611 if key not in ['schedule', 'history', 'escalation', 'timeout']:
612 if command_payload.get(key, None) != system_command.get(key, None):
613 diff[key] = {
614 'current': system_command.get(key, None),
615 'desired': command_payload.get(key, None)
616 }
617 if key in ['schedule', 'history', 'escalation', 'timeout']:
618 for sub_key in command_payload.get(key, {}):
619 if sub_key not in ['triggers']:
620 if (command_payload.get(key) or {}).get(sub_key, None) != (system_command.get(key) or {}).get(sub_key, None):
621 if key not in diff:
622 diff[key] = {}
623 diff[key][sub_key] = {
624 'current': (system_command.get(key) or {}).get(sub_key, None),
625 'desired': (command_payload.get(key) or {}).get(sub_key, None)
626 }
627 if sub_key in ['triggers']:
628 for sub_sub_key in (command_payload.get(key) or {}).get(sub_key, {}):
629 if ((command_payload.get(key) or {}).get(sub_key) or {}).get(sub_sub_key, {}) != ((system_command.get(key) or {}).get(sub_key) or {}).get(sub_sub_key, None):
630 if key not in diff:
631 diff[key] = {}
632 if sub_key not in diff.get(key, {}):
633 diff[key][sub_key] = {}
634 diff[key][sub_key][sub_sub_key] = {
635 'current': ((system_command.get(key) or {}).get(sub_key) or {}).get(sub_sub_key, None),
636 'desired': ((command_payload.get(key) or {}).get(sub_key) or {}).get(sub_sub_key, None)
637 }
638
639 if diff:
640 if module.check_mode:
641 module.exit_json(changed=True, msg="Command would be updated in system {0}.".format(module.params['system']['system_id']), changes=diff, payload=command_payload)
642
643 # Update command
644 api_call("PUT", "{0}/systems/{1}/commands/{2}".format(api_url, module.params['system']['system_id'], system_command['id']), headers=headers, json=command_payload, verify=module.params['api_connection']['tls_verify'], module=module, fail_msg="Failed to update command")
645 module.exit_json(changed=True, msg="Command updated in system {0}.".format(module.params['system']['system_id']), changes=diff)
646
647 module.exit_json(changed=False, msg="Command already exists with the desired configuration in system {0}.".format(module.params['system']['system_id']))
648
649 # Create command if it does not exist already
650 if module.check_mode:
651 module.exit_json(changed=True, msg="Command would be created in system {0}.".format(module.params['system']['system_id']), payload=command_payload)
652
653 api_call("POST", "{0}/systems/{1}/commands".format(api_url, module.params['system']['system_id']), headers=headers, json=command_payload, verify=module.params['api_connection']['tls_verify'], module=module, fail_msg="Failed to create command")
654 module.exit_json(changed=True, msg="Command created in system {0}.".format(module.params['system']['system_id']), payload=command_payload)
655
656 elif module.params['command']['state'] == 'absent':
657 if system_command:
658 if module.check_mode:
659 module.exit_json(changed=True, msg="Command would be deleted from system {0}.".format(module.params['system']['system_id']), payload=command_payload)
660
661 # Delete command
662 api_call("DELETE", "{0}/systems/{1}/commands/{2}".format(api_url, module.params['system']['system_id'], system_command['id']), headers=headers, verify=module.params['api_connection']['tls_verify'], module=module, fail_msg="Failed to update command")
663 module.exit_json(changed=True, msg="Command delete from system {0}.".format(module.params['system']['system_id']), command=system_command)
664
665 module.exit_json(changed=False, msg="Command already absent.")
666
667 module.exit_json(changed=False, msg="Command state processed.")
668
669
670 if __name__ == '__main__':
671 main()