
    Vh~R                         d Z dZdZddlZddl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dlmZ d Zd Zd Zd Zd Zedk(  r e        yy# e
$ r Y <w xY w)a  
---
module: lambda_event
version_added: 5.0.0
short_description: Creates, updates or deletes AWS Lambda function event mappings
description:
  - This module allows the management of AWS Lambda function event source mappings such as DynamoDB and Kinesis stream
    events via the Ansible framework. These event source mappings are relevant only in the AWS Lambda pull model, where
    AWS Lambda invokes the function.
    It is idempotent and supports "Check" mode. Use module M(amazon.aws.lambda) to manage the lambda
    function itself and M(amazon.aws.lambda_alias) to manage function aliases.
  - This module was originally added to C(community.aws) in release 1.0.0.

author:
  - Pierre Jodouin (@pjodouin)
  - Ryan Brown (@ryansb)
options:
  lambda_function_arn:
    description:
      - The name or ARN of the lambda function.
    required: true
    aliases: ['function_name', 'function_arn']
    type: str
  state:
    description:
      - Describes the desired state.
    default: "present"
    choices: ["present", "absent"]
    type: str
  alias:
    description:
      - Name of the function alias.
      - Mutually exclusive with O(version).
    type: str
  version:
    description:
      - Version of the Lambda function.
      - Mutually exclusive with O(alias).
    type: int
    default: 0
  event_source:
    description:
      - Source of the event that triggers the lambda function.
      - For DynamoDB and Kinesis events, select V(stream).
      - For SQS queues, select V(sqs).
    default: stream
    choices: ['stream', 'sqs']
    type: str
  source_params:
    description:
      - Sub-parameters required for event source.
    suboptions:
      source_arn:
        description:
          - The Amazon Resource Name (ARN) of the SQS queue, Kinesis stream or DynamoDB stream that is the event source.
        type: str
        required: true
      enabled:
        description:
          - Indicates whether AWS Lambda should begin polling or readin from the event source.
        default: true
        type: bool
      batch_size:
        description:
          - The largest number of records that AWS Lambda will retrieve from your event source at the time of invoking your function.
          - Amazon Kinesis - Default V(100). Max V(10000).
          - Amazon DynamoDB Streams - Default V(100). Max V(10000).
          - Amazon Simple Queue Service - Default V(10). For standard queues the max is V(10000). For FIFO queues the max is V(10).
          - Amazon Managed Streaming for Apache Kafka - Default V(100). Max V(10000).
          - Self-managed Apache Kafka - Default C(100). Max V(10000).
          - Amazon MQ (ActiveMQ and RabbitMQ) - Default V(100). Max V(10000).
          - DocumentDB - Default V(100). Max V(10000).
        type: int
      starting_position:
        description:
          - The position in the stream where AWS Lambda should start reading.
          - Required when O(event_source=stream).
        choices: [TRIM_HORIZON,LATEST]
        type: str
      function_response_types:
        description:
          - (Streams and Amazon SQS) A list of current response type enums applied to the event source mapping.
        type: list
        elements: str
        choices: [ReportBatchItemFailures]
        version_added: 5.5.0
      maximum_batching_window_in_seconds:
        description:
          - The maximum amount of time, in seconds, that Lambda spends gathering records before invoking the function.
          - You can configure O(source_params.maximum_batching_window_in_seconds) to any value from V(0) seconds to V(300) seconds in increments of seconds.
          - For streams and Amazon SQS event sources, when O(source_params.batch_size) is set to a value greater than V(10),
            O(source_params.maximum_batching_window_in_seconds) defaults to V(1).
          - O(source_params.maximum_batching_window_in_seconds) is not supported by FIFO queues.
        type: int
        version_added: 8.0.0
    required: true
    type: dict
extends_documentation_fragment:
  - amazon.aws.common.modules
  - amazon.aws.region.modules
  - amazon.aws.boto3
a  
# Example that creates a lambda event notification for a DynamoDB stream
- name: DynamoDB stream event mapping
  amazon.aws.lambda_event:
    state: present
    event_source: stream
    function_name: "{{ function_name }}"
    alias: Dev
    source_params:
      source_arn: arn:aws:dynamodb:us-east-1:123456789012:table/tableName/stream/2016-03-19T19:51:37.457
      enabled: true
      batch_size: 100
      starting_position: TRIM_HORIZON
  register: event

# Example that creates a lambda event notification for a DynamoDB stream
- name: DynamoDB stream event mapping
  amazon.aws.lambda_event:
    state: present
    event_source: stream
    function_name: "{{ function_name }}"
    source_params:
      source_arn: arn:aws:dynamodb:us-east-1:123456789012:table/tableName/stream/2016-03-19T19:51:37.457
      enabled: true
      batch_size: 100
      starting_position: LATEST
      function_response_types:
        - ReportBatchItemFailures
  register: event

- name: Show source event
  ansible.builtin.debug:
    var: event.lambda_stream_events
a  
---
events:
    description: Dictionary returned by the API describing stream event mappings
    returned: success
    type: dict
    contains:
      batch_size:
        description: The maximum number of records in each batch that Lambda pulls.
        type: int
        returned: always
      bisect_batch_on_function_error:
        description: If the function returns an error, split the batch in two and retry.
        type: bool
        returned: for Kinesis and DynamoDB Streams only
        sample: false
      destination_config:
        description: Configuration object that specifies the destination of an event after Lambda processes it.
        type: dict
        returned: For Kinesis, DynamoDB Streams, Amazon MSK, and self-managed Kafka only
        contains:
          on_failure:
            description: The destination configuration for failed invocations.
            type: dict
            contains:
              destination:
                description: Destination resource ARN.
                type: str
          on_success:
            description: The destination configuration for failed invocations.
            type: dict
            contains:
              destination:
                description: Destination resource ARN.
                type: str
      event_source_arn:
        description: The Amazon Resource Name (ARN) of the event source.
        type: str
        returned: always
        sample: "arn:aws:dynamodb:us-west-2:123456789012:table/yyyy/stream/2024-06-06T07:03:58.956"
      function_arn:
        description: The ARN of the Lambda function.
        type: str
        returned: always
        sample: "arn:aws:lambda:us-west-2:123456789012:function:test-lambda-3a0a29d0dbb5:1"
      function_response_types:
        description: A list of current response type enums applied to the event source mapping.
        type: list
        returned: For Kinesis, DynamoDB Streams, and Amazon SQS
        sample: ["ReportBatchItemFailures"]
      last_modified:
        description: The date that the event source mapping was last updated or that its state changed.
        type: str
        returned: always
        sample: "2024-06-06T12:34:21.990000+05:30"
      last_processing_result:
        description: The result of the last Lambda invocation of your function.
        type: str
        returned: always
        sample: "No records processed"
      maximum_batching_window_in_seconds:
        description: The maximum amount of time, in seconds, that Lambda spends gathering records before invoking the function.
        type: int
        returned: always
        sample: 1
      maximum_record_age_in_seconds:
        description: Discard records older than the specified age. The default value is infinite (-1).
        type: int
        returned: For Kinesis and DynamoDB Streams only
        sample: -1
      maximum_retry_attempts:
        description: Discard records after the specified number of retries.
        type: int
        returned: For Kinesis and DynamoDB Streams only
        sample: -1
      parallelization_factor:
        description: The number of batches to process concurrently from each shard.
        type: int
        returned: For Kinesis and DynamoDB Streams only
        sample: 1
      starting_position:
        description: The position in a stream from which to start reading.
        type: str
        returned: For Kinesis and DynamoDB Streams only
        sample: "LATEST"
      state:
        description: The state of the event source mapping.
        type: str
        returned: always
        sample: "deleting"
      state_transition_reason:
        description: Indicates whether a user or Lambda made the last change to the event source mapping.
        type: str
        returned: always
        sample: "USER_INITIATED"
      tumbling_window_in_seconds:
        description: The duration in seconds of a processing window for DynamoDB and Kinesis Streams event sources.
        type: int
        returned: For Kinesis and DynamoDB Streams only
        sample: 1
      uuid:
        description: The identifier of the event source mapping.
        type: str
        returned: always
        sample: "a1b2c3d4-5678-90ab-cdef-11111EXAMPLE"
    N)BotoCoreError)ClientError)MissingParametersError)ParamValidationError)camel_dict_to_snake_dict)is_boto3_error_code)AnsibleAWSModule)AWSRetryc                    | j                   d   }t        |       }t        j                  d|      s| j	                  d| d       |j                  d      sXt        |      dkD  r| j	                  d| d	       	 d
|i}|r||d<    |j                  di |}|d   d   | j                   d<   yt        |      dkD  r| j	                  d| d       |r| d| | j                   d<   yy# t        d      $ r& d| d}|r	d| d| d}| j	                  |       Y yt        $ r"}| j	                  d| d|        Y d}~yd}~ww xY w)z
    Performs basic parameter validation.

    :param module: The AnsibleAWSModule object
    :param client: The client used to perform requests to AWS
    :return:
    lambda_function_arnz
^[\w\-:]+$zFunction name zI is invalid. Names must contain only alphanumeric characters and hyphens.msgzarn:aws:lambda:@   zFunction name "z" exceeds 64 character limitFunctionName	QualifierConfigurationFunctionArnResourceNotFoundExceptionz!An error occurred: The function 'z' does not exist.z' (qualifier=z) does not exist.z5An error occurred while trying to describe function 'z': N   zARN "z" exceeds 140 character limit: )
paramsget_qualifierresearch	fail_json
startswithlenget_functionr   r   )moduleclientfunction_name	qualifierr   responser   es           k/home/dcms/DCMS/lib/python3.12/site-packages/ansible_collections/amazon/aws/plugins/modules/lambda_event.pyvalidate_paramsr'     s    MM"78Mf%I 99]M2 /xy 	 	

 ##$56}"?=/A]!^_	p$m4F&/{#*v**4V4H3;O3L]3[FMM/0 }#57T!UV6C_Ai[3QFMM/0  ##>? 	&5m_DUVC9-V_U``qr% 	p#XYfXggjkljm!noo	ps   =2C, ,1E	E	'EE	c                     d}| j                   d   dkD  rt        | j                   d         }|S | j                   d   rt        | j                   d         }|S )zh
    Returns the function qualifier as a version or alias or None.

    :param module:
    :return:
    Nversionr   alias)r   str)r    r#   s     r&   r   r   ?  s\     I}}Y!#i01	  
w	g./	    c                 R   t        j                  |      }| j                  d   j                         dk(  r|j	                  dd       |d   j                  d      r>|d   dkD  r| j                  d       |j                  d	      r| j                  d
       no|d   dk\  rg| j                  d       nT| j                  d   j                         dk(  r4|j	                  dd       d|d   cxk  rdk  sn | j                  d       |d   dkD  r|j                  d	      sd|d	<   |S )Nevent_sourcesqs
batch_size
   
source_arnz.fifoz-For FIFO queues the maximum batch_size is 10.r   "maximum_batching_window_in_secondszUmaximum_batching_window_in_seconds is not supported by Amazon SQS FIFO event sources.i'  z?For standard queue batch_size must be between lower than 10000.streamd   z4batch_size for streams must be between 100 and 10000   )copydeepcopyr   lower
setdefaultendswithr   get)r    source_params_source_params_cpys      r&   set_default_valuesr?   Z  s0   }5}}^$**,5%%lB7&//8!,/"4  %T U!%%&JK  o !  ",/58  %f g	~	&	,	,	.(	:%%lC8),7@5@!WX,'",5G5K5KLp5qCD?@r,   c                    t               }d}d}| j                  d   }t        | j                  d         }| j                  d   }|j                  d      }|r|j                  |       n| j	                  d	
       |dk(  rt        | |      }| j                  |j                  dd            }		  |j                  d*i |d   }|rd}|dk(  r|dk(  r!|j                  d      }| j                  j                  d      }|dk(  r&|s| j	                  d
       |j                  |       |j                  |	       |j                  d      r!|j                  |j                  d             |j                  d      r!|j                  |j                  d             |j                  d      r!|j                  |j                  d             	 | j                  s |j                  d*i |}d}n|d   }t        | j                  d   |d    !      }d}|j                  d      r"|d   |d"   k7  r|j                  |d          d}|	9|	r|d#   d$vr0|j                  d       d}n|d#   d%vr|j                  d       d}|rZ	 | j                  s |j                  d*i |}d}n8|dk(  r3t        |d   d    '      }	 | j                  s |j                  d*i |}d}t        t        ||)            S # t        $ r }
| j	                  d|
 
       Y d}
~
Ud}
~
ww xY w# t        t        t        f$ r}
| j	                  d|
 
       Y d}
~
pd}
~
ww xY w# t        t        t        f$ r}
| j	                  d&|
 
       Y d}
~
d}
~
ww xY w# t        t        t        f$ r}
| j	                  d(|
 
       Y d}
~
d}
~
ww xY w)+z
    Adds, updates or deletes lambda stream (DynamoDb, Kinesis) event notifications.
    :param module:
    :param aws:
    :return:
    Fabsentstater   )r   r=   r2   )EventSourceArnzHSource parameter 'source_arn' is required for stream event notification.r   presentenabledTrueEventSourceMappingsz:Error retrieving stream event notification configuration: Nstarting_positionr.   r4   zOSource parameter 'starting_position' is required for stream event notification.)StartingPosition)Enabledr0   )	BatchSizer3   )MaximumBatchingWindowInSecondsfunction_response_types)FunctionResponseTypesTz,Error creating stream source event mapping: r   UUID)r   rO   rK   State)rJ   Enabling)Disabled	Disablingz,Error updating stream source event mapping: )rO   z,Error removing stream source event mapping: )changedeventsr   )dictr   r<   updater   r?   booleanlist_event_source_mappingsr   
check_modecreate_event_source_mappingr   r   update_event_source_mappingdelete_event_source_mappingr   )r    r!   factsrT   current_staterB   
api_paramsr=   r2   source_param_enabledr%   rH   r.   current_mappingmapping_changeds                  r&   lambda_event_streamrd   y  s,    FEGMMM'"E6==1F#GHJ MM/2M""<0J4gh	*6=A ">>-*;*;Iv*NO_111?J?@UV%M 	H$ - 1 12E F!==,,^<Lx'($$m %  !!3D!E&:;  .!!M,=,=l,K!L  !EF!!3@3D3DEi3j "    !:;!!8I8IJc8d!eY((>F>>LLE $AhO6==9N+OVeflVmnJ#O   .=3NRabmRn3n!!M,,G!H"&#/'&w/7NN"))$)7*.&w/7PP"))%)8*.]!,, B B B PZ P"G
 I%58F#34JY((>F>>LLE $D$GHHQ  _YZ[Y\]^^_8  !57MN Y  'STUSV%W XXY: $%9;QR ]$$+WXYWZ)[$\\]  !57MN Y  'STUSV%W XXYs`   1K;  L'  M  N ;	L$LL$'M;MMN1NNO'OOc                     ddg} t        t        ddddg      t        ddd	g
      t        dd|       t        ddt        t        dd      t        dd      t        d      t        dddg      t        dddg      t        d                  t        dd      t        ddd            }t        |ddd ggg !      }	 |j                  d"t        j                         #      }t        |       |j                  d&   j                         d'v rt        ||      }n|j                  d(%        |j                  d)i  y# t
        t        f$ r}|j                  |d$%       Y d}~d}~ww xY w)*z?Produce a list of function suffixes which handle lambda events.r4   r/   FrD   rA   )requireddefaultchoicesTr"   function_arn)rf   aliasesrV   r+   )typerf   bool)rk   rg   int)rk   TRIM_HORIZONLATEST)rk   rh   listReportBatchItemFailures)rk   elementsrh   )r2   rE   r0   rH   rM   r3   )rk   rf   optionsN)rf   rg   r   )rk   rf   rg   )rB   r   r.   r=   r*   r)   r*   r)   )argument_specsupports_check_modemutually_exclusiverequired_togetherlambda)retry_decoratorzTrying to connect to AWSr   r.   )r4   r/   z1Please select `stream` or `sqs` as the event typer   )rV   r	   r!   r
   jittered_backoffr   r   fail_json_awsr'   r   r9   rd   r   	exit_json)source_choicesrt   r    r!   r%   resultss         r&   mainr     s|   &NE9y(>ST $.8YZ5(NSUT:&$7U+"&ENH;U"V(,&5SlRm(n37U3C
 E40%%;#M( # $i01	F@x9R9R9TU FF#}}^$**,0AA%ff5PQFw ' @Q$>??@s   %E E4E//E4__main__)DOCUMENTATIONEXAMPLESRETURNr7   r   botocore.exceptionsr   r   r   r   ImportError0ansible.module_utils.common.dict_transformationsr   <ansible_collections.amazon.aws.plugins.module_utils.botocorer   ;ansible_collections.amazon.aws.plugins.module_utils.modulesr	   ;ansible_collections.amazon.aws.plugins.module_utils.retriesr
   r'   r   r?   rd   r   __name__r   r,   r&   <module>r      s   eN!Fi
V  		1/:8 V \ X P(RV6>kI\+ \ zF c  		s   A A%$A%