
    Vh5                         d Z dZdZddl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 Zd	 Zd
 Zd Zd Zd Zd Zd Zd Zd Zd Zd Zedk(  r e        yy# e$ r Y Kw xY w)a  
---
module: lambda_policy
version_added: 5.0.0
short_description: Creates, updates or deletes AWS Lambda policy statements.
description:
  - This module allows the management of AWS Lambda policy statements.
  - It is idempotent and supports "Check" mode.
  - Use module M(amazon.aws.lambda) to manage the lambda function itself, M(amazon.aws.lambda_alias) to manage function aliases,
    M(amazon.aws.lambda_event) to manage event source mappings such as Kinesis streams, M(community.aws.execute_lambda) to execute a
    lambda function and M(amazon.aws.lambda_info) to gather information relating to one or more lambda functions.
  - This module was originally added to C(community.aws) in release 1.0.0.
author:
  - Pierre Jodouin (@pjodouin)
  - Michael De La Rue (@mikedlr)
options:
  function_name:
    description:
      - "Name of the Lambda function whose resource policy you are updating by adding a new permission."
      - "You can specify a function name (for example, Thumbnail ) or you can specify Amazon Resource Name (ARN) of the"
      - "function (for example, V(arn:aws:lambda:us-west-2:account-id:function:ThumbNail) ). AWS Lambda also allows you to"
      - "specify partial ARN (for example, V(account-id:Thumbnail) ). Note that the length constraint applies only to the"
      - "ARN. If you specify only the function name, it is limited to 64 character in length."
    required: true
    aliases: ['lambda_function_arn', '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
  statement_id:
    description:
      -  A unique statement identifier.
    required: true
    aliases: ['sid']
    type: str
  action:
    description:
      -  "The AWS Lambda action you want to allow in this statement. Each Lambda action is a string starting with
         lambda: followed by the API name (see Operations ). For example, V(lambda:CreateFunction) . You can use wildcard
         (V(lambda:*)) to grant permission for all AWS Lambda actions."
    required: true
    type: str
  principal:
    description:
      -  "The principal who is getting this permission. It can be Amazon S3 service Principal (s3.amazonaws.com ) if
         you want Amazon S3 to invoke the function, an AWS account ID if you are granting cross-account permission, or
         any valid AWS service principal such as sns.amazonaws.com. For example, you might want to allow a custom
         application in another AWS account to push events to AWS Lambda by invoking your function."
    required: true
    type: str
  source_arn:
    description:
      -  This is optional; however, when granting Amazon S3 permission to invoke your function, you should specify this
         field with the bucket Amazon Resource Name (ARN) as its value. This ensures that only events generated from
         the specified bucket can invoke the function.
    type: str
  source_account:
    description:
      -  The AWS account ID (without a hyphen) of the source owner. For example, if O(source_arn) identifies a bucket,
         then this is the bucket owner's account ID. You can use this additional condition to ensure the bucket you
         specify is owned by a specific account (it is possible the bucket owner deleted the bucket and some other AWS
         account created the bucket). You can also use this condition to specify all sources (that is, you don't
         specify the O(source_arn)) owned by a specific account.
    type: str
  event_source_token:
    description:
      -  Token string representing source ARN or account. Mutually exclusive with O(source_arn) or O(source_account).
    type: str
extends_documentation_fragment:
  - amazon.aws.common.modules
  - amazon.aws.region.modules
  - amazon.aws.boto3
a  

- name: Lambda S3 event notification
  amazon.aws.lambda_policy:
    state: present
    function_name: functionName
    alias: Dev
    statement_id: lambda-s3-myBucket-create-data-log
    action: lambda:InvokeFunction
    principal: s3.amazonaws.com
    source_arn: arn:aws:s3:eu-central-1:123456789012:bucketName
    source_account: 123456789012
  register: lambda_policy_action

- name: show results
  ansible.builtin.debug:
    var: lambda_policy_action
z
---
lambda_policy_action:
    description: Describes what action was taken.
    returned: success
    type: str
    sample: "added"
    N)	to_native)is_boto3_error_code)AnsibleAWSModulec                     dj                  | j                  d      D cg c]  }|j                          c}      S c c}w )z
    Changes python key into Pascal case equivalent. For example, 'this_function_name' becomes 'ThisFunctionName'.

    :param key:
    :return:
     _)joinsplit
capitalize)keytokens     l/home/dcms/DCMS/lib/python3.12/site-packages/ansible_collections/amazon/aws/plugins/modules/lambda_policy.pypcr      s2     77CIIcNC5E$$&CDDCs   =c                 p    dD ]1  }| j                   j                  |      |j                  |      k7  s1 y y)N)action	principal
source_arnsource_accountevent_source_tokenFT)paramsget)modulecurrent_statementparams      r   policy_equalr      s<    ^ ==U#'8'<'<U'CC     c                     t               }|D ].  }| j                  j                  |      }|!||t        |      <   0 |S )z
    Sets module parameters to those expected by the boto3 API.

    :param module:
    :param module_params:
    :return:
    )dictr   r   r   )r   module_params
api_paramsr   module_params        r   set_api_paramsr"      sJ     J 1}}((/#$0Jr%y!1
 r   c                    | j                   d   }|j                  d      rRt        j                  d|      s| j	                  d| d       t        |      dkD  r| j	                  d| d	       yyt        j                  d
|      s| j	                  d| d       t        |      dkD  r| j	                  d| d       yy)zr
    Performs parameter validation beyond the module framework's validation.

    :param module:
    :return:
    function_namezarn:z
^[\w\-:]+$zARN zP is invalid. ARNs must contain only alphanumeric characters, hyphens and colons.msg   z
ARN name "z" exceeds 140 character limitz	^[\w\-]+$zFunction name zI is invalid. Names must contain only alphanumeric characters and hyphens.@   zFunction name "z" exceeds 64 character limitN)r   
startswithresearch	fail_jsonlen)r   r$   s     r   validate_paramsr.      s     MM/2M 'yy6=/)yz   }#:m_<Y!Z[ $ yy}5$]O3|}   }"?=/A]!^_ #r   c                     | j                   j                  d      t        | j                   d         S | j                   d   rt        | j                   d         S y)zh
    Returns the function qualifier as a version or alias or None.

    :param module:
    :return:
    versionNalias)r   r   r   )r   s    r   get_qualifierr2      sP     }}#/y122	w	w/00r   c                 t   d| vri S i }| d   D ]Z  }|d   |k(  s|d   |d<   	 |d   d   |d<   	 |d   d   |d<   	 |d	   d
   d   |d<   	 |d	   d   d   |d<   	 |d	   d   d   |d<    |S  |S # t         $ r Y Jw xY w# t         $ r Y Mw xY w# t         $ r Y Mw xY w# t         $ r Y Mw xY w# t         $ r Y  |S w xY w)zreturn flattened single policy statement from a policy

    If a policy statement is present in the policy extract it and
    return it in a flattened form.  Otherwise return an empty
    dictionary.
    	StatementSidActionr   	PrincipalServicer   AWS	ConditionArnLikezAWS:SourceArnr   StringEqualszAWS:SourceAccountr   zlambda:EventSourceTokenr   )KeyError)policysidpolicy_statement	statements       r   extract_statementrB      s_    & 	 K( 	Us")28)<X&09+0Fy0Q -09+0Fu0M -1:;1G	1RSb1c .5>{5KN5[\o5p !129B;9OP^9_-: !56
 76 -          	sW   A-A<B
BB)-	A98A9<	BB	BB	B&%B&)	B76B7c                    | j                   d   }t        | d      }t        |       }|r|j                  |       d}	  |j                  d
i |}t        j                  |j                  dd	            }t        ||      S # t        d      $ r i cY S t        j                  j                  t        j                  j                  f$ r}| j                  |d       Y d}~d}~ww xY w)zChecks that policy exists and if so, that statement ID is present or absent.

    :param module:
    :param client:
    :return:
    statement_id)r$   	QualifierNResourceNotFoundExceptionzretrieving function policyr%   Policyz{} )r   r"   r2   update
get_policyr   botocore
exceptionsClientErrorBotoCoreErrorfail_json_awsjsonloadsr   rB   )r   clientr?   r    	qualifierpolicy_resultser>   s           r   get_policy_statementrW     s     --
'C  (:;Jf%II.NB***8Z8 ZZ**8T:;FVS)) :; 	'')) B 	Q$@AA	Bs   B C&6C&	C!!C&c                 T   d}d}t        | |      }t        |       }|r|j                  |       | j                  s	  |j                  di | d}|S # t
        j                  j                  t
        j                  j                  f$ r}| j                  |d       Y d}~Sd}~ww xY w)	ze
    Adds a permission statement to the policy.

    :param module:
    :param aws:
    :return:
    F)r$   rD   r   r   r   r   r   rE   zadding permission to policyr%   NTrI   )
r"   r2   rJ   
check_modeadd_permissionrL   rM   rN   rO   rP   )r   rS   changedr   r    rT   rV   s          r   add_policy_permissionr\   "  s     GF  /Jf%II.	G!F!!/J/ N	 ##//1D1D1R1RS 	G  (E FF	Gs   A 7B'
B""B'c                 R   d}t        | d      }t        |       }|r|j                  |       	 | j                  s |j                  di | d}|S # t
        j                  j                  t
        j                  j                  f$ r}| j                  |d       Y d}~|S d}~ww xY w)	zj
    Removed a permission statement from the policy.

    :param module:
    :param aws:
    :return:
    F)r$   rD   rE   Tzremoving permission from policyr%   NrI   )
r"   r2   rJ   rY   remove_permissionrL   rM   rN   rO   rP   )r   rS   r[   r    rT   rV   s         r   remove_policy_permissionr_   F  s     G  (IJJf%II.G  $F$$2z2G N ++X-@-@-N-NO GQ$EFFNGs    A 7B&B!!B&c                 (   d}d}| j                   d   }d}t        | |      }|rd}|dk(  r?|dk(  r&t        | |      st        | |       t	        | |      }d}|dk(  s"t	        | |      }d}n|dk(  rt        | |      }d}t        |t        |	      
      S )NFabsentstatenonepresentupdatedaddeddeleted)lambda_policy_action)r[   ansible_facts)r   rW   r   r_   r\   r   )r   lambda_clientr[   current_staterb   action_takencurrent_policy_statements          r   manage_statern   a  s    GMMM'"EL  4FMJ!	I%l6C[.\$V];+FMBG$L	)+FMBG"L	)	#*6=A t/VWWr   c                  &   t        t        dddg      t        dddg      t        ddg      t               t        d	
      t        d      t        d      t               t               t        d      
      } t        | dddgddgddgg      S )Nrd   ra   )defaultchoicesTlambda_function_arnfunction_arn)requiredaliasesr?   int)type)rt   F)no_log)
rb   r$   rD   r1   r0   r   r   r   r   r   r1   r0   r   r   r   )argument_specsupports_check_modemutually_exclusive)r   r   )ry   s    r   setup_module_objectr|   |  s    9y(.CDD3H.2YZ4%9f% 
 
 6vu-M" # i !<0!#34
 r   c                      t               } | j                  d      }t        |        t        | |      } | j                  di | y)z<
    Main entry point.

    :return dict: ansible facts
    lambdaNrI   )r|   rS   r.   rn   	exit_json)r   rS   resultss      r   mainr     sA     !"F]]8$FF66*GFwr   __main__)DOCUMENTATIONEXAMPLESRETURNrQ   r*   rL   ImportErroransible.module_utils._textr   <ansible_collections.amazon.aws.plugins.module_utils.botocorer   ;ansible_collections.amazon.aws.plugins.module_utils.modulesr   r   r   r"   r.   r2   rB   rW   r\   r_   rn   r|   r   __name__rI   r   r   <module>r      s   Sj&
  		 1 \ XE&`6 'T*@!H6X6:  zF U	  		s   A A A 