
    VhR                         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
 Zd Z G d d      Z G d d      Zd Zedk(  r e        yy# e$ r Y Pw xY w)a  
---
module: cloudwatchevent_rule
version_added: 5.0.0
short_description: Manage CloudWatch Event rules and targets
description:
  - This module creates and manages CloudWatch event rules and targets.
  - This module was originally added to C(community.aws) in release 1.0.0.
extends_documentation_fragment:
  - amazon.aws.common.modules
  - amazon.aws.region.modules
  - amazon.aws.boto3

author:
  - "Jim Dalton (@jsdalton) <jim.dalton@gmail.com>"
notes:
  - A rule must contain at least an O(event_pattern) or O(schedule_expression). A
    rule can have both an O(event_pattern) and a O(schedule_expression), in which
    case the rule will trigger on matching events as well as on a schedule.
  - When specifying targets, O(targets.input), O(targets.input_path),
    O(targets.input_transformer.input_paths_map) and O(targets.input_transformer.input_template)
    are mutually-exclusive and optional parameters.
options:
  name:
    description:
      - The name of the rule you are creating, updating or deleting. No spaces
        or special characters allowed (i.e. must match C([\.\-_A-Za-z0-9]+)).
    required: true
    type: str
  schedule_expression:
    description:
      - A cron or rate expression that defines the schedule the rule will
        trigger on. For example, C(cron(0 20 * * ? *)), C(rate(5 minutes)).
    required: false
    type: str
  event_pattern:
    description:
      - A string pattern that is used to match against incoming events to determine if the rule
        should be triggered.
    required: false
    type: json
  state:
    description:
      - Whether the rule is present (and enabled), disabled, or absent.
    choices: ["present", "disabled", "absent"]
    default: present
    required: false
    type: str
  description:
    description:
      - A description of the rule.
    required: false
    type: str
  role_arn:
    description:
      - The Amazon Resource Name (ARN) of the IAM role associated with the rule.
    required: false
    type: str
  targets:
    type: list
    elements: dict
    default: []
    description:
      - A list of targets to add to or update for the rule.
    suboptions:
      id:
        type: str
        required: true
        description: The unique target assignment ID.
      arn:
        type: str
        required: true
        description: The ARN associated with the target.
      role_arn:
        type: str
        description: The ARN of the IAM role to be used for this target when the rule is triggered.
      input:
        type: json
        description:
          - A JSON object that will override the event data passed to the target.
          - If neither O(targets.input) nor O(targets.input_path) nor O(targets.input_transformer)
            is specified, then the entire event is passed to the target in JSON form.
      input_path:
        type: str
        description:
          - A JSONPath string (e.g. V($.detail)) that specifies the part of the event data to be
            passed to the target.
          - If neither O(targets.input) nor O(targets.input_path) nor O(targets.input_transformer)
            is specified, then the entire event is passed to the target in JSON form.
      input_transformer:
        type: dict
        description:
          - Settings to support providing custom input to a target based on certain event data.
        version_added: 4.1.0
        version_added_collection: community.aws
        suboptions:
          input_paths_map:
            type: dict
            description:
              - A dict that specifies the transformation of the event data to
                custom input parameters.
          input_template:
            type: json
            description:
              - A string that templates the values input_paths_map extracted from the event data.
                It is used to produce the output you want to be sent to the target.
      ecs_parameters:
        type: dict
        description:
          - Contains the ECS task definition and task count to be used, if the event target is an ECS task.
        suboptions:
          task_definition_arn:
            type: str
            description: The full ARN of the task definition.
            required: true
          task_count:
            type: int
            description: The number of tasks to create based on task definition.
    required: false
a  
- amazon.aws.cloudwatchevent_rule:
    name: MyCronTask
    schedule_expression: "cron(0 20 * * ? *)"
    description: Run my scheduled task
    targets:
      - id: MyTargetId
        arn: arn:aws:lambda:us-east-1:123456789012:function:MyFunction

- amazon.aws.cloudwatchevent_rule:
    name: MyDisabledCronTask
    schedule_expression: "rate(5 minutes)"
    description: Run my disabled scheduled task
    state: disabled
    targets:
      - id: MyOtherTargetId
        arn: arn:aws:lambda:us-east-1:123456789012:function:MyFunction
        input: '{"foo": "bar"}'

- amazon.aws.cloudwatchevent_rule:
    name: MyInstanceLaunchEvent
    description: "Rule for EC2 instance launch"
    state: present
    event_pattern: '{"source":["aws.ec2"],"detail-type":["EC2 Instance State-change Notification"],"detail":{"state":["pending"]}}'
    targets:
      - id: MyTargetSnsTopic
        arn: arn:aws:sns:us-east-1:123456789012:MySNSTopic
        input_transformer:
          input_paths_map:
            instance: "$.detail.instance-id"
            state: "$.detail.state"
          input_template: "<instance> is in state <state>"

- amazon.aws.cloudwatchevent_rule:
    name: MyCronTask
    state: absent
a  
rule:
    description: CloudWatch Event rule data.
    returned: success
    type: dict
    contains:
      name:
        description:
          - The name of the rule you are creating, updating or deleting.
        returned: success
        type: str
        sample: "MyCronTask"
      schedule_expression:
        description:
          - A cron or rate expression that defines the schedule the rule will trigger on.
        returned: success
        type: str
        sample: 'cron(0 20 * * ? *)'
      state:
        description:
          - Whether the rule is present (and enabled), disabled, or absent.
        returned: success
        type: str
        sample: "enabled"
      description:
        description:
          - A description of the rule.
        returned: success
        type: str
        sample: "Run my scheduled task"
      arn:
        description: The ARN associated with the rule.
        type: str
        returned: success
        sample: 'arn:aws:events:us-east-1:123456789012:rule/MyCronTask'
targets:
    description: CloudWatch Event target(s) assigned to the rule.
    returned: success
    type: list
    elements: dict
    contains:
      id:
        description: The unique target assignment ID.
        type: str
        returned: success
        sample: 'MyTargetId'
      arn:
        description: The ARN associated with the target.
        type: str
        returned: success
        sample: 'arn:aws:lambda:us-east-1:123456789012:function:MyFunction'
    N)camel_dict_to_snake_dict)snake_dict_to_camel_dict)is_boto3_error_code)AnsibleAWSModule)scrub_none_parametersc                     	 t        j                  |        | S # t         j                  j                  $ r! t	        t        j
                  |             cY S w xY wN)jsonloadsdecoderJSONDecodeErrorstrdumps)json_strings    s/home/dcms/DCMS/lib/python3.12/site-packages/ansible_collections/amazon/aws/plugins/modules/cloudwatchevent_rule.py_format_jsonr      sF    ,

;<<'' ,4::k*++,s    ;AAc                 b    	 t        j                  |        y# t         j                  $ r Y yw xY w)NTF)r
   r   r   )ss    r   _validate_jsonr      s-    

1 s    ..c                   T    e Zd Z	 ddZd ZddZd Zd Zd Zd Z	d	 Z
d
 Zd Zd Zy)CloudWatchEventRuleNc                 t    || _         || _        d| _        || _        || _        || _        || _        || _        y )NF)nameclientchangedschedule_expressionevent_patterndescriptionrole_arnmodule)selfr    r   r   r   r   r   r   s           r   __init__zCloudWatchEventRule.__init__   s?     	#6 *&     c                 x   	 | j                   j                  | j                        }t        |      S # t        d      $ r i cY S t        j
                  j                  t        j
                  j                  f$ r>}| j                  j                  |d| j                          Y d}~t              S d}~ww xY w)z/Returns the existing details of the rule in AWSNameResourceNotFoundExceptionzCould not describe rule msgN)r   describe_ruler   r   botocore
exceptionsBotoCoreErrorClientErrorr    fail_json_awsr   )r!   	rule_infoes      r   describezCloudWatchEventRule.describe  s    	U11tyy1AI (	22 ##>? 	I--++
 	U KK%%a/G		{-S%TT'	22	Us   &3 B96B9;*B44B9c                 (   | j                   |rdndd}| j                  r| j                  |d<   | j                  r| j                  |d<   | j                  r| j                  |d<   | j                  r| j                  |d<   	  | j
                  j                  di |}d| _        S # t        j                  j                  t        j                  j                  f$ r4}| j                  j                  |d| j                    	       Y d
}~od
}~ww xY w)z"Creates or updates the rule in AWSENABLEDDISABLED)r&   StateScheduleExpressionEventPatternDescriptionRoleArnzCould not create/update rule r(   NT )r   r   r   r   r   r   put_ruler+   r,   r-   r.   r    r/   r   )r!   enabledrequestresponser1   s        r   putzCloudWatchEventRule.put  s     II")Yz
 ##,0,D,DG()&*&8&8GN#%)%5%5GM"==!%GI	Z+t{{++6g6H  ##1183F3F3R3RS 	ZKK%%a/LTYYK-X%YY	Zs   B& &7D*DDc                 ^   | j                          	 | j                  j                  | j                        }d| _
        S # t        j
                  j                  t        j
                  j                  f$ r4}| j                  j                  |d| j                          Y d}~od}~ww xY w)zDeletes the rule in AWSr%   zCould not delete rule r(   NT)remove_all_targetsr   delete_ruler   r+   r,   r-   r.   r    r/   r   r!   r?   r1   s      r   deletezCloudWatchEventRule.delete*  s    !	S{{..DII.>H  ##1183F3F3R3RS 	SKK%%a/Edii[-Q%RR	Ss   &A 7B,8*B''B,c                 >   	 | j                   j                  | j                        }d| _	        S # t        j                  j
                  t        j                  j                  f$ r4}| j                  j                  |d| j                          Y d}~od}~ww xY w)zEnables the rule in AWSr%   zCould not enable rule r(   NT)
r   enable_ruler   r+   r,   r-   r.   r    r/   r   rD   s      r   enablezCloudWatchEventRule.enable5  s    	S{{..DII.>H  ##1183F3F3R3RS 	SKK%%a/Edii[-Q%RR	S   &1 7B(*BBc                 >   	 | j                   j                  | j                        }d| _	        S # t        j                  j
                  t        j                  j                  f$ r4}| j                  j                  |d| j                          Y d}~od}~ww xY w)zDisables the rule in AWSr%   zCould not disable rule r(   NT)
r   disable_ruler   r+   r,   r-   r.   r    r/   r   rD   s      r   disablezCloudWatchEventRule.disable>  s    	T{{//TYY/?H  ##1183F3F3R3RS 	TKK%%a/Ftyyk-R%SS	TrI   c                 j   	 | j                   j                  | j                        }t              d   S # t        d      $ r g cY S t        j
                  j                  t        j
                  j                  f$ r4}| j                  j                  |d| j                          Y d}~d}~ww xY w)z.Lists the existing targets for the rule in AWS)Ruler'   zCould not find target for rule r(   Ntargets)r   list_targets_by_ruler   r   r+   r,   r-   r.   r    r/   r   )r!   rO   r1   s      r   list_targetsz CloudWatchEventRule.list_targetsG  s    	\kk66DII6FG (0;; ##>? 	I--++
 	\ KK%%a/Ntyyk-Z%[[		\s   &6 B26B2>*B--B2c                 l   |sy| j                   | j                  |      d}	  | j                  j                  di |}d| _
        S # t        j
                  j                  t        j
                  j                  f$ r4}| j                  j                  |d| j                           Y d}~od}~ww xY w)z:Creates or updates the provided targets on the rule in AWSN)rN   Targetsz.Could not create/update rule targets for rule r(   Tr;   )r   _targets_requestr   put_targetsr+   r,   r-   r.   r    r/   r   )r!   rO   r>   r?   r1   s        r   rU   zCloudWatchEventRule.put_targetsT  s    II,,W5
	k.t{{..99H  ##1183F3F3R3RS 	kKK%%a/]^b^g^g]h-i%jj	ks   A 7B3?*B..B3c                 N   |sy| j                   |d}	  | j                  j                  di |}d| _	        S # t        j                  j
                  t        j                  j                  f$ r4}| j                  j                  |d| j                           Y d}~od}~ww xY w)z1Removes the provided targets from the rule in AWSN)rN   Idsz(Could not remove rule targets from rule r(   Tr;   )
r   r   remove_targetsr+   r,   r-   r.   r    r/   r   )r!   
target_idsr>   r?   r1   s        r   rX   z"CloudWatchEventRule.remove_targetsc  s    99Z8	e1t{{11<G<H  ##1183F3F3R3RS 	eKK%%a/WX\XaXaWb-c%dd	es   9 7B$0*BB$c                 p    | j                         }| j                  |D cg c]  }|d   	 c}      S c c}w )zRemoves all targets on ruleid)rQ   rX   )r!   rO   ts      r   rB   z&CloudWatchEventRule.remove_all_targetso  s3    ##%""W#=AdG#=>>#=s   3c                    g }|D ]  }t        t        |d            }|j                  dd      rt        |d         |d<   |j                  dd      rg|j                  d      j                  dd      rt        |d   d         |d   d<   |j                  d      j                  dd      r|d   d   |d   d<   |j	                  |        |S )	z#Formats each target for the requestTInputNInputTransformerInputTemplateInputPathsMapinput_transformerinput_paths_map)r   r   getr   append)r!   rO   targets_requesttargettarget_requests        r   rT   z$CloudWatchEventRule._targets_requestt  s     	3F23KFTX3YZN!!'40*6~g7N*Ow'!!"4d;!%%&89==otTJV&'9:?KKN#56G "%%&89==otTJPQdJefwJxN#56G"">2	3 r#   )NNNNT)__name__
__module____qualname__r"   r2   r@   rE   rH   rL   rQ   rU   rX   rB   rT   r;   r#   r   r   r      s<    mq
3*	<
?
r#   r   c                   j    e Zd Zg dZd ZddZd Zd Zd ZddZ	d Z
dd	Zdd
Zd Zd Zd Zd Zy)CloudWatchEventRuleManager)r   r   r   r   r   c                      || _         || _        y r	   )rulerO   )r!   rp   rO   s      r   r"   z#CloudWatchEventRuleManager.__init__  s    	r#   c                     | j                   j                         }|r3| j                  |       | j                          | j	                  |       y| j                  |       y)z3Ensures the rule and targets are present and syncedN)rp   r2   
_sync_rule_sync_targets_sync_state_create)r!   r=   rule_descriptions      r   ensure_presentz)CloudWatchEventRuleManager.ensure_present  sL    99--/OOG$ W% LL!r#   c                 (    | j                  d       y)zBEnsures the rule and targets are present, but disabled, and syncedF)r=   N)rw   )r!   s    r   ensure_disabledz*CloudWatchEventRuleManager.ensure_disabled  s    E*r#   c                 r    | j                   j                         }|sy| j                   j                          y)z'Ensures the rule and targets are absentN)rp   r2   rE   )r!   rv   s     r   ensure_absentz(CloudWatchEventRuleManager.ensure_absent  s+    99--/		r#   c                     i g | j                   j                  d}| j                   j                         }|s|S |d= ||d<   |d   j                  | j                   j	                                |S )z(Retrieves rule and target state from AWS)rp   rO   r   response_metadatarp   rO   )rp   r   r2   extendrQ   )r!   	aws_staterv   s      r   fetch_aws_statez*CloudWatchEventRuleManager.fetch_aws_state  so    B499;L;LM	99--/ 01,	&)##DII$:$:$<=r#   c                 \    | j                         s| j                  j                  |       yy)Syncs local rule state with AWSN)_rule_matches_awsrp   r@   r!   r=   s     r   rr   z%CloudWatchEventRuleManager._sync_rule  s#    %%'IIMM'" (r#   c                     | j                         }|r| j                  j                  |       | j                         }|r| j                  j	                  |       yy)zSyncs local targets with AWSN)_remote_target_ids_to_removerp   rX   _targets_to_putrU   )r!   target_ids_to_removetargets_to_puts      r   rs   z(CloudWatchEventRuleManager._sync_targets  sS      $@@BII$$%9: --/II!!.1 r#   c                     | j                         }|r |dk7  r| j                  j                          y|s!|dk7  r| j                  j                          yyy)r   r4   r5   N)_remote_staterp   rH   rL   )r!   r=   remote_states      r   rt   z&CloudWatchEventRuleManager._sync_state  sK    ))+|y0II\Z7II 8r#   c                     | j                   j                  |       | j                   j                  | j                         y)zCreates rule and targets on AWSN)rp   r@   rU   rO   r   s     r   ru   z"CloudWatchEventRuleManager._create  s(    		g		dll+r#   c                 x      j                   j                         t         fd j                  D              S )z)Checks if the local rule data matches AWSc              3   p   K   | ]-  }t        j                  |      j                  |d       k(   / y wr	   )getattrrp   rd   ).0fieldaws_rule_datar!   s     r   	<genexpr>z?CloudWatchEventRuleManager._rule_matches_aws.<locals>.<genexpr>  s/     mSX7499e,0A0A%0NNms   36)rp   r2   allRULE_FIELDS)r!   r   s   `@r   r   z,CloudWatchEventRuleManager._rule_matches_aws  s/    		**, m\`\l\lmmmr#   c                 X   | j                   j                         }g }| j                  D ]L  }|d   +|d   d   #|d   d   }t        |      }|sd|z   dz   |d   d<   |j	                  t        |             N || _        | j                  D cg c]  }t        |      |vs| c}S c c}w )zCReturns a list of targets that need to be updated or added remotelyrb   input_template")rp   rQ   rO   r   re   r   r   )r!   remote_targetstempr\   val
valid_jsons         r   r   z*CloudWatchEventRuleManager._targets_to_put  s    //1  	2A$%1a8K6LM]6^6j +,-=>
 ,C0
!?BSy3A)*+;<KK-a01	2   <<]a+CA+Fn+\]]]s   B' B'c                     | j                   D cg c]  }|d   	 }}| j                  j                         }|D cg c]  }|d   |vs|d    c}S c c}w c c}w )z:Returns a list of targets that need to be removed remotelyr[   )rO   rp   rQ   )r!   r\   rY   r   rts        r   r   z7CloudWatchEventRuleManager._remote_target_ids_to_remove  sW    '+||4!ag4
4//1#1PRRXZ5O4PP 5Ps   AAAc                 F    | j                   j                         }|sy|d   S )z!Returns the remote state from AWSNstate)rp   r2   )r!   r   s     r   r   z(CloudWatchEventRuleManager._remote_state  s%    ii((*7##r#   Nri   )rj   rk   rl   r   r"   rw   ry   r{   r   rr   rs   rt   ru   r   r   r   r   r;   r#   r   rn   rn     sK    ]K
"+#

2 ,
n^0Q$r#   rn   c                  B   t        ddg t        t        dd      t        dd      t        d      t        d      t        d      t        dt        t        d      t        d            	      t        dt        t        dd      t        d
            	                  } t        t        d      t               t        d      t        g dd      t               t               |       }t        |      }t        t        j                  D cg c]  }||j                  j                  |      f! c}      }|j                  j                  d      }|j                  j                  d      }|j                  d      }t        |fd|i|}t        ||      }	|dk(  r|	j                          nB|dk(  r|	j                          n,|dk(  r|	j                          n|j                  d| d        |j                  di |	j                          y c c}w )Nlistdictr   T)typerequired)r   r
   )rc   r   )r   optionsint)task_definition_arn
task_count)r[   arnr   input
input_pathrb   ecs_parameters)r   elementsdefaultr   )r   )presentdisabledabsentr   )choicesr   )r   r   r   r   r   r   rO   )argument_specrO   r   eventsr   r   r   zInvalid state 'z
' providedr(   r;   )r   r   rn   r   paramsrd   r   r   rw   ry   r{   	fail_json	exit_jsonr   )
target_argsr   r    rf	rule_datarO   r   r   cwe_rulecwe_rule_managers
             r   mainr     s   .%$/u%F#'"$(f$5#'V#4  (,%$(G#/
	K4 4  F'<iPFM M:F<V<b<bcbr6==,,R01cdImm	*GMMg&E]]8$F"6F&FIFH1(GD	'')	*	((*	(	&&(ugZ@AF:'779:# ds   $H__main__)DOCUMENTATIONEXAMPLESRETURNr
   r+   ImportError0ansible.module_utils.common.dict_transformationsr   r   <ansible_collections.amazon.aws.plugins.module_utils.botocorer   ;ansible_collections.amazon.aws.plugins.module_utils.modulesr   Bansible_collections.amazon.aws.plugins.module_utils.transformationr   r   r   r   rn   r   rj   r;   r#   r   <module>r      s   wr$L3
j 	 V U \ X d,H HVv$ v$r7;t zF u
  		s   A A! A!