
    Vhba                         d Z dZdZ	 ddlmZ ddlmZ ddlmZ ddl	m
Z
 ddlmZ dd	lmZ dd
lmZ d Zd ZddZd Zd Zd Zd Zd Zedk(  r e        yy# e$ r Y Lw xY w)a  
---
module: cloudtrail
version_added: 5.0.0
short_description: manage CloudTrail create, delete, update
description:
  - Creates, deletes, or updates CloudTrail configuration. Ensures logging is also enabled.
  - This module was originally added to C(community.aws) in release 1.0.0.
author:
  - Ansible Core Team
  - Ted Timmons (@tedder)
  - Daniel Shepherd (@shepdelacreme)
options:
  state:
    description:
      - Add or remove CloudTrail configuration.
      - 'The following states have been preserved for backwards compatibility: O(state=enabled) and O(state=disabled).'
      - O(state=enabled) is equivalet to O(state=present).
      - O(state=disabled) is equivalet to O(state=absent).
    type: str
    choices: ['present', 'absent', 'enabled', 'disabled']
    default: present
  name:
    description:
      - Name for the CloudTrail.
      - Names are unique per-region unless the CloudTrail is a multi-region trail, in which case it is unique per-account.
    type: str
    default: default
  enable_logging:
    description:
      - Start or stop the CloudTrail logging. If stopped the trail will be paused and will not record events or deliver log files.
    default: true
    type: bool
  s3_bucket_name:
    description:
      - An existing S3 bucket where CloudTrail will deliver log files.
      - This bucket should exist and have the proper policy.
      - See U(https://docs.aws.amazon.com/awscloudtrail/latest/userguide/aggregating_logs_regions_bucket_policy.html).
      - Required when O(state=present).
    type: str
  s3_key_prefix:
    description:
      - S3 Key prefix for delivered log files. A trailing slash is not necessary and will be removed.
    type: str
  is_multi_region_trail:
    description:
      - Specify whether the trail belongs only to one region or exists in all regions.
    default: false
    type: bool
  enable_log_file_validation:
    description:
      - Specifies whether log file integrity validation is enabled.
      - 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.
    type: bool
    aliases: [ "log_file_validation_enabled" ]
  include_global_events:
    description:
      - Record API calls from global services such as IAM and STS.
    default: true
    type: bool
    aliases: [ "include_global_service_events" ]
  sns_topic_name:
    description:
      - SNS Topic name to send notifications to when a log file is delivered.
    type: str
  cloudwatch_logs_role_arn:
    description:
      - Specifies a full ARN for an IAM role that assigns the proper permissions for CloudTrail to create and write to the log group.
      - See U(https://docs.aws.amazon.com/awscloudtrail/latest/userguide/send-cloudtrail-events-to-cloudwatch-logs.html).
      - Required when O(cloudwatch_logs_log_group_arn).
    type: str
  cloudwatch_logs_log_group_arn:
    description:
      - A full ARN specifying a valid CloudWatch log group to which CloudTrail logs will be delivered. The log group should already exist.
      - See U(https://docs.aws.amazon.com/awscloudtrail/latest/userguide/send-cloudtrail-events-to-cloudwatch-logs.html).
      - Required when O(cloudwatch_logs_role_arn).
    type: str
  kms_key_id:
    description:
      - Specifies the KMS key ID to use to encrypt the logs delivered by CloudTrail. This also has the effect of enabling log file encryption.
      - 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.
      - Encryption can be disabled by setting O(kms_key_id="").
      - See U(https://docs.aws.amazon.com/awscloudtrail/latest/userguide/encrypting-cloudtrail-log-files-with-aws-kms.html).
    type: str
notes:
  - The O(purge_tags) option was added in release 4.0.0.

extends_documentation_fragment:
  - amazon.aws.common.modules
  - amazon.aws.region.modules
  - amazon.aws.tags
  - amazon.aws.boto3
a  
- name: create single region cloudtrail
  amazon.aws.cloudtrail:
    state: present
    name: default
    s3_bucket_name: mylogbucket
    s3_key_prefix: cloudtrail
    region: us-east-1

- name: create multi-region trail with validation and tags
  amazon.aws.cloudtrail:
    state: present
    name: default
    s3_bucket_name: mylogbucket
    region: us-east-1
    is_multi_region_trail: true
    enable_log_file_validation: true
    cloudwatch_logs_role_arn: "arn:aws:iam::123456789012:role/CloudTrail_CloudWatchLogs_Role"
    cloudwatch_logs_log_group_arn: "arn:aws:logs:us-east-1:123456789012:log-group:CloudTrail/DefaultLogGroup:*"
    kms_key_id: "alias/MyAliasName"
    tags:
      environment: dev
      Name: default

- name: show another valid kms_key_id
  amazon.aws.cloudtrail:
    state: present
    name: default
    s3_bucket_name: mylogbucket
    kms_key_id: "arn:aws:kms:us-east-1:123456789012:key/12345678-1234-1234-1234-123456789012"
    # simply "12345678-1234-1234-1234-123456789012" would be valid too.

- name: pause logging the trail we just created
  amazon.aws.cloudtrail:
    state: present
    name: default
    enable_logging: false
    s3_bucket_name: mylogbucket
    region: us-east-1
    is_multi_region_trail: true
    enable_log_file_validation: true
    tags:
      environment: dev
      Name: default

- name: delete a trail
  amazon.aws.cloudtrail:
    state: absent
    name: default
a  
exists:
    description: whether the resource exists.
    returned: always
    type: bool
    sample: true
trail:
    description: CloudTrail resource details.
    returned: always
    type: complex
    sample: hash/dictionary of values
    contains:
        trail_arn:
            description: Full ARN of the CloudTrail resource.
            returned: success
            type: str
            sample: arn:aws:cloudtrail:us-east-1:123456789012:trail/default
        name:
            description: Name of the CloudTrail resource.
            returned: success
            type: str
            sample: default
        is_logging:
            description: Whether logging is turned on or paused for the Trail.
            returned: success
            type: bool
            sample: True
        s3_bucket_name:
            description: S3 bucket name where log files are delivered.
            returned: success
            type: str
            sample: myBucket
        s3_key_prefix:
            description: Key prefix in bucket where log files are delivered (if any).
            returned: success when present
            type: str
            sample: myKeyPrefix
        log_file_validation_enabled:
            description: Whether log file validation is enabled on the trail.
            returned: success
            type: bool
            sample: true
        include_global_service_events:
            description: Whether global services (IAM, STS) are logged with this trail.
            returned: success
            type: bool
            sample: true
        is_multi_region_trail:
            description: Whether the trail applies to all regions or just one.
            returned: success
            type: bool
            sample: true
        is_organization_trail:
            description:
            - Specifies whether the trail is created for all accounts in an organization in Organizations, or only for the current Amazon Web Services account.
            returned: success
            type: bool
            sample: true
        has_custom_event_selectors:
            description: Whether any custom event selectors are used for this trail.
            returned: success
            type: bool
            sample: False
        has_insight_selectors:
            description: Whether any insight selectors are used for this trail.
            returned: success
            type: bool
            sample: False
        home_region:
            description: The home region where the trail was originally created and must be edited.
            returned: success
            type: str
            sample: us-east-1
        sns_topic_name:
            description: The SNS topic name where log delivery notifications are sent.
            returned: success when present
            type: str
            sample: myTopic
        sns_topic_arn:
            description: Full ARN of the SNS topic where log delivery notifications are sent.
            returned: success when present
            type: str
            sample: arn:aws:sns:us-east-1:123456789012:topic/myTopic
        cloud_watch_logs_log_group_arn:
            description: Full ARN of the CloudWatch Logs log group where events are delivered.
            returned: success when present
            type: str
            sample: arn:aws:logs:us-east-1:123456789012:log-group:CloudTrail/DefaultLogGroup:*
        cloud_watch_logs_role_arn:
            description: Full ARN of the IAM role that CloudTrail assumes to deliver events.
            returned: success when present
            type: str
            sample: arn:aws:iam::123456789012:role/CloudTrail_CloudWatchLogs_Role
        kms_key_id:
            description: Full ARN of the KMS Key used to encrypt log files.
            returned: success when present
            type: str
            sample: arn:aws:kms::123456789012:key/12345678-1234-1234-1234-123456789012
        tags:
            description: hash/dictionary of tags applied to this resource
            returned: success
            type: dict
            sample: {'environment': 'dev', 'Name': 'default'}
    )BotoCoreError)ClientError)camel_dict_to_snake_dict)AnsibleAWSModule)ansible_dict_to_boto3_tag_list)boto3_tag_list_to_ansible_dict)compare_aws_tagsc                 `    	 |j                  |      }|d   S # t        t        f$ r g cY S w xY w)z
    get list of key aliases

    module : AnsibleAWSModule object
    client : boto3 client connection object for kms
    keyId : keyId to get aliases for
    )KeyIdAliases)list_aliasesr   r   )moduleclientkeyIdkey_resps       i/home/dcms/DCMS/lib/python3.12/site-packages/ansible_collections/amazon/aws/plugins/modules/cloudtrail.pyget_kms_key_aliasesr     sD    &&U&3 I ;'  	s    --c                     i }	  |j                   di |}|S # t        t        f$ r}| j                  |d       Y d}~|S d}~ww xY w)z
    Creates a CloudTrail

    module : AnsibleAWSModule object
    client : boto3 client connection object
    ct_params : The parameters for the Trail to create
    zFailed to create TrailmsgN )create_trailr   r   fail_json_aws)r   r   	ct_paramsresperrs        r   r   r   !  s`     D@"v""/Y/ K ;' @S&>??K@s    AA  ANc                    |y|xs i }t        |||      \  }}|s|sy| j                  ry|r2|D ci c]  }|||   
 }	}t        |	      }	 |j                  ||       |r t        |      }	 |j                  ||       yyc c}w # t        t
        f$ r}
| j                  |
d       Y d}
~
Od}
~
ww xY w# t        t
        f$ r}
| j                  |
d       Y d}
~
yd}
~
ww xY w)	a  
    Creates, updates, removes tags on a CloudTrail resource

    module : AnsibleAWSModule object
    client : boto3 client connection object
    tags : Dict of tags converted from ansible_dict to boto3 list of dicts
    trail_arn : The ARN of the CloudTrail to operate on
    curr_tags : Dict of the current tags on resource, if any
    dry_run : true/false to determine if changes will be made if needed
    NF)
purge_tagsT)
ResourceIdTagsListz Failed to remove tags from Trailr   zFailed to add tags to Trail)r	   
check_moder   remove_tagsr   r   r   add_tags)r   r   tags	trail_arn	curr_tagsr   tags_to_addtags_to_removekremover   s              r   	tag_trailr+   2  s    |RI"29dz"ZK~+9:a!Yq\/::7?	N)nM 4[A	IOOy;OG  ; {+ 	N  *L MM	N {+ 	I  *G HH	Is5   BB	 /B8 	B5B00B58C$CC$c                    |dk(  r%	 |j                  |       |j                  |      S |dk(  r%	 |j                  |       |j                  |      S | j                  d       y# t        t        f$ r}| j	                  |d       Y d}~yd}~ww xY w# t        t        f$ r}| j	                  |d       Y d}~yd}~ww xY w)	z
    Starts or stops logging based on given state

    module : AnsibleAWSModule object
    client : boto3 client connection object
    name : The name or ARN of the CloudTrail to operate on
    action : start or stop
    startNamezFailed to start loggingr   NstopzFailed to stop loggingzUnsupported logging action)start_loggingget_trail_statusr   r   r   stop_logging	fail_json)r   r   nameactionr   s        r   set_loggingr7   \  s     	E  d +***55 
6		DT****55 	9: {+ 	E  *C DD	E {+ 	D  *B CC	Ds.   #A( #B (B7BBC&B>>Cc                    	 |j                  |g      }t	        d         r|d   d   }	 |j                  |d         }|j                  |d	   g
      }d   |d<   t        d   d   d         |d<   t        g d      }|t        |j                               z
  D ]  }	d||	<   	 |S y# t        t        f$ r}| j                  |d       Y d}~d}~ww xY w# t        t        f$ r}| j                  |d       Y d}~d}~ww xY w)z
    Describes existing trail in an account

    module : AnsibleAWSModule object
    client : boto3 client connection object
    name : Name of the trail
    )trailNameListzFailed to describe Trailr   N	trailListr   r/   r.   TrailARN)ResourceIdList	IsLoggingResourceTagListr    r$   )S3KeyPrefixSnsTopicNameSnsTopicARNCloudWatchLogsLogGroupArnCloudWatchLogsRoleArnKmsKeyId)
describe_trailsr   r   r   lenr2   	list_tagsr   setkeys)
r   r   r5   
trail_respr   trailstatus_resp	tags_listoptional_valsvs
             r   get_trail_factsrP   u  sF   B++4&+A

 :k"#;'*	F 11uV}1EK((z9J8K(LI )5k6yAR7STU7VWa7bcf	
 UZZ\!22 	AE!H	 ? ;' BS&@AAB {+ 	F  *D EE	Fs.   B, +C ,C;CCD*DDc                     	 |j                  |       y# t        t        f$ r}| j                  |d       Y d}~yd}~ww xY w)z
    Delete a CloudTrail

    module : AnsibleAWSModule object
    client : boto3 client connection object
    trail_arn : Full CloudTrail ARN
    r.   zFailed to delete Trailr   N)delete_trailr   r   r   )r   r   r%   r   s       r   rR   rR     sG    @+;' @S&>??@    A<Ac                     	  |j                   di | y# t        t        f$ r}| j                  |d       Y d}~yd}~ww xY w)z
    Delete a CloudTrail

    module : AnsibleAWSModule object
    client : boto3 client connection object
    ct_params : The parameters for the Trail to update
    zFailed to update Trailr   Nr   )update_trailr   r   r   )r   r   r   r   s       r   rU   rU     sI    @(i(;' @S&>??@rS   c                     t        t        dg d      t        d      t        dd      t               t        d	
      t               t        d	d      t        ddg      t        dddg      t               t               t               t        ddg      t        dd            } dddgfdddgfg}dg}t        | d||      }|j                  d   dv rd}n|j                  d   dv rd}|j                  d   }|j                  d   }|j                  d   }t        |j                  d   |j                  d   |j                  d   |j                  d          }|j                  d!   r!|j                  d!   j                  d"      |d#<   |j                  d$   r|j                  d$   |d%<   |j                  d&   r|j                  d&   |d'<   |j                  d(   r|j                  d(   |d)<   |j                  d*   |j                  d*   |d+<   |j                  d,   |j                  d,   |d-<   |j	                  d.      }	|j
                  }
t        d	d	/      }t        ||	|d0         }|d|d1<   |j                  d-      }dk(  r;|d1   r6d|d2<   d	|d1<   t               |d3<   |j                  sYt        ||	|d4          nG|dk(  r|d1   rd	}|D ]  }t        |      }|d+k(  rd5}|j                  |      d6k(  rd }n|j                  |      }||j                  |      k7  sRd}|d-k7  rd|d2<   |j                  sk|j                  ||j                  |      i        |j                  s|rt        ||	|       t        ||	|d0         }|j                  s|j                  d-      k7  rbd|d2<   n\|j                  d-      }|k7  rFd|d2<   t        ||j	                  d7      |      }|D ]   }|d8   |k(  s|d9   |k(  s	|d:   |k(  sd	|d2<   " |r-|d;   s(d|d2<   d|d;<   |j                  st        ||	|d0   d<=       |s-|d;   r(d|d2<   d	|d;<   |j                  st        ||	|d0   d>=       t        ||	||d4   |d   |?      }|r,t               }|s|d   }|j                  |       d|d2<   ||d<   t!        |dg@      |d3<   nE|dk(  r?|d1   s9d|d2<   d|d1<   |j                  su|rt#        |      |dA<   t%        ||	|      }	 |	j'                  |d0   B      }|rd;   st        ||	|d0   d<=       |sd;   rt        ||	|d0   d>=       t        ||	|d0         }|j                  rdE}	 |j	                  dF      }|j/                         dG   }t               }|j                  |       d+|vrd	|d+<   |d+   |d+<   |j1                  d+       dH|
z   dIz   |z   dJz   |d0   z   }d	|dK<   |
|dL<   ||d4<   ||d;<   ||d<   t!        |dg@      |d3<    |j2                  dMi | y # t(        t*        f$ r}|j-                  |dCD       Y d }~+d }~ww xY w# t(        t*        f$ r Y w xY w)NNpresent)rW   absentenableddisabled)defaultchoicesr[   )r[   Tbool)r[   typeF)no_loglog_file_validation_enabled)r^   aliasesinclude_global_service_events)r[   r^   ra   dictresource_tags)stater5   enable_loggings3_bucket_names3_key_prefixsns_topic_nameis_multi_region_trailenable_log_file_validationinclude_global_eventscloudwatch_logs_role_arncloudwatch_logs_log_group_arn
kms_key_idr$   r   re   rg   rY   )rm   rn   )argument_specsupports_check_moderequired_togetherrequired_if)rW   rY   )rX   rZ   rX   r$   r   rf   r5   rl   rj   )r/   S3BucketNameIncludeGlobalServiceEventsIsMultiRegionTrailrh   /r?   ri   r@   rm   rC   rn   rB   rk   EnableLogFileValidationro   rD   
cloudtrail)changedexistsr/   r{   rz   rK   r;   LogFileValidationEnabled kms	AliasNameAliasArnTargetKeyIdr=   r-   )r5   r6   r0   )r$   r%   r&   r   )ignore_listr    r.   zFailed to fetch Trail statucr   123456789012stsAccountzarn:aws:cloudtrail::z:trail/HasCustomEventSelectors
HomeRegionr   )rc   r   paramsrstripr   regionrP   getr!   rR   strupdaterU   r   r7   r+   r   r   r   r2   r   r   r   get_caller_identitypop	exit_json)rp   rs   rr   r   re   r$   r   rf   r   r   r   resultsrK   initial_kms_key_id	do_updatekeytkeyvalnew_keyinitial_aliasesatags_changedupdated_tagscreated_trailrL   r   acct_id
sts_clientfake_arns                                r   mainr     s4   9.Z[)$Dv6v%(v"5v>#'V>[=\#]"4fGfFgh!%&*f6v'8962M" Y)9(:;gyScRd=efKVW# +	F }}W!77	w	#9	9== D|,J]]#34N]]6"]]#34#)==1H#I!==)@A	I }}_%#)==#A#H#H#M	- }}%&$*MM2B$C	.!}}/0-3]];U-V	)*}}4517?^1_	-.}}12>/5}}=Y/Z	+,}}\". &l ;	*]]<(F]]F5/G FFIf,=>E  "YYz2WX.!	!6  z):;	)	 1	 	=Cs8D//1}}S!R'mmC(eiio% 	:% *.GI&$$LL$	c(:!;<'	=*   Y3#FFIf4EFE   !UYYz%::%)	"mmJ/G!W,%)	"
 #6ffmmE>RTf"g( 3A~0AjMW4LPQR_P`dkPk-2	*3
 %"4!%GI!%E+$$FF61B7S%"4!%GI!&E+$$FF61B6R !Fz1BeTZmhr
 6L$V}%!%GI(E&M 4ExP	)	GH$5!	   (Ft(L	*%(CMN$55=;P5Q k+&>FF61B7S!k+&>FF61B6R#FFIf4EFE $G#]]51
$88:9E FELL#(	97<	34/89R/SE+,II/0,v5;gE	QT]^dTeeH/4E+,"(E, (E*!/E+ E&M3ExPFwC ";/ N$$S.L$MMN  ";/ s*   X -$Y Y.YYY! Y!__main__)NT)DOCUMENTATIONEXAMPLESRETURNbotocore.exceptionsr   r   ImportError0ansible.module_utils.common.dict_transformationsr   ;ansible_collections.amazon.aws.plugins.module_utils.modulesr   ;ansible_collections.amazon.aws.plugins.module_utils.taggingr   r   r	   r   r   r+   r7   rP   rR   rU   r   __name__r       r   <module>r      s   \|1fg
R	1/ V X f f X$"'T;2*Z@@H V zF K  		s   A A! A!