Debian Codegraph @

ansible_collections/amazon/aws/plugins/modules/cloudtrail.py

raw
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3
4 # Copyright: Ansible Project
5 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
6
7 DOCUMENTATION = r"""
8 ---
9 module: cloudtrail
10 version_added: 5.0.0
11 short_description: manage CloudTrail create, delete, update
12 description:
13 - Creates, deletes, or updates CloudTrail configuration. Ensures logging is also enabled.
14 - This module was originally added to C(community.aws) in release 1.0.0.
15 author:
16 - Ansible Core Team
17 - Ted Timmons (@tedder)
18 - Daniel Shepherd (@shepdelacreme)
19 options:
20 state:
21 description:
22 - Add or remove CloudTrail configuration.
23 - 'The following states have been preserved for backwards compatibility: O(state=enabled) and O(state=disabled).'
24 - O(state=enabled) is equivalet to O(state=present).
25 - O(state=disabled) is equivalet to O(state=absent).
26 type: str
27 choices: ['present', 'absent', 'enabled', 'disabled']
28 default: present
29 name:
30 description:
31 - Name for the CloudTrail.
32 - Names are unique per-region unless the CloudTrail is a multi-region trail, in which case it is unique per-account.
33 type: str
34 default: default
35 enable_logging:
36 description:
37 - Start or stop the CloudTrail logging. If stopped the trail will be paused and will not record events or deliver log files.
38 default: true
39 type: bool
40 s3_bucket_name:
41 description:
42 - An existing S3 bucket where CloudTrail will deliver log files.
43 - This bucket should exist and have the proper policy.
44 - See U(https://docs.aws.amazon.com/awscloudtrail/latest/userguide/aggregating_logs_regions_bucket_policy.html).
45 - Required when O(state=present).
46 type: str
47 s3_key_prefix:
48 description:
49 - S3 Key prefix for delivered log files. A trailing slash is not necessary and will be removed.
50 type: str
51 is_multi_region_trail:
52 description:
53 - Specify whether the trail belongs only to one region or exists in all regions.
54 default: false
55 type: bool
56 enable_log_file_validation:
57 description:
58 - Specifies whether log file integrity validation is enabled.
59 - CloudTrail will create a hash for every log file delivered and produce a signed digest file that can be used to ensure log files have not been tampered.
60 type: bool
61 aliases: [ "log_file_validation_enabled" ]
62 include_global_events:
63 description:
64 - Record API calls from global services such as IAM and STS.
65 default: true
66 type: bool
67 aliases: [ "include_global_service_events" ]
68 sns_topic_name:
69 description:
70 - SNS Topic name to send notifications to when a log file is delivered.
71 type: str
72 cloudwatch_logs_role_arn:
73 description:
74 - Specifies a full ARN for an IAM role that assigns the proper permissions for CloudTrail to create and write to the log group.
75 - See U(https://docs.aws.amazon.com/awscloudtrail/latest/userguide/send-cloudtrail-events-to-cloudwatch-logs.html).
76 - Required when O(cloudwatch_logs_log_group_arn).
77 type: str
78 cloudwatch_logs_log_group_arn:
79 description:
80 - A full ARN specifying a valid CloudWatch log group to which CloudTrail logs will be delivered. The log group should already exist.
81 - See U(https://docs.aws.amazon.com/awscloudtrail/latest/userguide/send-cloudtrail-events-to-cloudwatch-logs.html).
82 - Required when O(cloudwatch_logs_role_arn).
83 type: str
84 kms_key_id:
85 description:
86 - Specifies the KMS key ID to use to encrypt the logs delivered by CloudTrail. This also has the effect of enabling log file encryption.
87 - The value can be an alias name prefixed by "alias/", a fully specified ARN to an alias, a fully specified ARN to a key, or a globally unique identifier.
88 - Encryption can be disabled by setting O(kms_key_id="").
89 - See U(https://docs.aws.amazon.com/awscloudtrail/latest/userguide/encrypting-cloudtrail-log-files-with-aws-kms.html).
90 type: str
91 notes:
92 - The O(purge_tags) option was added in release 4.0.0.
93
94 extends_documentation_fragment:
95 - amazon.aws.common.modules
96 - amazon.aws.region.modules
97 - amazon.aws.tags
98 - amazon.aws.boto3
99 """
100
101 EXAMPLES = r"""
102 - name: create single region cloudtrail
103 amazon.aws.cloudtrail:
104 state: present
105 name: default
106 s3_bucket_name: mylogbucket
107 s3_key_prefix: cloudtrail
108 region: us-east-1
109
110 - name: create multi-region trail with validation and tags
111 amazon.aws.cloudtrail:
112 state: present
113 name: default
114 s3_bucket_name: mylogbucket
115 region: us-east-1
116 is_multi_region_trail: true
117 enable_log_file_validation: true
118 cloudwatch_logs_role_arn: "arn:aws:iam::123456789012:role/CloudTrail_CloudWatchLogs_Role"
119 cloudwatch_logs_log_group_arn: "arn:aws:logs:us-east-1:123456789012:log-group:CloudTrail/DefaultLogGroup:*"
120 kms_key_id: "alias/MyAliasName"
121 tags:
122 environment: dev
123 Name: default
124
125 - name: show another valid kms_key_id
126 amazon.aws.cloudtrail:
127 state: present
128 name: default
129 s3_bucket_name: mylogbucket
130 kms_key_id: "arn:aws:kms:us-east-1:123456789012:key/12345678-1234-1234-1234-123456789012"
131 # simply "12345678-1234-1234-1234-123456789012" would be valid too.
132
133 - name: pause logging the trail we just created
134 amazon.aws.cloudtrail:
135 state: present
136 name: default
137 enable_logging: false
138 s3_bucket_name: mylogbucket
139 region: us-east-1
140 is_multi_region_trail: true
141 enable_log_file_validation: true
142 tags:
143 environment: dev
144 Name: default
145
146 - name: delete a trail
147 amazon.aws.cloudtrail:
148 state: absent
149 name: default
150 """
151
152 RETURN = r"""
153 exists:
154 description: whether the resource exists.
155 returned: always
156 type: bool
157 sample: true
158 trail:
159 description: CloudTrail resource details.
160 returned: always
161 type: complex
162 sample: hash/dictionary of values
163 contains:
164 trail_arn:
165 description: Full ARN of the CloudTrail resource.
166 returned: success
167 type: str
168 sample: arn:aws:cloudtrail:us-east-1:123456789012:trail/default
169 name:
170 description: Name of the CloudTrail resource.
171 returned: success
172 type: str
173 sample: default
174 is_logging:
175 description: Whether logging is turned on or paused for the Trail.
176 returned: success
177 type: bool
178 sample: True
179 s3_bucket_name:
180 description: S3 bucket name where log files are delivered.
181 returned: success
182 type: str
183 sample: myBucket
184 s3_key_prefix:
185 description: Key prefix in bucket where log files are delivered (if any).
186 returned: success when present
187 type: str
188 sample: myKeyPrefix
189 log_file_validation_enabled:
190 description: Whether log file validation is enabled on the trail.
191 returned: success
192 type: bool
193 sample: true
194 include_global_service_events:
195 description: Whether global services (IAM, STS) are logged with this trail.
196 returned: success
197 type: bool
198 sample: true
199 is_multi_region_trail:
200 description: Whether the trail applies to all regions or just one.
201 returned: success
202 type: bool
203 sample: true
204 is_organization_trail:
205 description:
206 - Specifies whether the trail is created for all accounts in an organization in Organizations, or only for the current Amazon Web Services account.
207 returned: success
208 type: bool
209 sample: true
210 has_custom_event_selectors:
211 description: Whether any custom event selectors are used for this trail.
212 returned: success
213 type: bool
214 sample: False
215 has_insight_selectors:
216 description: Whether any insight selectors are used for this trail.
217 returned: success
218 type: bool
219 sample: False
220 home_region:
221 description: The home region where the trail was originally created and must be edited.
222 returned: success
223 type: str
224 sample: us-east-1
225 sns_topic_name:
226 description: The SNS topic name where log delivery notifications are sent.
227 returned: success when present
228 type: str
229 sample: myTopic
230 sns_topic_arn:
231 description: Full ARN of the SNS topic where log delivery notifications are sent.
232 returned: success when present
233 type: str
234 sample: arn:aws:sns:us-east-1:123456789012:topic/myTopic
235 cloud_watch_logs_log_group_arn:
236 description: Full ARN of the CloudWatch Logs log group where events are delivered.
237 returned: success when present
238 type: str
239 sample: arn:aws:logs:us-east-1:123456789012:log-group:CloudTrail/DefaultLogGroup:*
240 cloud_watch_logs_role_arn:
241 description: Full ARN of the IAM role that CloudTrail assumes to deliver events.
242 returned: success when present
243 type: str
244 sample: arn:aws:iam::123456789012:role/CloudTrail_CloudWatchLogs_Role
245 kms_key_id:
246 description: Full ARN of the KMS Key used to encrypt log files.
247 returned: success when present
248 type: str
249 sample: arn:aws:kms::123456789012:key/12345678-1234-1234-1234-123456789012
250 tags:
251 description: hash/dictionary of tags applied to this resource
252 returned: success
253 type: dict
254 sample: {'environment': 'dev', 'Name': 'default'}
255 """
256
257 try:
258 from botocore.exceptions import BotoCoreError
259 from botocore.exceptions import ClientError
260 except ImportError:
261 pass # Handled by AnsibleAWSModule
262
263 from ansible.module_utils.common.dict_transformations import camel_dict_to_snake_dict
264
265 from ansible_collections.amazon.aws.plugins.module_utils.modules import AnsibleAWSModule
266 from ansible_collections.amazon.aws.plugins.module_utils.tagging import ansible_dict_to_boto3_tag_list
267 from ansible_collections.amazon.aws.plugins.module_utils.tagging import boto3_tag_list_to_ansible_dict
268 from ansible_collections.amazon.aws.plugins.module_utils.tagging import compare_aws_tags
269
270
271 def get_kms_key_aliases(module, client, keyId):
272 """
273 get list of key aliases
274
275 module : AnsibleAWSModule object
276 client : boto3 client connection object for kms
277 keyId : keyId to get aliases for
278 """
279 try:
280 key_resp = client.list_aliases(KeyId=keyId)
281 except (BotoCoreError, ClientError):
282 # Don't fail here, just return [] to maintain backwards compat
283 # in case user doesn't have kms:ListAliases permissions
284 return []
285
286 return key_resp["Aliases"]
287
288
289 def create_trail(module, client, ct_params):
290 """
291 Creates a CloudTrail
292
293 module : AnsibleAWSModule object
294 client : boto3 client connection object
295 ct_params : The parameters for the Trail to create
296 """
297 resp = {}
298 try:
299 resp = client.create_trail(**ct_params)
300 except (BotoCoreError, ClientError) as err:
301 module.fail_json_aws(err, msg="Failed to create Trail")
302
303 return resp
304
305
306 def tag_trail(module, client, tags, trail_arn, curr_tags=None, purge_tags=True):
307 """
308 Creates, updates, removes tags on a CloudTrail resource
309
310 module : AnsibleAWSModule object
311 client : boto3 client connection object
312 tags : Dict of tags converted from ansible_dict to boto3 list of dicts
313 trail_arn : The ARN of the CloudTrail to operate on
314 curr_tags : Dict of the current tags on resource, if any
315 dry_run : true/false to determine if changes will be made if needed
316 """
317
318 if tags is None:
319 return False
320
321 curr_tags = curr_tags or {}
322
323 tags_to_add, tags_to_remove = compare_aws_tags(curr_tags, tags, purge_tags=purge_tags)
324 if not tags_to_add and not tags_to_remove:
325 return False
326
327 if module.check_mode:
328 return True
329
330 if tags_to_remove:
331 remove = {k: curr_tags[k] for k in tags_to_remove}
332 tags_to_remove = ansible_dict_to_boto3_tag_list(remove)
333 try:
334 client.remove_tags(ResourceId=trail_arn, TagsList=tags_to_remove)
335 except (BotoCoreError, ClientError) as err:
336 module.fail_json_aws(err, msg="Failed to remove tags from Trail")
337
338 if tags_to_add:
339 tags_to_add = ansible_dict_to_boto3_tag_list(tags_to_add)
340 try:
341 client.add_tags(ResourceId=trail_arn, TagsList=tags_to_add)
342 except (BotoCoreError, ClientError) as err:
343 module.fail_json_aws(err, msg="Failed to add tags to Trail")
344
345 return True
346
347
348 def set_logging(module, client, name, action):
349 """
350 Starts or stops logging based on given state
351
352 module : AnsibleAWSModule object
353 client : boto3 client connection object
354 name : The name or ARN of the CloudTrail to operate on
355 action : start or stop
356 """
357 if action == "start":
358 try:
359 client.start_logging(Name=name)
360 return client.get_trail_status(Name=name)
361 except (BotoCoreError, ClientError) as err:
362 module.fail_json_aws(err, msg="Failed to start logging")
363 elif action == "stop":
364 try:
365 client.stop_logging(Name=name)
366 return client.get_trail_status(Name=name)
367 except (BotoCoreError, ClientError) as err:
368 module.fail_json_aws(err, msg="Failed to stop logging")
369 else:
370 module.fail_json(msg="Unsupported logging action")
371
372
373 def get_trail_facts(module, client, name):
374 """
375 Describes existing trail in an account
376
377 module : AnsibleAWSModule object
378 client : boto3 client connection object
379 name : Name of the trail
380 """
381 # get Trail info
382 try:
383 trail_resp = client.describe_trails(trailNameList=[name])
384 except (BotoCoreError, ClientError) as err:
385 module.fail_json_aws(err, msg="Failed to describe Trail")
386
387 # Now check to see if our trail exists and get status and tags
388 if len(trail_resp["trailList"]):
389 trail = trail_resp["trailList"][0]
390 try:
391 status_resp = client.get_trail_status(Name=trail["Name"])
392 tags_list = client.list_tags(ResourceIdList=[trail["TrailARN"]])
393 except (BotoCoreError, ClientError) as err:
394 module.fail_json_aws(err, msg="Failed to describe Trail")
395
396 trail["IsLogging"] = status_resp["IsLogging"]
397 trail["tags"] = boto3_tag_list_to_ansible_dict(tags_list["ResourceTagList"][0]["TagsList"])
398 # Check for non-existent values and populate with None
399 optional_vals = set(
400 [
401 "S3KeyPrefix",
402 "SnsTopicName",
403 "SnsTopicARN",
404 "CloudWatchLogsLogGroupArn",
405 "CloudWatchLogsRoleArn",
406 "KmsKeyId",
407 ]
408 )
409 for v in optional_vals - set(trail.keys()):
410 trail[v] = None
411 return trail
412
413 else:
414 # trail doesn't exist return None
415 return None
416
417
418 def delete_trail(module, client, trail_arn):
419 """
420 Delete a CloudTrail
421
422 module : AnsibleAWSModule object
423 client : boto3 client connection object
424 trail_arn : Full CloudTrail ARN
425 """
426 try:
427 client.delete_trail(Name=trail_arn)
428 except (BotoCoreError, ClientError) as err:
429 module.fail_json_aws(err, msg="Failed to delete Trail")
430
431
432 def update_trail(module, client, ct_params):
433 """
434 Delete a CloudTrail
435
436 module : AnsibleAWSModule object
437 client : boto3 client connection object
438 ct_params : The parameters for the Trail to update
439 """
440 try:
441 client.update_trail(**ct_params)
442 except (BotoCoreError, ClientError) as err:
443 module.fail_json_aws(err, msg="Failed to update Trail")
444
445
446 def main():
447 argument_spec = dict(
448 state=dict(default="present", choices=["present", "absent", "enabled", "disabled"]),
449 name=dict(default="default"),
450 enable_logging=dict(default=True, type="bool"),
451 s3_bucket_name=dict(),
452 s3_key_prefix=dict(no_log=False),
453 sns_topic_name=dict(),
454 is_multi_region_trail=dict(default=False, type="bool"),
455 enable_log_file_validation=dict(type="bool", aliases=["log_file_validation_enabled"]),
456 include_global_events=dict(default=True, type="bool", aliases=["include_global_service_events"]),
457 cloudwatch_logs_role_arn=dict(),
458 cloudwatch_logs_log_group_arn=dict(),
459 kms_key_id=dict(),
460 tags=dict(type="dict", aliases=["resource_tags"]),
461 purge_tags=dict(default=True, type="bool"),
462 )
463
464 required_if = [("state", "present", ["s3_bucket_name"]), ("state", "enabled", ["s3_bucket_name"])]
465 required_together = [("cloudwatch_logs_role_arn", "cloudwatch_logs_log_group_arn")]
466
467 module = AnsibleAWSModule(
468 argument_spec=argument_spec,
469 supports_check_mode=True,
470 required_together=required_together,
471 required_if=required_if,
472 )
473
474 # collect parameters
475 if module.params["state"] in ("present", "enabled"):
476 state = "present"
477 elif module.params["state"] in ("absent", "disabled"):
478 state = "absent"
479 tags = module.params["tags"]
480 purge_tags = module.params["purge_tags"]
481 enable_logging = module.params["enable_logging"]
482 ct_params = dict(
483 Name=module.params["name"],
484 S3BucketName=module.params["s3_bucket_name"],
485 IncludeGlobalServiceEvents=module.params["include_global_events"],
486 IsMultiRegionTrail=module.params["is_multi_region_trail"],
487 )
488
489 if module.params["s3_key_prefix"]:
490 ct_params["S3KeyPrefix"] = module.params["s3_key_prefix"].rstrip("/")
491
492 if module.params["sns_topic_name"]:
493 ct_params["SnsTopicName"] = module.params["sns_topic_name"]
494
495 if module.params["cloudwatch_logs_role_arn"]:
496 ct_params["CloudWatchLogsRoleArn"] = module.params["cloudwatch_logs_role_arn"]
497
498 if module.params["cloudwatch_logs_log_group_arn"]:
499 ct_params["CloudWatchLogsLogGroupArn"] = module.params["cloudwatch_logs_log_group_arn"]
500
501 if module.params["enable_log_file_validation"] is not None:
502 ct_params["EnableLogFileValidation"] = module.params["enable_log_file_validation"]
503
504 if module.params["kms_key_id"] is not None:
505 ct_params["KmsKeyId"] = module.params["kms_key_id"]
506
507 client = module.client("cloudtrail")
508 region = module.region
509
510 results = dict(changed=False, exists=False)
511
512 # Get existing trail facts
513 trail = get_trail_facts(module, client, ct_params["Name"])
514
515 # If the trail exists set the result exists variable
516 if trail is not None:
517 results["exists"] = True
518 initial_kms_key_id = trail.get("KmsKeyId")
519
520 if state == "absent" and results["exists"]:
521 # If Trail exists go ahead and delete
522 results["changed"] = True
523 results["exists"] = False
524 results["trail"] = dict()
525 if not module.check_mode:
526 delete_trail(module, client, trail["TrailARN"])
527
528 elif state == "present" and results["exists"]:
529 # If Trail exists see if we need to update it
530 do_update = False
531 for key in ct_params:
532 tkey = str(key)
533 # boto3 has inconsistent parameter naming so we handle it here
534 if key == "EnableLogFileValidation":
535 tkey = "LogFileValidationEnabled"
536 # We need to make an empty string equal None
537 if ct_params.get(key) == "":
538 val = None
539 else:
540 val = ct_params.get(key)
541 if val != trail.get(tkey):
542 do_update = True
543 if tkey != "KmsKeyId":
544 # We'll check if the KmsKeyId casues changes later since
545 # user could've provided a key alias, alias arn, or key id
546 # and trail['KmsKeyId'] is always a key arn
547 results["changed"] = True
548 # If we are in check mode copy the changed values to the trail facts in result output to show what would change.
549 if module.check_mode:
550 trail.update({tkey: ct_params.get(key)})
551
552 if not module.check_mode and do_update:
553 update_trail(module, client, ct_params)
554 trail = get_trail_facts(module, client, ct_params["Name"])
555
556 # Determine if KmsKeyId changed
557 if not module.check_mode:
558 if initial_kms_key_id != trail.get("KmsKeyId"):
559 results["changed"] = True
560 else:
561 new_key = ct_params.get("KmsKeyId")
562 if initial_kms_key_id != new_key:
563 # Assume changed for a moment
564 results["changed"] = True
565
566 # However, new_key could be a key id, alias arn, or alias name
567 # that maps back to the key arn in initial_kms_key_id. So check
568 # all aliases for a match.
569 initial_aliases = get_kms_key_aliases(module, module.client("kms"), initial_kms_key_id)
570 for a in initial_aliases:
571 if a["AliasName"] == new_key or a["AliasArn"] == new_key or a["TargetKeyId"] == new_key:
572 results["changed"] = False
573
574 # Check if we need to start/stop logging
575 if enable_logging and not trail["IsLogging"]:
576 results["changed"] = True
577 trail["IsLogging"] = True
578 if not module.check_mode:
579 set_logging(module, client, name=ct_params["Name"], action="start")
580 if not enable_logging and trail["IsLogging"]:
581 results["changed"] = True
582 trail["IsLogging"] = False
583 if not module.check_mode:
584 set_logging(module, client, name=ct_params["Name"], action="stop")
585
586 # Check if we need to update tags on resource
587 tags_changed = tag_trail(
588 module, client, tags=tags, trail_arn=trail["TrailARN"], curr_tags=trail["tags"], purge_tags=purge_tags
589 )
590 if tags_changed:
591 updated_tags = dict()
592 if not purge_tags:
593 updated_tags = trail["tags"]
594 updated_tags.update(tags)
595 results["changed"] = True
596 trail["tags"] = updated_tags
597
598 # Populate trail facts in output
599 results["trail"] = camel_dict_to_snake_dict(trail, ignore_list=["tags"])
600
601 elif state == "present" and not results["exists"]:
602 # Trail doesn't exist just go create it
603 results["changed"] = True
604 results["exists"] = True
605 if not module.check_mode:
606 if tags:
607 ct_params["TagsList"] = ansible_dict_to_boto3_tag_list(tags)
608 # If we aren't in check_mode then actually create it
609 created_trail = create_trail(module, client, ct_params)
610 # Get the trail status
611 try:
612 status_resp = client.get_trail_status(Name=created_trail["Name"])
613 except (BotoCoreError, ClientError) as err:
614 module.fail_json_aws(err, msg="Failed to fetch Trail statuc")
615 # Set the logging state for the trail to desired value
616 if enable_logging and not status_resp["IsLogging"]:
617 set_logging(module, client, name=ct_params["Name"], action="start")
618 if not enable_logging and status_resp["IsLogging"]:
619 set_logging(module, client, name=ct_params["Name"], action="stop")
620 # Get facts for newly created Trail
621 trail = get_trail_facts(module, client, ct_params["Name"])
622
623 # If we are in check mode create a fake return structure for the newly minted trail
624 if module.check_mode:
625 acct_id = "123456789012"
626 try:
627 sts_client = module.client("sts")
628 acct_id = sts_client.get_caller_identity()["Account"]
629 except (BotoCoreError, ClientError):
630 pass
631 trail = dict()
632 trail.update(ct_params)
633 if "EnableLogFileValidation" not in ct_params:
634 ct_params["EnableLogFileValidation"] = False
635 trail["EnableLogFileValidation"] = ct_params["EnableLogFileValidation"]
636 trail.pop("EnableLogFileValidation")
637 fake_arn = "arn:aws:cloudtrail:" + region + ":" + acct_id + ":trail/" + ct_params["Name"]
638 trail["HasCustomEventSelectors"] = False
639 trail["HomeRegion"] = region
640 trail["TrailARN"] = fake_arn
641 trail["IsLogging"] = enable_logging
642 trail["tags"] = tags
643 # Populate trail facts in output
644 results["trail"] = camel_dict_to_snake_dict(trail, ignore_list=["tags"])
645
646 module.exit_json(**results)
647
648
649 if __name__ == "__main__":
650 main()