Debian Codegraph @

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