
    VhFj              "          d Z dZd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dlmZ ddlmZ  e edddgd       edddg       edd e edd       edd       edd       edd       edd       edd       ed e ed       ed             !       ed       edd e edd       ed e ed       ed             !      "      #       ed$d%      &
      #       edd e edd'g(       ed e edd)d*g(      +      !      ,      #       ed       edd-d.g/       edd$0      1      Zd2dd3d4gfd2dd3gfgZdZ	 	 	 dMd5ed6ed7ee   d8ee   d9ee   d:efd;ZdNd<ed6ed7ed=ed:ef
d>Zd5ed?ed:efd@ZdAedBed:efdCZd5edDed:efdEZ 	 dOd5edFee   dGedHee   fdIZ!d5ed8ed:efdJZ"dK Z#e$dLk(  r e#        yy# e$ r Y w xY w)Pa#  
---
module: backup_plan
version_added: 6.0.0
short_description: Manage AWS Backup Plans
description:
  - Creates, updates, or deletes AWS Backup Plans.
  - For more information see the AWS documentation for Backup plans U(https://docs.aws.amazon.com/aws-backup/latest/devguide/about-backup-plans.html).
author:
  - Kristof Imre Szabo (@krisek)
  - Alina Buzachis (@alinabuzachis)
  - Helen Bailey (@hakbailey)
options:
  state:
    description:
      - Create/update or delete a backup plan.
    type: str
    default: present
    choices: ['present', 'absent']
  backup_plan_name:
    description:
      - The display name of a backup plan. Must contain 1 to 50 alphanumeric or '-_.' characters.
    type: str
    required: true
    aliases: ['name']
  rules:
    description:
      - An array of BackupRule objects, each of which specifies a scheduled task that is used to back up a selection of resources.
      - Required when O(state=present).
    type: list
    elements: dict
    suboptions:
      rule_name:
        description: Name of the rule.
        type: str
        required: true
      target_backup_vault_name:
        description: Name of the Backup Vault this rule should target.
        type: str
        required: true
      schedule_expression:
        description: A CRON expression in UTC specifying when Backup initiates a backup
          job. AWS default is used if not supplied.
        type: str
        default: 'cron(0 5 ? * * *)'
      start_window_minutes:
        description:
          - A value in minutes after a backup is scheduled before a job will be
            canceled if it doesn't start successfully. If this value is included, it
            must be at least 60 minutes to avoid errors.
          - AWS default if not supplied is V(480).
        type: int
        default: 480
      completion_window_minutes:
        description:
          - A value in minutes after a backup job is successfully started before it
            must be completed or it will be canceled by Backup.
          - AWS default if not supplied is V(10080).
        type: int
        default: 10080
      lifecycle:
        description:
          - The lifecycle defines when a protected resource is transitioned to cold
            storage and when it expires. Backup will transition and expire backups
            automatically according to the lifecycle that you define.
          - Backups transitioned to cold storage must be stored in cold storage for a
            minimum of 90 days. Therefore, the "retention" setting must be 90 days
            greater than the "transition to cold after days" setting. The "transition
            to cold after days" setting cannot be changed after a backup has been
            transitioned to cold.
        type: dict
        suboptions:
          move_to_cold_storage_after_days:
            description: Specifies the number of days after creation that a recovery point is moved to cold storage.
            type: int
          delete_after_days:
            description: Specifies the number of days after creation that a recovery
              point is deleted. Must be greater than V(90) days plus
              O(rules.lifecycle.move_to_cold_storage_after_days).
            type: int
      recovery_point_tags:
        description: To help organize your resources, you can assign your own metadata to the resources that you create.
        type: dict
      copy_actions:
        description: An array of copy_action objects, which contains the details of the copy operation.
        type: list
        elements: dict
        suboptions:
          destination_backup_vault_arn:
            description: An Amazon Resource Name (ARN) that uniquely identifies the destination backup vault for the copied backup.
            type: str
            required: true
          lifecycle:
            description:
              - Contains an array of Transition objects specifying how long in days
                before a recovery point transitions to cold storage or is deleted.
              - Backups transitioned to cold storage must be stored in cold storage for
                a minimum of 90 days. Therefore, on the console, the "retention"
                setting must be 90 days greater than the "transition to cold after
                days" setting. The "transition to cold after days" setting cannot be
                changed after a backup has been transitioned to cold.
            type: dict
            suboptions:
              move_to_cold_storage_after_days:
                description: Specifies the number of days after creation that a
                  recovery point is moved to cold storage.
                type: int
              delete_after_days:
                description: Specifies the number of days after creation that a
                  recovery point is deleted. Must be greater than V(90) days plus
                   O(rules.copy_actions.lifecycle.move_to_cold_storage_after_days).
                type: int
      enable_continuous_backup:
        description:
          - Specifies whether Backup creates continuous backups. True causes Backup to
            create continuous backups capable of point-in-time restore (PITR). False
            (or not specified) causes Backup to create snapshot backups.
          - AWS default if not supplied is V(false).
        type: bool
        default: false
      schedule_expression_timezone:
        description:
          - This is the timezone in which the schedule expression is set.
          - By default, ScheduleExpressions are in UTC. You can modify this to a specified timezone.
          - This option requires botocore >= 1.31.36.
        type: str
        default: "Etc/UTC"
        required: false
        version_added: 7.3.0
  advanced_backup_settings:
    description:
      - Specifies a list of advanced backup settings for each resource type.
      - These settings are only available for Windows Volume Shadow Copy Service (VSS) backup jobs.
    required: false
    type: list
    elements: dict
    suboptions:
      resource_type:
        description:
          - Specifies an object containing resource type and backup options.
          - The only supported resource type is Amazon EC2 instances with Windows Volume Shadow Copy Service (VSS).
        type: str
        choices: ['EC2']
      backup_options:
        description:
          - Specifies the backup option for a selected resource.
          - This option is only available for Windows VSS backup jobs.
        type: dict
        suboptions:
          WindowsVSS:
            description: Enable or disable WindowsVSS backup option.
            type: str
            choices: ['enabled', 'disabled']
  creator_request_id:
    description: Identifies the request and allows failed requests to be retried
      without the risk of running the operation twice. If the request includes a
      CreatorRequestId that matches an existing backup plan, that plan is returned.
    type: str
  tags:
    description: To help organize your resources, you can assign your own metadata to
      the resources that you create. Each tag is a key-value pair. The specified tags
      are assigned to all backups created with this plan.
    type: dict
    aliases: ['resource_tags', 'backup_plan_tags']

extends_documentation_fragment:
  - amazon.aws.common.modules
  - amazon.aws.region.modules
  - amazon.aws.boto3
  - amazon.aws.tags
a4  
- name: Create an AWSbackup plan
  amazon.aws.backup_plan:
    state: present
    backup_plan_name: elastic
    rules:
      - rule_name: daily
        advanced_backup_settings:
          - resource_type: "EC2"
            backup_options:
              WindowsVSS: enabled
        target_backup_vault_name: "{{ backup_vault_name }}"
        schedule_expression: 'cron(0 5 ? * * *)'
        start_window_minutes: 60
        completion_window_minutes: 1440
- name: Delete an AWS Backup plan
  amazon.aws.backup_plan:
    backup_plan_name: elastic
    state: absent
a  
exists:
  description: Whether the resource exists.
  returned: always
  type: bool
  sample: true
backup_plan_arn:
  description: ARN of the backup plan.
  returned: always
  type: str
  sample: arn:aws:backup:eu-central-1:111122223333:backup-plan:1111f877-1ecf-4d79-9718-a861cd09df3b
backup_plan_id:
  description: ID of the backup plan.
  returned: always
  type: str
  sample: "1111f877-1ecf-4d79-9718-a861cd09df3b"
backup_plan_name:
  description: Name of the backup plan.
  returned: always
  type: str
  sample: elastic
creation_date:
  description: Creation date of the backup plan.
  returned: on create/update
  type: str
  sample: '2023-01-24T10:08:03.193000+01:00'
deletion_date:
  description: Date the backup plan was deleted.
  returned: on delete
  type: str
  sample: '2023-05-05T16:24:51.987000-04:00'
version_id:
  description: Version ID of the backup plan.
  returned: always
  type: str
  sample: ODM3MjVjNjItYWFkOC00NjExLWIwZTYtZDNiNGI5M2I0ZTY1
backup_plan:
  description: Backup plan details.
  returned: on create/update
  type: dict
  contains:
    backup_plan_name:
      description: The display name of a backup plan.
      returned: always
      type: str
      sample: elastic
    rules:
      description:
        - An array of BackupRule objects, each of which specifies a scheduled task that is used to back up a selection of resources.
      returned: always
      type: list
      elements: dict
      contains:
        rule_name:
          description: A display name for a backup rule.
          returned: always
          type: str
          sample: "daily"
        target_backup_vault_name:
          description: The name of a logical container where backups are stored.
          returned: always
          type: str
          sample: "09da67966fd5-backup-vault"
        schedule_expression:
          description: A cron expression in UTC specifying when Backup initiates a backup job.
          returned: always
          type: str
          sample: "cron(0 5 ? * * *)"
        start_window_minutes:
          description:
            - A value in minutes after a backup is scheduled before a job will be canceled if it
              doesn't start successfully.
          type: int
          returned: always
          sample: 480
        completion_window_minutes:
          description:
            - A value in minutes after a backup job is successfully started before it must be
              completed or it will be canceled by Backup.
          type: int
          returned: always
          sample: 10080
        lifecycle:
          description:
            - Defines when a protected resource is transitioned to cold storage and when it expires.
          type: dict
          returned: when configured.
          sample: {
                    "delete_after_days": 100,
                    "move_to_cold_storage_after_days": 10
                  }
        recovery_point_tags:
          description:
            - An array of key-value pair strings that are assigned to resources that are associated with
              this rule when restored from backup.
          type: dict
          returned: when configured.
          sample: {
                    "Tagkey1": "TagValue1",
                    "Tagkey2": "TagValue2"
                  }
        rule_id:
          description:
            - Uniquely identifies a rule that is used to schedule the backup of a selection of resources.
          type: str
          returned: always
          sample: "973621ef-d863-41ef-b5c3-9e943a64ad0c"
        copy_actions:
          description: An array of CopyAction objects, which contains the details of the copy operation.
          returned: when configured.
          type: list
          elements: dict
          sample: [
                    {
                      "destination_backup_vault_arn": "arn:aws:backup:us-west-2:123456789012:backup-vault:my-test-vault",
                      "lifecycle": {
                          "delete_after_days": 100,
                          "move_to_cold_storage_after_days": 10
                      }
                    }
                  ]
        enable_continous_backup:
          description: Specifies whether Backup creates continuous backups.
          type: bool
          returned: always
          sample: false
        schedule_expression_timezone:
          description:
            - This is the timezone in which the schedule expression is set.
            - This information is returned for botocore versions >= 1.31.36.
          type: str
          returned: when botocore >= 1.31.36
          sample: "Etc/UTC"
          version_added: 7.3.0
    advanced_backup_settings:
      description: Advanced backup settings of the backup plan.
      returned: when configured.
      type: list
      elements: dict
      sample: [
                {
                  "backup_options": {
                      "windows_vss": "enabled"
                  },
                  "resource_type": "EC2"
                }
              ]
      contains:
        resource_type:
          description: Resource type of the advanced settings.
          type: str
          sample: "EC2"
        backup_options:
          description: Backup options of the advanced settings.
          type: dict
          sample: {
                    "windows_vss": "enabled"
                  }
    tags:
      description: Tags of the backup plan.
      returned: on create/update
      type: str
      sample: {
                "TagKey1": "TagValue1",
                "TagKey2": "TagValue2"
              }
    N)datetime)Optional)camel_dict_to_snake_dict)snake_dict_to_camel_dict)get_plan_details)AnsibleAWSModule)compare_aws_tags)scrub_none_parameters)BotoCoreError)ClientErrorstrpresentabsent)typechoicesdefaultTname)requiredr   aliaseslistdict)r   r   zcron(0 5 ? * * *))r   r   inti  i`'  zEtc/UTC)r   )move_to_cold_storage_after_daysdelete_after_days)r   options)destination_backup_vault_arn	lifecycle)r   elementsr   boolF)
	rule_nametarget_backup_vault_nameschedule_expressionstart_window_minutescompletion_window_minutesschedule_expression_timezoner   recovery_point_tagscopy_actionsenable_continuous_backupEC2)r   r   enableddisabled)
WindowsVSS)resource_typebackup_optionsbackup_plan_tagsresource_tags)r   r   )r   r   )statebackup_plan_namerulesadvanced_backup_settingscreator_request_idtags
purge_tagsr1   r2   r3   moduleplanr6   backup_plan_id	operationreturnc           	          dt        |j                         D ci c]  \  }}|dk7  s|| c}}d      i}|dk(  r|r||d<   | j                  d   }|r||d<   |S |d	k(  r||d
<   |S c c}}w )a|  
    Formats plan details to match boto3 backup client param expectations.

    module : AnsibleAWSModule object
    plan: Dict of plan details including name, rules, and advanced settings
    tags: Dict of plan tags
    backup_plan_id: ID of backup plan to update, only needed for update operation
    operation: Operation to add specific params for, either create or update
    
BackupPlanr2   T)capitalize_firstcreateBackupPlanTagsr5   CreatorRequestIdupdateBackupPlanId)r   itemsparams)	r8   r9   r6   r:   r;   kvrF   r5   s	            j/home/dcms/DCMS/lib/python3.12/site-packages/ansible_collections/amazon/aws/plugins/modules/backup_plan.pyformat_client_paramsrJ     s    " 	."jjlFdaa3E.EQTF!
F H'+F#$#]]+?@);F%&
 M 
h	!/~M Gs
   A(A(	plan_namedeletec           
          t        j                         j                         }|r| dd|ddS | dd|d| |d   |d   |ddS )a  
    Formats plan details in check mode to match result expectations.

    plan_name: Name of backup plan
    plan: Dict of plan details including name, rules, and advanced settings
    tags: Optional dict of plan tags
    delete: Whether the response is for a delete action
     )r2   r:   backup_plan_arndeletion_date
version_idr3   r4   )r2   r3   r4   r6   )r2   r:   rO   creation_daterQ   backup_plan)r   now	isoformat)rK   r9   r6   rL   	timestamps        rI   format_check_mode_responserW     sj     ((*I ) !&
 	
 !* !&$-g,01K,L	
 	
    create_paramsc                     	  |j                   di |}|S # t        t        f$ r}| j                  |d       Y d}~S d}~ww xY w)z
    Creates a backup plan.

    module : AnsibleAWSModule object
    client : boto3 backup client connection object
    create_params : The boto3 backup client parameters to create a backup plan
    z"Failed to create backup plan {err}msgN )create_backup_planr   r   fail_json_aws)r8   clientrY   responseerrs        rI   r^   r^     ^    L,6,,=}= O	 	 L 	S&JKKOL    A>Aexisting_plannew_planc                    d}t        j                  | d   d   D cg c],  }|j                         D ci c]  \  }}|dk7  s|| c}}. c}}}d      }t        j                  |d   d      }|r||k7  rd}t        j                  | d   j                  dg       d      }t        j                  |j                  dg       d      }	||	k7  rd}|S c c}}w c c}}}w )a.  
    Determines whether existing and new plan rules/settings match.

    existing_plan: Dict of existing plan details including rules and advanced settings,
        in snake-case format
    new_plan: Dict of existing plan details including rules and advanced settings, in
        snake-case format
    FrS   r3   rule_idT)	sort_keysr4   )jsondumpsrE   get)
re   rf   update_neededrulekeyvalexisting_rules	new_rules!existing_advanced_backup_settingsnew_advanced_backup_settingss
             rI   plan_update_neededru     s     M ZZQ^_lQmnuQvww4::<	DxsC3)3C#s(	DwN 

8G,=I^y8 )-

m$(()CRH)% $(::hll;UWY.Zfj#k (,HH! 
Ews   CCC	CCupdate_paramsc                     	  |j                   di |}|S # t        t        f$ r}| j                  |d       Y d}~S d}~ww xY w)z
    Updates a backup plan.

    module : AnsibleAWSModule object
    client : boto3 backup client connection object
    update_params : The boto3 backup client parameters to update a backup plan
    z"Failed to update backup plan {err}r[   Nr]   )update_backup_planr   r   r_   )r8   r`   rv   ra   rb   s        rI   rx   rx   9  rc   rd   new_tagsplan_arncurrent_tagsc                    |s|sy| j                   ry|xs i }|xs i }t        ||| j                  d         \  }}|s|sy|r	 |j                  ||       |r	 |j                  ||	       yy# t        t
        f$ r}| j                  |d       Y d}~?d}~ww xY w# t        t
        f$ r}| j                  |d
       Y d}~yd}~ww xY w)a`  
    Creates, updates, and/or removes tags on a Backup Plan resource.

    module : AnsibleAWSModule object
    client : boto3 client connection object
    new_tags : Dict of tags converted from ansible_dict to boto3 list of dicts
    plan_arn : The ARN of the Backup Plan to operate on
    curr_tags : Dict of the current tags on resource, if any
    FTr7   )r7   )ResourceArn
TagKeyListz#Failed to remove tags from the planr[   N)r}   TagszFailed to add tags to the plan)
check_moder	   rF   untag_resourcer   r   r_   tag_resource)r8   r`   ry   rz   r{   tags_to_addtags_to_removerb   s           rI   tag_backup_planr   K  s    " L~2H%2L"2<V\VcVcdpVq"rK~	Q!!h>!R 	LH;G  {+ 	Q  *O PP	Q {+ 	L  *J KK	Ls0   A0 B 0B?BBC.CCc                     	 |j                  |      }|S # t        t        f$ r}| j                  |d       Y d}~S d}~ww xY w)z
    Deletes a Backup Plan

    module : AnsibleAWSModule object
    client : boto3 backup client connection object
    backup_plan_id : ID (*not* name or ARN) of Backup plan to delete
    )rD   z Failed to delete the Backup Planr[   N)delete_backup_planr   r   r_   )r8   r`   r:   ra   rb   s        rI   r   r   x  sW    J,,.,I O ;' JS&HIIOJrd   c                  v   t        t        t        t              } t	        dd      }| j                  d      }| j                  d   }| j                  d   }| j                  d   | j                  d   xs g D cg c]  }t        |       c}| j                  d   xs g D cg c]  }t        |       c}d	}| j                  d   r>|d   D ]6  }| j                  d
      r| j                  d       |j                  d       8 | j                  d   }	t        | ||      }
|
r|
d   d   }|
d   }
nd x}
}|dk(  r|b| j                  rt        |||	      }n,t        | ||	d      }t        | ||      }t        | ||      d   }d|d<   d|d<   |j!                  |       nd|d<   t#        |
|      r-| j                  st        | ||d      }t%        | ||       d|d<   t'        | ||	|
d   |
d         rd|d<   | j                  rt        |||	      }nt        | ||      d   }|j!                  |       nj|dk(  re|| j)                  d| d       nL| j                  rt        ||
|	d      }nt+        | ||      }d|d<   d|d<   |j!                  t-        |              | j.                  di | y c c}w c c}w )N)argument_specrequired_ifsupports_check_modeF)changedexistsbackupr1   r2   r3   r4   )r2   r3   r4   z1.31.36zhschedule_expression_timezone requires botocore >= 1.31.36. schedule_expression_timezone will be ignored.r%   r6   r   r:   r   r@   )r6   r;   Tr   r   rC   )r:   r;   rO   r   zBackup plan z not found.r[   r]   )r   ARGUMENT_SPECREQUIRED_IFSUPPORTS_CHECK_MODEr   r`   rF   r
   botocore_at_leastwarnpopr   r   rW   rJ   r^   rC   ru   rx   r   debugr   r   	exit_json)r8   resultr`   r1   rK   rn   settingr9   eachr6   re   existing_plan_idrS   client_paramsra   s                  rI   mainr     s   #/F %.F ]]8$FMM'"E01I #MM*<=:@--:P:VTVW$'-W:@--Hb:c:igi%
/6!'*%
D }}WM 	9D++I6~ 78	9 == D %VVY?M(+,<=%a(+//(	#  8D$O 4VTX` a-ffmL.vvyI!L#F8 $F9MM+&  $F8!-6(($8'7"*	%M 'vv}E$(y!/0f% %)y!  8D$O.vvyI!LMM+&	(	#LL|I;kBLC  5iPTVZ[-ff>NO $F9$F8MM28<=FvU X%
s   :J1#J6__main__)NNN)F)N)%DOCUMENTATIONEXAMPLESRETURNrj   r   typingr   0ansible.module_utils.common.dict_transformationsr   r   :ansible_collections.amazon.aws.plugins.module_utils.backupr   ;ansible_collections.amazon.aws.plugins.module_utils.modulesr   ;ansible_collections.amazon.aws.plugins.module_utils.taggingr	   Bansible_collections.amazon.aws.plugins.module_utils.transformationr
   botocore.exceptionsr   r   ImportErrorr   r   r   r   r   rJ   r   rW   r^   ru   rx   r   r   r   __name__r]   rX   rI   <module>r      s0  jX*f
P    U U W X X d	1/ 
EIx#8)
L4efXF
Du5%)4e%D $%9L M!%5#!>&*u&E)-5))L48e4D&*&6 !%& 115t%1P"# $<@e<L.2.>!	 &*vu%E;
"F "EE7;%)ZAX(YZ

 '	6$6#H	IDv.g4n i,g67h+,-
    $(#!!
! 4.! SM	!
 }! 
!H
# 
T 
 
t 
`d 
D/  QU $d d t @/  QU . $(** tn* 	*
 4.*Z/  QU [| zF K  		s   G- -G65G6