-
Notifications
You must be signed in to change notification settings - Fork 1.7k
/
AWSSystemManager.py
1598 lines (1401 loc) · 61 KB
/
AWSSystemManager.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import re
from typing import TYPE_CHECKING, Any, NamedTuple, NoReturn
import demistomock as demisto
from AWSApiModule import *
from CommonServerPython import *
# The following imports are used only for type hints and autocomplete.
# They are not used at runtime, and not exist in the docker image.
if TYPE_CHECKING:
from mypy_boto3_ssm.client import SSMClient
from mypy_boto3_ssm.literals import ResourceTypeForTaggingType
from mypy_boto3_ssm.type_defs import (
DescribeAutomationExecutionsRequestRequestTypeDef,
DocumentDescriptionTypeDef,
GetInventoryRequestRequestTypeDef,
ListAssociationsRequestRequestTypeDef,
ListDocumentsRequestRequestTypeDef,
)
""" CONSTANTS """
RESOURCE_TYPE_MAP: dict[str, "ResourceTypeForTaggingType"] = {
"Maintenance Window": "MaintenanceWindow",
"Managed Instance": "ManagedInstance",
"Ops Metadata": "OpsMetadata",
"Patch Baseline": "PatchBaseline",
"Ops Item": "OpsItem",
"Association": "Association",
"Automation": "Automation",
"Document": "Document",
"Parameter": "Parameter",
}
SERVICE_NAME = "ssm" # Amazon Simple Systems Manager (SSM).
DEFAULT_TIMEOUT = 600 # Default timeout for polling commands.
MAXIMUM_COMMAND_TIMEOUT = (
2592000 # Maximum timeout for running commands in ssm (30 days).
)
MINIMUM_COMMAND_TIMEOUT = 30 # Minimum timeout for running commands in ssm.
DEFAULT_INTERVAL_IN_SECONDS = 30 # Interval for polling commands.
TERMINAL_AUTOMATION_STATUSES = { # the status for run automation command
"Success": "The automation completed successfully.",
"TimedOut": "A step or approval wasn't completed before the specified timeout period.",
"Cancelled": "The automation was stopped by a requester before it completed.",
"Failed": "The automation didn't complete successfully. This is a terminal state.",
}
CANCEL_TERMINAL_AUTOMATION_STATUSES = { # the status for cancel automation command
"Success": "The cancel command failed. The automation completed successfully before the cancellation.",
"TimedOut": "The cancel command failed. The automation failed on timeout before the cancellation.",
"Cancelled": "The cancel command completed successfully, The automation was stopped by a requester before it completed.",
"Failed": "The cancel command failed. The automation failed before it completed.",
}
TERMINAL_COMMAND_STATUSES = { # the status for run command command
"Success": "The command completed successfully.",
"Failed": "The command wasn't successfully on the managed node.",
"Delivery Timed Out": "The command wasn't delivered to the managed node before the total timeout expired.",
"Incomplete": "The command was attempted on all managed nodes and one or more of the invocations "
"doesn't have a value of Success. However, not enough invocations failed for the status to be Failed.",
"Cancelled": "The command was canceled before it was completed.",
"Canceled": "The command was canceled before it was completed.", # AWS typo, British English (canceled)
"Rate Exceeded": "The number of managed nodes targeted by the command exceeded the account quota for pending invocations. "
"The system has canceled the command before executing it on any node.",
"Access Denied": "The user or role initiating the command doesn't have access to the targeted resource group. AccessDenied "
"doesn't count against the parent command's max-errors limit, "
"but does contribute to whether the parent command status is Success or Failed.",
"No Instances In Tag": "The tag key-pair value or resource group targeted by the command doesn't match any managed nodes. ",
}
CANCEL_TERMINAL_COMMAND_STATUSES = { # the status for cancel command command
"Success": "The cancel command failed. The command completed successfully before the cancellation.",
"Failed": "The cancel command failed. The command failed before it completed.",
"Delivery Timed Out": "The command wasn't delivered to the managed node before the total timeout expired.",
"Incomplete": "The command was attempted on all managed nodes and one or more of the invocations "
"doesn't have a value of Success. However, not enough invocations failed for the status to be Failed.",
"Cancelled": "The cancel command completed successfully, The command was cancelled before it was completed.",
# AWS typo, British English (canceled)
"Canceled": "The cancel command completed successfully. The command was canceled before it was completed.",
"Rate Exceeded": "The number of managed nodes targeted by the command exceeded the account quota for pending invocations. "
"The system has canceled the command before executing it on any node.",
"Access Denied": "The user or role initiating the command doesn't have access to the targeted resource group. AccessDenied "
"doesn't count against the parent command's max-errors limit, "
"but does contribute to whether the parent command status is Success or Failed.",
"No Instances In Tag": "The tag key-pair value or resource group targeted by the command doesn't match any managed nodes. ",
}
class RegexValidator(NamedTuple):
name: str
regex: re.Pattern[str]
error_template: str
ASSOCIATION_ID_VALIDATOR = RegexValidator(
name="association_id",
regex=re.compile(
r"[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}",
),
error_template="Invalid association id: {association_id}",
)
ASSOCIATION_VERSION_VALIDATOR = RegexValidator(
name="association_version",
regex=re.compile(r"([$]LATEST)|([1-9][0-9]*)"),
error_template="Invalid association version: {association_version}",
)
INSTANCE_ID_VALIDATOR = RegexValidator(
name="instance_id",
regex=re.compile(r"(^i-(\w{8}|\w{17})$)|(^mi-\w{17}$)"),
error_template="Invalid instance id: {instance_id}",
)
""" Helper functions """
def update_if_value(
input_dictionary: dict,
output_dictionary: Any,
input_to_output_keys: dict[str, str],
) -> Any:
"""
Update the output dictionary with values from the input dictionary based on specified key mappings.
This function iterates through the key-value pairs in the `input_to_output_keys` dictionary, and for each pair,
it checks if the corresponding key exists in the `input_dictionary`. If the key exists, it copies the value to
the `output_dictionary` under the specified output key.
Args:
-----
input_dictionary (dict): The input dictionary containing data to be copied.
output_dictionary (dict): The output dictionary where data will be copied.
input_to_output_keys (dict): A dictionary mapping input keys to output keys.
Returns:
-------
dict: The updated `output_dictionary` containing copied values based on the mapping.
Example:
-------
>>> input_dict = {'next_token': 'test', 'instance_id': test_id}
>>> output_dict = {}
>>> key_mapping = {'next_token': 'NextToken', 'instance_id': 'InstanceId'}
>>> update_if_value(input_dict, output_dict, key_mapping)
{'NextToken': 'test', 'InstanceId': test_id}
"""
for input_key, output_key in input_to_output_keys.items():
if value := input_dictionary.get(input_key):
output_dictionary[output_key] = value
return output_dictionary
def format_parameters_arguments(parameters: str) -> dict[str, Any]:
"""Formats the 'parameters' into a valid format for the AWS SDK(boto3)
the valid format `{"key": ["value"]}`
Args:
----
parameters (str): A string containing key-value pairs separated by colons and
values separated by commas.
The valid format:
1. type dict: {"key": "value1, value2"}
2. type str: `"key":["value1","value2"]`
3. type str: `{"key":["value1","value2"]}`
Returns:
-------
dict[str, Any]: A dictionary where keys are extracted from the input string,
and values are lists of values associated with each key.
Example:
-------
Use this function to format a parameters string:
>>> parameters = `'"key":["value1","value2"], "key2": ["value3"]'`
>>> formatted_parameters = format_parameters_arguments(parameters)
>>> print(formatted_parameters)
{'key1': ['value1', 'value2'], 'key2': ['value3']}
Note:
----
- The input from the War Room should follow the format `"key":["value1","value2"]` or `{"key":["value1","value2"]}`.
- The input from the playbook should follow the format {"key": "value1, value2"}.
- The type of the parameter, from the playbook is dict and from the War Room is str.
"""
parameters_dict = {}
if isinstance(parameters, str):
if not parameters.startswith("{") and not parameters.endswith("}"):
parameters = "{" + parameters + "}"
try:
parameters_dict = json.loads(parameters)
except json.decoder.JSONDecodeError as e:
raise DemistoException(
"Make sure the parameters are in one of the allowed formats."
) from e
elif isinstance(parameters, dict): # in case the command running from playbook
for key, value in parameters.items():
parameters_dict[key] = argToList(value)
return parameters_dict
def format_document_version(document_version: str) -> str:
"""Convert the version str to AWS SSM document version string format.
Args:
----
document_version (str): The document version to format.
Returns:
-------
str: The formatted document version string.
- If "latest", it returns "$LATEST".
Example:
-------
>>> version = "latest"
>>> formatted_version = format_document_version(version)
>>> print(Formatted version)
$LATEST
"""
return {"latest": "$LATEST", "default": "$DEFAULT"}.get(
document_version, document_version
)
def validate_args(args: dict[str, Any]) -> NoReturn | None:
"""Validates the arguments in the provided dictionary using regular expressions,
from the constants REGEX_PATTERNS.
Args:
----
args: A dictionary containing the arguments to be validated.
Raises:
------
DemistoException: If any of the arguments fail to match their respective regex patterns.
Example:
-------
>>> args = {
>>> 'instance_id': 'i-0a00aaa000000000a', # valid instance id
>>> 'association_id': '0000' # invalid association id
>>> }
>>> try:
>>> validate_args(args)
>>> except DemistoException as e: # e equals to "Invalid association id: 0000"
>>> print(f"Validation error: {e}")
Validation error: Invalid association id: 0000
"""
for validator in (
ASSOCIATION_ID_VALIDATOR,
ASSOCIATION_VERSION_VALIDATOR,
INSTANCE_ID_VALIDATOR,
):
if (arg_value := args.get(validator.name)) and not re.search(
validator.regex,
arg_value,
):
raise DemistoException(
validator.error_template.format(**{validator.name: arg_value}),
)
return None
def config_aws_session(args: dict[str, str], aws_client: AWSClient) -> "SSMClient":
"""Configures an AWS session for the Lambda service,
Used in all the commands.
Args:
----
args: A dictionary containing the configuration parameters for the session.
- 'region' (str): The AWS region.
- 'roleArn' (str): The ARN of the IAM role.
- 'roleSessionName' (str): The name of the role session.
- 'roleSessionDuration' (str): The duration of the role session.
aws_client: The AWS client used to configure the session.
Returns:
-------
AWS session (ssm client): The configured AWS session.
"""
return aws_client.aws_session(
service=SERVICE_NAME,
region=args.get("region"),
role_arn=args.get("roleArn"),
role_session_name=args.get("roleSessionName"),
role_session_duration=args.get("roleSessionDuration"),
)
def convert_datetime_to_iso(response) -> dict[str, Any]:
"""Converts datetime objects in a response dictionary to ISO formatted strings.
Args:
----
response (dict): The response dictionary.
Returns:
-------
dict: The response dictionary with datetime objects converted to ISO formatted strings.
Example:
-------
>>> response = {
>>> 'timestamp': datetime(2023, 8, 20, 12, 30, 0),
>>> 'data': {
>>> 'created_at': datetime(2023, 8, 19, 15, 45, 0)
>>> }
>>> }
>>> iso_response = convert_datetime_to_iso(response)
>>> print(iso_response)
{
'timestamp': '2023-08-20T12:30:00',
'data': {
'created_at': '2023-08-19T15:45:00'
}
}
"""
def _datetime_to_string(obj: Any) -> str:
if isinstance(obj, datetime):
return obj.isoformat()
raise TypeError(f"Type {type(obj)} is not serializable.")
# json.dumps(default=): If specified, default should be a function that
# gets called for objects that can’t otherwise be serialized.
# It should return a JSON encodable version of the object or raise a TypeError. If not specified, TypeError is raised.
return json.loads(json.dumps(response, default=_datetime_to_string))
def next_token_command_result(next_token: str, outputs_prefix: str) -> CommandResults:
"""Creates a CommandResults object with the next token as the output.
Args:
----
next_token (str): The next token.
outputs_prefix (str): The prefix for the outputs.
Returns:
-------
CommandResults: A CommandResults object with the next token as the output.
Example:
-------
>>> next_token_command_result("token", "InventoryNextToken")
in the context output(war room):
{
AWS:
SSM:
InventoryNextToken:
NextToken: "token"
}
"""
return CommandResults(
outputs={f"AWS.SSM.{outputs_prefix}(val.NextToken)": {"NextToken": next_token}},
readable_output=f"For more results, use the next token from the context path: AWS.SSM.{outputs_prefix}.NextToken",
)
def get_command_status(command_id: str, ssm_client: "SSMClient") -> str:
"""Gets the status of an AWS Systems Manager (SSM) command.
Args:
----
command_id (str): The unique identifier of the command.
ssm_client (SSMClient): An instance of the AWS Systems Manager (SSM) client.
Returns:
-------
str: The status of the command.
## Possible values:
- Pending
- InProgress
- Cancelling
- Delayed
- Success
- Delivery Timed Out
- Execution Timed Out
- Failed
- Canceled or Cancelled (AWS typo, British English)
- Undeliverable
- Terminated
- Access Denied
"""
response = ssm_client.list_commands(CommandId=command_id)
try:
return response["Commands"][0]["Status"]
except IndexError as e:
raise DemistoException(f"Command ID {command_id} not found in response") from e
except KeyError as e:
raise DemistoException(
f"Status key not found for command ID {command_id}"
) from e
def parse_automation_execution(automation: dict[str, Any]) -> dict[str, Any]:
"""Parses an automation execution
and returns a dict contain the parsed automation.
for the readable_output function.
"""
return {
"Automation Execution Id": automation.get("AutomationExecutionId"),
"Document Name": automation.get("DocumentName"),
"Document Version": automation.get("DocumentVersion"),
"Start Time": automation.get("ExecutionStartTime"),
"End Time": automation.get("ExecutionEndTime"),
"Automation Execution Status": automation.get("AutomationExecutionStatus"),
"Mode": automation.get("Mode"),
"Executed By": automation.get("ExecutedBy"),
}
""" COMMAND FUNCTIONS """
def add_tags_to_resource_command(
args: dict[str, Any],
ssm_client: "SSMClient",
) -> CommandResults:
"""Adds tags to a specified resource.
The response from the API call when success is empty dict.
Args:
----
ssm_client ("SSMClient"): An instance of the SSM client.
args (dict): A dictionary containing the command arguments.
- 'resource_type' (str): The type of the resource.
- 'resource_id' (str): The ID of the resource.
- 'tag_key' (str): The key of the tag to add.
- 'tag_value' (str): The value of the tag to add.
Returns:
-------
CommandResults: readable output only,
"""
kwargs = {
"ResourceType": RESOURCE_TYPE_MAP[args["resource_type"]],
"ResourceId": args["resource_id"],
"Tags": [{"Key": args["tag_key"], "Value": args["tag_value"]}],
}
ssm_client.add_tags_to_resource(**kwargs)
return CommandResults(
readable_output=f"Tags successfully added to resource {args['resource_id']}.",
)
def remove_tags_from_resource_command(
args: dict[str, Any],
ssm_client: "SSMClient",
) -> CommandResults:
ssm_client.remove_tags_from_resource(
ResourceType=RESOURCE_TYPE_MAP[args["resource_type"]],
ResourceId=args["resource_id"],
TagKeys=[args["tag_key"]],
)
return CommandResults(
readable_output=f"Tag {args['tag_key']} removed from resource {args['resource_id']} successfully.",
)
def list_tags_for_resource_command(args: dict[str, Any], ssm_client: "SSMClient"):
resource_id = args["resource_id"]
response = ssm_client.list_tags_for_resource(
ResourceType=RESOURCE_TYPE_MAP[args["resource_type"]], ResourceId=resource_id
)
tag_list = response["TagList"]
tags = {"ResourceId": resource_id, "TagList": tag_list}
human_readable = tableToMarkdown(f"Tags for {resource_id}", tag_list)
command_results = CommandResults(
outputs_key_field="ResourceId",
outputs_prefix="AWS.SSM.Tag",
outputs=tags,
readable_output=human_readable,
)
return command_results
def list_inventory_command(
args: dict[str, Any],
ssm_client: "SSMClient",
) -> list[CommandResults]:
"""Fetches inventory information from AWS SSM using the provided SSM client and arguments.
Args:
----
ssm_client: SSM client object for making API requests.
args (dict): Command arguments containing filters and parameters.
Returns:
-------
list[CommandResults]: A list of CommandResults containing the inventory information.
"""
def _parse_inventory_entities(entities: list[dict]) -> list[dict]:
parsed_entities = []
for entity in entities:
entity_content: list = entity.get("Content", [])
parsed_entity = {"Id": entity.get("Id")}
for content in entity_content:
parsed_entities.append(
parsed_entity
| {
"Instance Id": content.get("InstanceId"),
"Computer Name": content.get("ComputerName"),
"Platform Type": content.get("PlatformType"),
"Platform Name": content.get("PlatformName"),
"Agent version": content.get("AgentVersion"),
"IP address": content.get("IpAddress"),
"Resource Type": content.get("ResourceType"),
}
)
return parsed_entities
kwargs: "GetInventoryRequestRequestTypeDef" = {
"MaxResults": arg_to_number(args.get("limit", 50)) or 50,
"Filters": [
{"Key": "AWS:InstanceInformation.InstanceStatus", "Values": ["active"]}
],
}
kwargs = update_if_value(args, kwargs, {"next_token": "NextToken"})
if argToBoolean(args.get("include_inactive_instance")):
kwargs["Filters"][0]["Values"].extend(
["stopped", "terminated", "ConnectionLost"]
)
response = ssm_client.get_inventory(**kwargs)
command_results = []
if response_next_token := response.get("NextToken"):
command_results.append(
next_token_command_result(response_next_token, "InventoryNextToken"),
)
entities = list(response.get("Entities", []))
# Extract the Data field from the object and add it to the main dictionary, Data contain a dict.
# added type ignore(1) because "Argument 1 to "update" of "MutableMapping" has incompatible type..."
# added type ignore(2) because "Argument 1 to "update" of "TypedDict" has incompatible type...."
for item in entities:
item["Data"].update(item["Data"].pop("AWS:InstanceInformation", {})) # type: ignore[arg-type]
item.update(item.pop("Data")) # type: ignore[typeddict-item]
command_results.append(
CommandResults(
outputs_prefix="AWS.SSM.Inventory",
outputs=entities,
outputs_key_field="Id",
readable_output=tableToMarkdown(
name="AWS SSM Inventory",
t=_parse_inventory_entities(entities), # type: ignore
),
),
)
return command_results
def list_inventory_entry_command(
args: dict[str, Any],
ssm_client: "SSMClient",
) -> list[CommandResults]:
"""Lists inventory entries for a specific instance and type name using the provided SSM client and arguments.
Args:
----
ssm_client: AWS SSM client object for making API requests.
args (dict): Command arguments containing filters and parameters.
- instance_id (str): The ID of the instance.
- type_name (str): The type name of the inventory.
- limit (int, optional): Maximum number of entries to retrieve. Defaults to 50.
- next_token (str, optional): Token to retrieve the next set of entries.
Returns:
-------
list[CommandResults]: A list of CommandResults containing the inventory entries information.
and the next token if exists.
Raises:
------
DemistoException: If an invalid instance ID is provided.
"""
map_type_name = {
"Instance Information": "InstanceInformation",
"File": "File",
"Process": "Process",
"Windows Update": "WindowsUpdate",
"Network": "Network",
"Patch Summary": "PatchSummary",
"Patch Compliance": "PatchCompliance",
"Compliance Item": "ComplianceItem",
"Instance Detailed Information": "InstanceDetailedInformation",
"Service": "Service",
"Windows Registry": "WindowsRegistry",
"Windows Role": "WindowsRole",
"Tag": "Tag",
"Resource Group": "ResourceGroup",
"Billing Info": "BillingInfo",
"Application": "Application",
"AWS Components": "AWSComponents",
}
type_name = map_type_name[args["type_name"]]
kwargs = {
"InstanceId": args["instance_id"],
"TypeName": f"AWS:{type_name}",
"MaxResults": arg_to_number(args.get("limit", 50)) or 50,
}
kwargs = update_if_value(args, kwargs, {"next_token": "NextToken"})
response = ssm_client.list_inventory_entries(**kwargs)
# added type ignore because "Key "ResponseMetadata" of TypedDict "ListInventoryEntriesResultTypeDef" cannot be deleted"
response.pop("ResponseMetadata") # type: ignore[misc]
entries = response.get("Entries", [])
command_results = []
if next_token := response.get("NextToken"):
# added type ignore because "Key NextToken" of TypedDict "ListInventoryEntriesResultTypeDef" cannot be deleted"
response.pop("NextToken") # type: ignore[misc]
command_results.append(
next_token_command_result(next_token, "InventoryEntryNextToken"),
)
command_results.append(
CommandResults(
outputs_prefix="AWS.SSM.InventoryEntry",
outputs=response,
outputs_key_field="InstanceId",
readable_output=tableToMarkdown(
name="AWS SSM Inventory Entry",
t=entries,
),
),
)
return command_results
def list_associations_command(
args: dict[str, Any],
ssm_client: "SSMClient",
) -> list[CommandResults]:
"""Lists associations in AWS SSM using the provided SSM client and arguments.
Args:
----
ssm_client: AWS SSM client object for making API requests.
args (dict): Command arguments containing filters and parameters.
- limit (int, optional): Maximum number of associations to retrieve. Defaults to 50.
- next_token (str, optional): Token to retrieve the next set of associations.
Returns:
-------
list[CommandResults]: A list of CommandResults containing the association information.
and the next token if exists in the response.
"""
def _parse_associations(associations: list[dict[str, Any]]) -> list[dict[str, Any]]:
return [
{
"Document name": association.get("Name"),
"Association id": association.get("AssociationId"),
"Association version": association.get("AssociationVersion"),
"Last execution date": association.get("LastExecutionDate"),
"Resource status count": dict_safe_get(
association,
["Overview", "AssociationStatusAggregatedCount"],
),
"Status": dict_safe_get(association, ["Overview", "Status"]),
}
for association in associations
]
kwargs: "ListAssociationsRequestRequestTypeDef" = {
"MaxResults": arg_to_number(args.get("limit", 50)) or 50,
}
kwargs = update_if_value(args, kwargs, {"next_token": "NextToken"})
response = ssm_client.list_associations(**kwargs)
response = convert_datetime_to_iso(response)
associations = response.get("Associations", [])
command_results = []
if next_token := response.get("NextToken"):
command_results.append(
next_token_command_result(next_token, "InventoryNextToken"),
)
command_results.append(
CommandResults(
outputs_prefix="AWS.SSM.Association",
outputs=associations,
outputs_key_field="AssociationId",
readable_output=tableToMarkdown(
name="AWS SSM Associations",
t=_parse_associations(associations),
),
),
)
return command_results
def get_association_command(
args: dict[str, Any],
ssm_client: "SSMClient",
) -> CommandResults:
"""Retrieves information about an SSM association based on provided parameters.
Args:
----
ssm_client: The AWS SSM client used to interact with the service.
args (dict[str, Any]): A dictionary containing the command arguments.
Returns:
-------
CommandResults: A CommandResults object containing information about the retrieved association.
Raises:
------
DemistoException: If the provided arguments are invalid.
"""
def _parse_association(association: dict[str, Any]) -> dict[str, Any]:
return {
"Document name": association.get("Name"),
"Document version": association.get("DocumentVersion"),
"Association name": association.get("AssociationName"),
"Association id": association.get("AssociationId"),
"Association version": association.get("AssociationVersion"),
"Last execution date": association.get("LastExecutionDate"),
"Resource status count": dict_safe_get(
association,
["Overview", "AssociationStatusAggregatedCount"],
),
"Status": dict_safe_get(association, ["Overview", "Status"]),
"Create date": association.get("Date"),
"Schedule expression": association.get("ScheduleExpression"),
}
association_id = args.get("association_id")
association_version = args.get("association_version")
instance_id = args.get("instance_id")
document_name = args.get("document_name")
if not (association_id or (instance_id and document_name)):
msg = "This command must provide either association_id or instance_id and document_name."
raise DemistoException(msg)
kwargs = {
"AssociationId": association_id,
"AssociationVersion": association_version,
"InstanceId": instance_id,
"Name": document_name,
}
kwargs = {key: value for key, value in kwargs.items() if value is not None}
response = ssm_client.describe_association(**kwargs)
response = convert_datetime_to_iso(response)
association_description = response.get("AssociationDescription", {})
return CommandResults(
outputs=association_description,
outputs_key_field="AssociationId",
outputs_prefix="AWS.SSM.Association",
readable_output=tableToMarkdown(
name="AWS SSM Association",
t=_parse_association(association_description),
),
)
def list_versions_association_command(
args: dict[str, Any],
ssm_client: "SSMClient",
) -> list[CommandResults]:
"""Lists the versions of an SSM association based on provided parameters.
Args:
----
ssm_client: The AWS SSM client used to interact with the service.
- association_id (required): The ID of the association.
- limit (optional): The maximum number of versions to return. Defaults to 50.
- next_token (optional): The token for the next set of results.
Returns:
-------
list[CommandResults]: A list of CommandResults objects, containing information about the association versions.
If next_token provide in the response, the first CommandResults in the list will contain the next token.
"""
def _parse_association_versions(
association_versions: list[dict[str, Any]],
) -> list[dict[str, Any]]:
return [
{
"Version": association_version.get("AssociationVersion"),
"Name": association_version.get("Name"),
"Create date": association_version.get("CreatedDate"),
"Association id": association_version.get("AssociationId"),
"Document version": association_version.get("DocumentVersion"),
"Targets": association_version.get("Targets"),
"Parameters": association_version.get("Parameters"),
"Schedule expression": association_version.get("ScheduleExpression"),
"Output location": association_version.get("OutputLocation"),
"MaxConcurrency": association_version.get("MaxConcurrency"),
"MaxErrors": association_version.get("MaxErrors"),
}
for association_version in association_versions
]
kwargs = {
"AssociationId": args["association_id"],
"MaxResults": arg_to_number(args.get("limit", 50)) or 50,
}
kwargs = update_if_value(args, kwargs, {"next_token": "NextToken"})
response = ssm_client.list_association_versions(**kwargs)
response = convert_datetime_to_iso(response)
association_versions = response.get("AssociationVersions", [])
command_results: list[CommandResults] = []
if response_next_token := response.get("NextToken"):
command_results.append(
next_token_command_result(
response_next_token,
"AssociationVersionNextToken",
),
)
command_results.append(
CommandResults(
outputs=association_versions,
outputs_key_field="AssociationId",
outputs_prefix="AWS.SSM.AssociationVersion",
readable_output=tableToMarkdown(
t=_parse_association_versions(association_versions),
name="Association Versions",
json_transform_mapping={
"Parameters": JsonTransformer(
is_nested=True,
),
"Targets": JsonTransformer(
is_nested=True,
),
},
),
),
)
return command_results
def list_documents_command(
args: dict[str, Any],
ssm_client: "SSMClient",
) -> list[CommandResults]:
"""Lists the documents in AWS SSM using the provided SSM client and arguments.
Args:
----
ssm_client: AWS SSM client object for making API requests.
args (dict): Command arguments containing filters and parameters.
- limit (int, optional): Maximum number of documents to retrieve. Defaults to 50.
- next_token (str, optional): Token to retrieve the next set of documents.
Returns:
-------
list[CommandResults]: A list of CommandResults containing the documents information.
and the next token if exists in the response.
"""
def _parse_documents(documents: list[dict[str, Any]]) -> list[dict[str, Any]]:
return [
{
"Name": document.get("Name"),
"Owner": document.get("Owner"),
"Document version": document.get("DocumentVersion"),
"Document type": document.get("DocumentType"),
"Created date": document.get("CreatedDate"),
"Platform types": document.get("PlatformTypes"),
}
for document in documents
]
kwargs: "ListDocumentsRequestRequestTypeDef" = {
"MaxResults": arg_to_number(args.get("limit", 50)) or 50,
}
kwargs = update_if_value(args, kwargs, {"next_token": "NextToken"})
response = ssm_client.list_documents(**kwargs)
response = convert_datetime_to_iso(response)
documents = response.get("DocumentIdentifiers", [])
command_results = []
if next_token := response.get("NextToken"):
command_results.append(
next_token_command_result(next_token, "DocumentNextToken"),
)
command_results.append(
CommandResults(
outputs=documents,
outputs_key_field="Name",
outputs_prefix="AWS.SSM.Document",
readable_output=tableToMarkdown(
name="AWS SSM Documents",
t=_parse_documents(documents),
headers=[
"Name",
"Owner",
"Document version",
"Document type",
"Platform types",
"Created date",
],
),
),
)
return command_results
def get_document_command(
args: dict[str, Any],
ssm_client: "SSMClient",
) -> CommandResults:
"""Retrieves information about an AWS Systems Manager (SSM) document.
Args:
----
args (dict[str, Any]): A dictionary containing command arguments.
- document_name (str, required): The name of the SSM document.
- document_version (str, optional): The version of the SSM document to retrieve.
- version_name (str, optional): The name of the version of the SSM document to retrieve.
ssm_client (SSMClient): An instance of the AWS Systems Manager (SSM) client.
Returns:
-------
CommandResults: An object containing the results of the command.
"""
def _parse_document(document: "DocumentDescriptionTypeDef"):
return {
"Name": document.get("Name"),
"Display Name": document.get("DisplayName"),
"Document version": document.get("VersionName"),
"Owner": document.get("Owner"),
"Description": document.get("Description"),
"Platform types": document.get("PlatformTypes"),
"Created date": document.get("CreatedDate"),
"Status": document.get("Status"),
}
kwargs = {"Name": args["document_name"]}
if document_version := args.get("document_version"):
kwargs["DocumentVersion"] = format_document_version(document_version)
kwargs = update_if_value(args, kwargs, {"version_name": "VersionName"})
response = ssm_client.describe_document(**kwargs)
response = convert_datetime_to_iso(response)
document = response["Document"]
return CommandResults(
outputs=document,
outputs_key_field="Name",
outputs_prefix="AWS.SSM.Document",
readable_output=tableToMarkdown(
name="AWS SSM Document",
t=_parse_document(document),
),
)
def get_automation_execution_command(
args: dict[str, Any],
ssm_client: "SSMClient",
) -> CommandResults:
"""Retrieves information about an AWS Systems Manager (SSM) automation execution.
Args:
----
args (dict[str, Any]): A dictionary containing command arguments.
- execution_id (str): The unique identifier of the automation execution.
ssm_client (SSMClient): An instance of the AWS Systems Manager (SSM) client.
Returns:
-------
CommandResults: An object containing the results of the command.
"""
automation_execution = ssm_client.get_automation_execution(
AutomationExecutionId=args["execution_id"],
)["AutomationExecution"]
automation_execution = convert_datetime_to_iso(automation_execution)
return CommandResults(
outputs_prefix="AWS.SSM.AutomationExecution",
outputs_key_field="AutomationExecutionId",
outputs=automation_execution,
readable_output=tableToMarkdown(
name="AWS SSM Automation Execution",
t=parse_automation_execution(automation_execution),