Automatización de instantáneas coherentes con las aplicaciones con scripts previos y posteriores - Amazon EBS

Las traducciones son generadas a través de traducción automática. En caso de conflicto entre la traducción y la version original de inglés, prevalecerá la version en inglés.

Automatización de instantáneas coherentes con las aplicaciones con scripts previos y posteriores

Puede automatizar las instantáneas coherentes con la aplicación con Amazon Data Lifecycle Manager habilitando scripts previos y posteriores en sus políticas de ciclo de vida de instantáneas que engloben las instancias.

Amazon Data Lifecycle Manager se integra con AWS Systems Manager (Systems Manager) para admitir instantáneas coherentes con las aplicaciones. Amazon Data Lifecycle Manager utiliza documentos de comandos de Systems Manager (SSM) que incluyen scripts previos y posteriores para automatizar las acciones necesarias para completar instantáneas coherentes con las aplicaciones. Antes de que Amazon Data Lifecycle Manager inicie la creación de instantáneas, ejecuta los comandos del script previo para congelar y vaciar las E/S. Una vez que Amazon Data Lifecycle Manager inicia la creación de instantáneas, ejecuta los comandos del script posterior para descongelar las E/S.

Con Amazon Data Lifecycle Manager puede automatizar las instantáneas coherentes con las aplicaciones de lo siguiente:

  • Aplicaciones de Windows con el Servicio de instantáneas de volumen (VSS)

  • SAP HANA utiliza un documento SSDM AWS gestionado. Para obtener más información, consulte Amazon EBS snapshots for SAP HANA.

  • Bases de datos autogestionadas, como MySQL, PostgreSQL InterSystems o IRIS, mediante plantillas de documentos SSM

Introducción a las instantáneas coherentes con las aplicaciones

En esta sección se explican los pasos que debe seguir para automatizar las instantáneas coherentes con las aplicaciones mediante Amazon Data Lifecycle Manager.

Debe preparar las instancias de destino para las instantáneas coherentes con las aplicaciones mediante Amazon Data Lifecycle Manager. Realice una de las siguientes acciones en función de su caso de uso.

Prepare for VSS Backups
Preparación de las instancias de destino para las copias de seguridad de VSS
  1. Instale SSM Agent en las instancias de destino, si aún no está instalado. Si SSM Agent ya está instalado en las instancias de destino, omita este paso.

    Para obtener más información, consulte Instalación manual de SSM Agent en instancias de Amazon EC2 para Windows.

  2. Asegúrese de que el agente SSM esté en ejecución. Para obtener más información, consulte Verificación del estado de SSM Agent e inicio del agente.

  3. Configure Systems Manager para instancias de Amazon EC2. Para obtener más información, consulte Configuración de Systems Manager para instancias de Amazon EC2 en la Guía del usuario de AWS Systems Manager .

  4. Asegúrese de que se cumplen los requisitos del sistema para las copias de seguridad de VSS.

  5. Adjunte un perfil de instancia compatible con VSS a las instancias de destino.

  6. Instale los componentes de VSS.

Prepare for SAP HANA backups
Preparación de las instancias de destino para las copias de seguridad de SAP HANA
  1. Prepare el entorno de SAP HANA en sus instancias de destino.

    1. Configure su instancia con SAP HANA. Si aún no tiene un entorno de SAP HANA existente, puede consultar SAP HANA Environment Setup on AWS.

    2. Inicie sesión en SystemDB como un usuario administrador adecuado.

    3. Cree un usuario de copia de seguridad de base de datos para usarlo con Amazon Data Lifecycle Manager.

      CREATE USER username PASSWORD password NO FORCE_FIRST_PASSWORD_CHANGE;

      Por ejemplo, el siguiente comando crea un usuario llamado dlm_user con la contraseña password.

      CREATE USER dlm_user PASSWORD password NO FORCE_FIRST_PASSWORD_CHANGE;
    4. Asigne el rol BACKUP OPERATOR al usuario de copias de seguridad de bases de datos que creó en el paso anterior.

      GRANT BACKUP OPERATOR TO username

      Por ejemplo, el comando siguiente asigna el rol a un usuario denominado dlm_user.

      GRANT BACKUP OPERATOR TO dlm_user
    5. Inicie sesión en el sistema operativo como administrador, por ejemplo, sidadm.

    6. Cree una entrada hdbuserstore para almacenar la información de conexión, de modo que el documento de SSM de SAP HANA pueda conectarse a SAP HANA sin que los usuarios tengan que ingresar la información.

      hdbuserstore set DLM_HANADB_SNAPSHOT_USER localhost:3hana_instance_number13 username password

      Por ejemplo:

      hdbuserstore set DLM_HANADB_SNAPSHOT_USER localhost:30013 dlm_user password
    7. Pruebe la conexión.

      hdbsql -U DLM_HANADB_SNAPSHOT_USER "select * from dummy"
  2. Instale SSM Agent en las instancias de destino, si aún no está instalado. Si SSM Agent ya está instalado en las instancias de destino, omita este paso.

    Para obtener más información, consulte Instalación manual de SSM Agent en instancias de Amazon EC2 para Linux.

  3. Asegúrese de que SSM Agent esté en ejecución. Para obtener más información, consulte Verificación del estado de SSM Agent e inicio del agente.

  4. Configure Systems Manager para instancias de Amazon EC2. Para obtener más información, consulte Configuración de Systems Manager para instancias de Amazon EC2 en la Guía del usuario de AWS Systems Manager .

Prepare for custom SSM documents
Preparación de los documentos de SSM personalizados de las instancias de destino
  1. Instale SSM Agent en las instancias de destino, si aún no está instalado. Si SSM Agent ya está instalado en las instancias de destino, omita este paso.

  2. Asegúrese de que SSM Agent esté en ejecución. Para obtener más información, consulte Verificación del estado de SSM Agent e inicio del agente.

  3. Configure Systems Manager para instancias de Amazon EC2. Para obtener más información, consulte Configuración de Systems Manager para instancias de Amazon EC2 en la Guía del usuario de AWS Systems Manager .

nota

Este paso solo es necesario para los documentos de SSM personalizados. No es necesario para las copias de seguridad de VSS ni SAP HANA. Para las copias de seguridad de VSS y SAP HANA, Amazon Data Lifecycle Manager utiliza el documento SSM AWS gestionado.

Si va a automatizar instantáneas coherentes con las aplicaciones para una base de datos autogestionada, como MySQL, PostgreSQL o InterSystems IRIS, debe crear un documento de comandos SSM que incluya un script previo para congelar y vaciar las E/S antes de que se inicie la creación de las instantáneas, y un posscript para descongelar las E/S una vez iniciada la creación de las instantáneas.

Si su base de datos MySQL, PostgreSQL InterSystems o IRIS utiliza configuraciones estándar, puede crear un documento de comandos SSM utilizando el ejemplo de contenido del documento SSM que aparece a continuación. Si su base de datos MySQL, PostgreSQL InterSystems o IRIS utiliza una configuración no estándar, puede utilizar el siguiente contenido de ejemplo como punto de partida para su documento de comandos de SSM y, a continuación, personalizarlo para que se ajuste a sus necesidades. Como alternativa, si desea crear un nuevo documento de SSM desde cero, puede utilizar la plantilla de documento de SSM vacía que aparece a continuación y agregar los comandos previos y posteriores en las secciones del documento correspondientes.

Tenga en cuenta lo siguiente:
  • Es su responsabilidad asegurarse de que el documento de SSM realice las acciones correctas y necesarias para la configuración de su base de datos.

  • Se garantiza que las instantáneas son coherentes con las aplicaciones solo si los scripts previos y posteriores del documento de SSM pueden congelar, vaciar y descongelar las E/S correctamente.

  • El documento de SSM debe incluir los campos obligatorios para allowedValues, incluidos pre-script, post-script y dry-run. Amazon Data Lifecycle Manager ejecutará comandos en la instancia en función del contenido de esas secciones. Si su documento de SSM no incluye esas secciones, Amazon Data Lifecycle Manager lo considerará una ejecución fallida.

MySQL sample document content
###===============================================================================### # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # Permission is hereby granted, free of charge, to any person obtaining a copy of this # software and associated documentation files (the "Software"), to deal in the Software # without restriction, including without limitation the rights to use, copy, modify, # merge, publish, distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, # INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A # PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT # HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE # SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ###===============================================================================### schemaVersion: '2.2' description: Amazon Data Lifecycle Manager Pre/Post script for MySQL databases parameters: executionId: type: String default: None description: (Required) Specifies the unique identifier associated with a pre and/or post execution allowedPattern: ^(None|[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12})$ command: # Data Lifecycle Manager will trigger the pre-script and post-script actions during policy execution. # 'dry-run' option is intended for validating the document execution without triggering any commands # on the instance. The following allowedValues will allow Data Lifecycle Manager to successfully # trigger pre and post script actions. type: String default: 'dry-run' description: (Required) Specifies whether pre-script and/or post-script should be executed. allowedValues: - pre-script - post-script - dry-run mainSteps: - action: aws:runShellScript description: Run MySQL Database freeze/thaw commands name: run_pre_post_scripts precondition: StringEquals: - platformType - Linux inputs: runCommand: - | #!/bin/bash ###===============================================================================### ### Error Codes ###===============================================================================### # The following Error codes will inform Data Lifecycle Manager of the type of error # and help guide handling of the error. # The Error code will also be emitted via AWS Eventbridge events in the 'cause' field. # 1 Pre-script failed during execution - 201 # 2 Post-script failed during execution - 202 # 3 Auto thaw occurred before post-script was initiated - 203 # 4 Pre-script initiated while post-script was expected - 204 # 5 Post-script initiated while pre-script was expected - 205 # 6 Application not ready for pre or post-script initiation - 206 ###=================================================================### ### Global variables ###=================================================================### START=$(date +%s) # For testing this script locally, replace the below with OPERATION=$1. OPERATION={{ command }} FS_ALREADY_FROZEN_ERROR='freeze failed: Device or resource busy' FS_ALREADY_THAWED_ERROR='unfreeze failed: Invalid argument' FS_BUSY_ERROR='mount point is busy' # Auto thaw is a fail safe mechanism to automatically unfreeze the application after the # duration specified in the global variable below. Choose the duration based on your # database application's tolerance to freeze. export AUTO_THAW_DURATION_SECS="60" # Add all pre-script actions to be performed within the function below execute_pre_script() { echo "INFO: Start execution of pre-script" # Check if filesystem is already frozen. No error code indicates that filesystem # is not currently frozen and that the pre-script can proceed with freezing the filesystem. check_fs_freeze # Execute the DB commands to flush the DB in preparation for snapshot snap_db # Freeze the filesystem. No error code indicates that filesystem was succefully frozen freeze_fs echo "INFO: Schedule Auto Thaw to execute in ${AUTO_THAW_DURATION_SECS} seconds." $(nohup bash -c execute_schedule_auto_thaw >/dev/null 2>&1 &) } # Add all post-script actions to be performed within the function below execute_post_script() { echo "INFO: Start execution of post-script" # Unfreeze the filesystem. No error code indicates that filesystem was successfully unfrozen. unfreeze_fs thaw_db } # Execute Auto Thaw to automatically unfreeze the application after the duration configured # in the AUTO_THAW_DURATION_SECS global variable. execute_schedule_auto_thaw() { sleep ${AUTO_THAW_DURATION_SECS} execute_post_script } # Disable Auto Thaw if it is still enabled execute_disable_auto_thaw() { echo "INFO: Attempting to disable auto thaw if enabled" auto_thaw_pgid=$(pgrep -f execute_schedule_auto_thaw | xargs -i ps -hp {} -o pgid) if [ -n "${auto_thaw_pgid}" ]; then echo "INFO: execute_schedule_auto_thaw process found with pgid ${auto_thaw_pgid}" sudo pkill -g ${auto_thaw_pgid} rc=$? if [ ${rc} != 0 ]; then echo "ERROR: Unable to kill execute_schedule_auto_thaw process. retval=${rc}" else echo "INFO: Auto Thaw has been disabled" fi fi } # Iterate over all the mountpoints and check if filesystem is already in freeze state. # Return error code 204 if any of the mount points are already frozen. check_fs_freeze() { for target in $(lsblk -nlo MOUNTPOINTS) do # Freeze of the root and boot filesystems is dangerous and pre-script does not freeze these filesystems. # Hence, we will skip the root and boot mountpoints while checking if filesystem is in freeze state. if [ $target == '/' ]; then continue; fi if [[ "$target" == *"/boot"* ]]; then continue; fi error_message=$(sudo mount -o remount,noatime $target 2>&1) # Remount will be a no-op without a error message if the filesystem is unfrozen. # However, if filesystem is already frozen, remount will fail with busy error message. if [ $? -ne 0 ];then # If the filesystem is already in frozen, return error code 204 if [[ "$error_message" == *"$FS_BUSY_ERROR"* ]];then echo "ERROR: Filesystem ${target} already frozen. Return Error Code: 204" exit 204 fi # If the check filesystem freeze failed due to any reason other than the filesystem already frozen, return 201 echo "ERROR: Failed to check_fs_freeze on mountpoint $target due to error - $errormessage" exit 201 fi done } # Iterate over all the mountpoints and freeze the filesystem. freeze_fs() { for target in $(lsblk -nlo MOUNTPOINTS) do # Freeze of the root and boot filesystems is dangerous. Hence, skip filesystem freeze # operations for root and boot mountpoints. if [ $target == '/' ]; then continue; fi if [[ "$target" == *"/boot"* ]]; then continue; fi echo "INFO: Freezing $target" error_message=$(sudo fsfreeze -f $target 2>&1) if [ $? -ne 0 ];then # If the filesystem is already in frozen, return error code 204 if [[ "$error_message" == *"$FS_ALREADY_FROZEN_ERROR"* ]]; then echo "ERROR: Filesystem ${target} already frozen. Return Error Code: 204" sudo mysql -e 'UNLOCK TABLES;' exit 204 fi # If the filesystem freeze failed due to any reason other than the filesystem already frozen, return 201 echo "ERROR: Failed to freeze mountpoint $targetdue due to error - $errormessage" thaw_db exit 201 fi echo "INFO: Freezing complete on $target" done } # Iterate over all the mountpoints and unfreeze the filesystem. unfreeze_fs() { for target in $(lsblk -nlo MOUNTPOINTS) do # Freeze of the root and boot filesystems is dangerous and pre-script does not freeze these filesystems. # Hence, will skip the root and boot mountpoints during unfreeze as well. if [ $target == '/' ]; then continue; fi if [[ "$target" == *"/boot"* ]]; then continue; fi echo "INFO: Thawing $target" error_message=$(sudo fsfreeze -u $target 2>&1) # Check if filesystem is already unfrozen (thawed). Return error code 204 if filesystem is already unfrozen. if [ $? -ne 0 ]; then if [[ "$error_message" == *"$FS_ALREADY_THAWED_ERROR"* ]]; then echo "ERROR: Filesystem ${target} is already in thaw state. Return Error Code: 205" exit 205 fi # If the filesystem unfreeze failed due to any reason other than the filesystem already unfrozen, return 202 echo "ERROR: Failed to unfreeze mountpoint $targetdue due to error - $errormessage" exit 202 fi echo "INFO: Thaw complete on $target" done } snap_db() { # Run the flush command only when MySQL DB service is up and running sudo systemctl is-active --quiet mysqld.service if [ $? -eq 0 ]; then echo "INFO: Execute MySQL Flush and Lock command." sudo mysql -e 'FLUSH TABLES WITH READ LOCK;' # If the MySQL Flush and Lock command did not succeed, return error code 201 to indicate pre-script failure if [ $? -ne 0 ]; then echo "ERROR: MySQL FLUSH TABLES WITH READ LOCK command failed." exit 201 fi sync else echo "INFO: MySQL service is inactive. Skipping execution of MySQL Flush and Lock command." fi } thaw_db() { # Run the unlock command only when MySQL DB service is up and running sudo systemctl is-active --quiet mysqld.service if [ $? -eq 0 ]; then echo "INFO: Execute MySQL Unlock" sudo mysql -e 'UNLOCK TABLES;' else echo "INFO: MySQL service is inactive. Skipping execution of MySQL Unlock command." fi } export -f execute_schedule_auto_thaw export -f execute_post_script export -f unfreeze_fs export -f thaw_db # Debug logging for parameters passed to the SSM document echo "INFO: ${OPERATION} starting at $(date) with executionId: ${EXECUTION_ID}" # Based on the command parameter value execute the function that supports # pre-script/post-script operation case ${OPERATION} in pre-script) execute_pre_script ;; post-script) execute_post_script execute_disable_auto_thaw ;; dry-run) echo "INFO: dry-run option invoked - taking no action" ;; *) echo "ERROR: Invalid command parameter passed. Please use either pre-script, post-script, dry-run." exit 1 # return failure ;; esac END=$(date +%s) # Debug Log for profiling the script time echo "INFO: ${OPERATION} completed at $(date). Total runtime: $((${END} - ${START})) seconds."
PostgreSQL sample document content
###===============================================================================### # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # Permission is hereby granted, free of charge, to any person obtaining a copy of this # software and associated documentation files (the "Software"), to deal in the Software # without restriction, including without limitation the rights to use, copy, modify, # merge, publish, distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, # INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A # PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT # HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE # SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ###===============================================================================### schemaVersion: '2.2' description: Amazon Data Lifecycle Manager Pre/Post script for PostgreSQL databases parameters: executionId: type: String default: None description: (Required) Specifies the unique identifier associated with a pre and/or post execution allowedPattern: ^(None|[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12})$ command: # Data Lifecycle Manager will trigger the pre-script and post-script actions during policy execution. # 'dry-run' option is intended for validating the document execution without triggering any commands # on the instance. The following allowedValues will allow Data Lifecycle Manager to successfully # trigger pre and post script actions. type: String default: 'dry-run' description: (Required) Specifies whether pre-script and/or post-script should be executed. allowedValues: - pre-script - post-script - dry-run mainSteps: - action: aws:runShellScript description: Run PostgreSQL Database freeze/thaw commands name: run_pre_post_scripts precondition: StringEquals: - platformType - Linux inputs: runCommand: - | #!/bin/bash ###===============================================================================### ### Error Codes ###===============================================================================### # The following Error codes will inform Data Lifecycle Manager of the type of error # and help guide handling of the error. # The Error code will also be emitted via AWS Eventbridge events in the 'cause' field. # 1 Pre-script failed during execution - 201 # 2 Post-script failed during execution - 202 # 3 Auto thaw occurred before post-script was initiated - 203 # 4 Pre-script initiated while post-script was expected - 204 # 5 Post-script initiated while pre-script was expected - 205 # 6 Application not ready for pre or post-script initiation - 206 ###===============================================================================### ### Global variables ###===============================================================================### START=$(date +%s) OPERATION={{ command }} FS_ALREADY_FROZEN_ERROR='freeze failed: Device or resource busy' FS_ALREADY_THAWED_ERROR='unfreeze failed: Invalid argument' FS_BUSY_ERROR='mount point is busy' # Auto thaw is a fail safe mechanism to automatically unfreeze the application after the # duration specified in the global variable below. Choose the duration based on your # database application's tolerance to freeze. export AUTO_THAW_DURATION_SECS="60" # Add all pre-script actions to be performed within the function below execute_pre_script() { echo "INFO: Start execution of pre-script" # Check if filesystem is already frozen. No error code indicates that filesystem # is not currently frozen and that the pre-script can proceed with freezing the filesystem. check_fs_freeze # Execute the DB commands to flush the DB in preparation for snapshot snap_db # Freeze the filesystem. No error code indicates that filesystem was succefully frozen freeze_fs echo "INFO: Schedule Auto Thaw to execute in ${AUTO_THAW_DURATION_SECS} seconds." $(nohup bash -c execute_schedule_auto_thaw >/dev/null 2>&1 &) } # Add all post-script actions to be performed within the function below execute_post_script() { echo "INFO: Start execution of post-script" # Unfreeze the filesystem. No error code indicates that filesystem was successfully unfrozen unfreeze_fs } # Execute Auto Thaw to automatically unfreeze the application after the duration configured # in the AUTO_THAW_DURATION_SECS global variable. execute_schedule_auto_thaw() { sleep ${AUTO_THAW_DURATION_SECS} execute_post_script } # Disable Auto Thaw if it is still enabled execute_disable_auto_thaw() { echo "INFO: Attempting to disable auto thaw if enabled" auto_thaw_pgid=$(pgrep -f execute_schedule_auto_thaw | xargs -i ps -hp {} -o pgid) if [ -n "${auto_thaw_pgid}" ]; then echo "INFO: execute_schedule_auto_thaw process found with pgid ${auto_thaw_pgid}" sudo pkill -g ${auto_thaw_pgid} rc=$? if [ ${rc} != 0 ]; then echo "ERROR: Unable to kill execute_schedule_auto_thaw process. retval=${rc}" else echo "INFO: Auto Thaw has been disabled" fi fi } # Iterate over all the mountpoints and check if filesystem is already in freeze state. # Return error code 204 if any of the mount points are already frozen. check_fs_freeze() { for target in $(lsblk -nlo MOUNTPOINTS) do # Freeze of the root and boot filesystems is dangerous and pre-script does not freeze these filesystems. # Hence, we will skip the root and boot mountpoints while checking if filesystem is in freeze state. if [ $target == '/' ]; then continue; fi if [[ "$target" == *"/boot"* ]]; then continue; fi error_message=$(sudo mount -o remount,noatime $target 2>&1) # Remount will be a no-op without a error message if the filesystem is unfrozen. # However, if filesystem is already frozen, remount will fail with busy error message. if [ $? -ne 0 ];then # If the filesystem is already in frozen, return error code 204 if [[ "$error_message" == *"$FS_BUSY_ERROR"* ]];then echo "ERROR: Filesystem ${target} already frozen. Return Error Code: 204" exit 204 fi # If the check filesystem freeze failed due to any reason other than the filesystem already frozen, return 201 echo "ERROR: Failed to check_fs_freeze on mountpoint $target due to error - $errormessage" exit 201 fi done } # Iterate over all the mountpoints and freeze the filesystem. freeze_fs() { for target in $(lsblk -nlo MOUNTPOINTS) do # Freeze of the root and boot filesystems is dangerous. Hence, skip filesystem freeze # operations for root and boot mountpoints. if [ $target == '/' ]; then continue; fi if [[ "$target" == *"/boot"* ]]; then continue; fi echo "INFO: Freezing $target" error_message=$(sudo fsfreeze -f $target 2>&1) if [ $? -ne 0 ];then # If the filesystem is already in frozen, return error code 204 if [[ "$error_message" == *"$FS_ALREADY_FROZEN_ERROR"* ]]; then echo "ERROR: Filesystem ${target} already frozen. Return Error Code: 204" exit 204 fi # If the filesystem freeze failed due to any reason other than the filesystem already frozen, return 201 echo "ERROR: Failed to freeze mountpoint $targetdue due to error - $errormessage" exit 201 fi echo "INFO: Freezing complete on $target" done } # Iterate over all the mountpoints and unfreeze the filesystem. unfreeze_fs() { for target in $(lsblk -nlo MOUNTPOINTS) do # Freeze of the root and boot filesystems is dangerous and pre-script does not freeze these filesystems. # Hence, will skip the root and boot mountpoints during unfreeze as well. if [ $target == '/' ]; then continue; fi if [[ "$target" == *"/boot"* ]]; then continue; fi echo "INFO: Thawing $target" error_message=$(sudo fsfreeze -u $target 2>&1) # Check if filesystem is already unfrozen (thawed). Return error code 204 if filesystem is already unfrozen. if [ $? -ne 0 ]; then if [[ "$error_message" == *"$FS_ALREADY_THAWED_ERROR"* ]]; then echo "ERROR: Filesystem ${target} is already in thaw state. Return Error Code: 205" exit 205 fi # If the filesystem unfreeze failed due to any reason other than the filesystem already unfrozen, return 202 echo "ERROR: Failed to unfreeze mountpoint $targetdue due to error - $errormessage" exit 202 fi echo "INFO: Thaw complete on $target" done } snap_db() { # Run the flush command only when PostgreSQL DB service is up and running sudo systemctl is-active --quiet postgresql if [ $? -eq 0 ]; then echo "INFO: Execute Postgres CHECKPOINT" # PostgreSQL command to flush the transactions in memory to disk sudo -u postgres psql -c 'CHECKPOINT;' # If the PostgreSQL Command did not succeed, return error code 201 to indicate pre-script failure if [ $? -ne 0 ]; then echo "ERROR: Postgres CHECKPOINT command failed." exit 201 fi sync else echo "INFO: PostgreSQL service is inactive. Skipping execution of CHECKPOINT command." fi } export -f execute_schedule_auto_thaw export -f execute_post_script export -f unfreeze_fs # Debug logging for parameters passed to the SSM document echo "INFO: ${OPERATION} starting at $(date) with executionId: ${EXECUTION_ID}" # Based on the command parameter value execute the function that supports # pre-script/post-script operation case ${OPERATION} in pre-script) execute_pre_script ;; post-script) execute_post_script execute_disable_auto_thaw ;; dry-run) echo "INFO: dry-run option invoked - taking no action" ;; *) echo "ERROR: Invalid command parameter passed. Please use either pre-script, post-script, dry-run." exit 1 # return failure ;; esac END=$(date +%s) # Debug Log for profiling the script time echo "INFO: ${OPERATION} completed at $(date). Total runtime: $((${END} - ${START})) seconds."
InterSystems IRIS sample document content
###===============================================================================### # MIT License # # Copyright (c) 2024 InterSystems # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. ###===============================================================================### schemaVersion: '2.2' description: SSM Document Template for Amazon Data Lifecycle Manager Pre/Post script feature for InterSystems IRIS. parameters: executionId: type: String default: None description: Specifies the unique identifier associated with a pre and/or post execution allowedPattern: ^(None|[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12})$ command: type: String # Data Lifecycle Manager will trigger the pre-script and post-script actions. You can also use this SSM document with 'dry-run' for manual testing purposes. default: 'dry-run' description: (Required) Specifies whether pre-script and/or post-script should be executed. #The following allowedValues will allow Data Lifecycle Manager to successfully trigger pre and post script actions. allowedValues: - pre-script - post-script - dry-run mainSteps: - action: aws:runShellScript description: Run InterSystems IRIS Database freeze/thaw commands name: run_pre_post_scripts precondition: StringEquals: - platformType - Linux inputs: runCommand: - | #!/bin/bash ###===============================================================================### ### Global variables ###===============================================================================### DOCKER_NAME=iris LOGDIR=./ EXIT_CODE=0 OPERATION={{ command }} START=$(date +%s) # Check if Docker is installed # By default if Docker is present, script assumes that InterSystems IRIS is running in Docker # Leave only the else block DOCKER_EXEC line, if you run InterSystems IRIS non-containerised (and Docker is present). # Script assumes irissys user has OS auth enabled, change the OS user or supply login/password depending on your configuration. if command -v docker &> /dev/null then DOCKER_EXEC="docker exec $DOCKER_NAME" else DOCKER_EXEC="sudo -i -u irissys" fi # Add all pre-script actions to be performed within the function below execute_pre_script() { echo "INFO: Start execution of pre-script" # find all iris running instances iris_instances=$($DOCKER_EXEC iris qall 2>/dev/null | tail -n +3 | grep '^up' | cut -c5- | awk '{print $1}') echo "`date`: Running iris instances $iris_instances" # Only for running instances for INST in $iris_instances; do echo "`date`: Attempting to freeze $INST" # Detailed instances specific log LOGFILE=$LOGDIR/$INST-pre_post.log #check Freeze status before starting $DOCKER_EXEC irissession $INST -U '%SYS' "##Class(Backup.General).IsWDSuspendedExt()" freeze_status=$? if [ $freeze_status -eq 5 ]; then echo "`date`: ERROR: $INST IS already FROZEN" EXIT_CODE=204 else echo "`date`: $INST is not frozen" # Freeze # Docs: https://docs.intersystems.com/irislatest/csp/documatic/%25CSP.Documatic.cls?LIBRARY=%25SYS&CLASSNAME=Backup.General#ExternalFreeze $DOCKER_EXEC irissession $INST -U '%SYS' "##Class(Backup.General).ExternalFreeze(\"$LOGFILE\",,,,,,600,,,300)" status=$? case $status in 5) echo "`date`: $INST IS FROZEN" ;; 3) echo "`date`: $INST FREEZE FAILED" EXIT_CODE=201 ;; *) echo "`date`: ERROR: Unknown status code: $status" EXIT_CODE=201 ;; esac echo "`date`: Completed freeze of $INST" fi done echo "`date`: Pre freeze script finished" } # Add all post-script actions to be performed within the function below execute_post_script() { echo "INFO: Start execution of post-script" # find all iris running instances iris_instances=$($DOCKER_EXEC iris qall 2>/dev/null | tail -n +3 | grep '^up' | cut -c5- | awk '{print $1}') echo "`date`: Running iris instances $iris_instances" # Only for running instances for INST in $iris_instances; do echo "`date`: Attempting to thaw $INST" # Detailed instances specific log LOGFILE=$LOGDIR/$INST-pre_post.log #check Freeze status befor starting $DOCKER_EXEC irissession $INST -U '%SYS' "##Class(Backup.General).IsWDSuspendedExt()" freeze_status=$? if [ $freeze_status -eq 5 ]; then echo "`date`: $INST is in frozen state" # Thaw # Docs: https://docs.intersystems.com/irislatest/csp/documatic/%25CSP.Documatic.cls?LIBRARY=%25SYS&CLASSNAME=Backup.General#ExternalFreeze $DOCKER_EXEC irissession $INST -U%SYS "##Class(Backup.General).ExternalThaw(\"$LOGFILE\")" status=$? case $status in 5) echo "`date`: $INST IS THAWED" $DOCKER_EXEC irissession $INST -U%SYS "##Class(Backup.General).ExternalSetHistory(\"$LOGFILE\")" ;; 3) echo "`date`: $INST THAW FAILED" EXIT_CODE=202 ;; *) echo "`date`: ERROR: Unknown status code: $status" EXIT_CODE=202 ;; esac echo "`date`: Completed thaw of $INST" else echo "`date`: ERROR: $INST IS already THAWED" EXIT_CODE=205 fi done echo "`date`: Post thaw script finished" } # Debug logging for parameters passed to the SSM document echo "INFO: ${OPERATION} starting at $(date) with executionId: ${EXECUTION_ID}" # Based on the command parameter value execute the function that supports # pre-script/post-script operation case ${OPERATION} in pre-script) execute_pre_script ;; post-script) execute_post_script ;; dry-run) echo "INFO: dry-run option invoked - taking no action" ;; *) echo "ERROR: Invalid command parameter passed. Please use either pre-script, post-script, dry-run." # return failure EXIT_CODE=1 ;; esac END=$(date +%s) # Debug Log for profiling the script time echo "INFO: ${OPERATION} completed at $(date). Total runtime: $((${END} - ${START})) seconds." exit $EXIT_CODE

Para obtener más información, consulte el repositorio. GitHub

Empty document template
###===============================================================================### # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # Permission is hereby granted, free of charge, to any person obtaining a copy of this # software and associated documentation files (the "Software"), to deal in the Software # without restriction, including without limitation the rights to use, copy, modify, # merge, publish, distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, # INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A # PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT # HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE # SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ###===============================================================================### schemaVersion: '2.2' description: SSM Document Template for Amazon Data Lifecycle Manager Pre/Post script feature parameters: executionId: type: String default: None description: (Required) Specifies the unique identifier associated with a pre and/or post execution allowedPattern: ^(None|[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12})$ command: # Data Lifecycle Manager will trigger the pre-script and post-script actions during policy execution. # 'dry-run' option is intended for validating the document execution without triggering any commands # on the instance. The following allowedValues will allow Data Lifecycle Manager to successfully # trigger pre and post script actions. type: String default: 'dry-run' description: (Required) Specifies whether pre-script and/or post-script should be executed. allowedValues: - pre-script - post-script - dry-run mainSteps: - action: aws:runShellScript description: Run Database freeze/thaw commands name: run_pre_post_scripts precondition: StringEquals: - platformType - Linux inputs: runCommand: - | #!/bin/bash ###===============================================================================### ### Error Codes ###===============================================================================### # The following Error codes will inform Data Lifecycle Manager of the type of error # and help guide handling of the error. # The Error code will also be emitted via AWS Eventbridge events in the 'cause' field. # 1 Pre-script failed during execution - 201 # 2 Post-script failed during execution - 202 # 3 Auto thaw occurred before post-script was initiated - 203 # 4 Pre-script initiated while post-script was expected - 204 # 5 Post-script initiated while pre-script was expected - 205 # 6 Application not ready for pre or post-script initiation - 206 ###===============================================================================### ### Global variables ###===============================================================================### START=$(date +%s) # For testing this script locally, replace the below with OPERATION=$1. OPERATION={{ command }} # Add all pre-script actions to be performed within the function below execute_pre_script() { echo "INFO: Start execution of pre-script" } # Add all post-script actions to be performed within the function below execute_post_script() { echo "INFO: Start execution of post-script" } # Debug logging for parameters passed to the SSM document echo "INFO: ${OPERATION} starting at $(date) with executionId: ${EXECUTION_ID}" # Based on the command parameter value execute the function that supports # pre-script/post-script operation case ${OPERATION} in pre-script) execute_pre_script ;; post-script) execute_post_script ;; dry-run) echo "INFO: dry-run option invoked - taking no action" ;; *) echo "ERROR: Invalid command parameter passed. Please use either pre-script, post-script, dry-run." exit 1 # return failure ;; esac END=$(date +%s) # Debug Log for profiling the script time echo "INFO: ${OPERATION} completed at $(date). Total runtime: $((${END} - ${START})) seconds."

Una vez que tenga el contenido del documento de SSM, utilice uno de los procedimientos siguientes para crear el documento de SSM personalizado.

Console
Creación del documento de comandos de SSM
  1. Abra la AWS Systems Manager consola en https://console.aws.amazon.com//systems-manager/.

  2. En el panel de navegación, seleccione Documentos y, a continuación, seleccione Crear documento, Comando o sesión.

  3. En Name (Nombre), ingrese un nombre descriptivo para el documento.

  4. En Tipo de destino, seleccione/AWS::EC2::Instance.

  5. En Tipo de documento, seleccione Comando.

  6. En el campo Contenido, seleccione YAML y, a continuación, pegue el contenido del documento.

  7. En la sección Etiquetas de documento, agregue una etiqueta con una clave de etiqueta de DLMScriptsAccess y un valor de etiqueta de true.

    importante

    La DLMScriptsAccess:true etiqueta la exige la política AWSDataLifecycleManagerSSMFullAccess AWS gestionada utilizada en el paso 3: Preparar la función de IAM de Amazon Data Lifecycle Manager. La política usa la clave de condición aws:ResourceTag para restringir el acceso a los documentos de SSM que tienen esta etiqueta.

  8. Elija Create document (Crear documento).

AWS CLI
Creación del documento de comandos de SSM

Utilice el comando create-document. En --name, especifique un nombre descriptivo del documento. En --document-type, especifique Command. En --content, especifique la ruta al archivo .yaml con el contenido del documento de SSM. En --tags, especifique "Key=DLMScriptsAccess,Value=true".

$ aws ssm create-document \ --content file://path/to/file/documentContent.yaml \ --name "document_name" \ --document-type "Command" \ --document-format YAML \ --tags "Key=DLMScriptsAccess,Value=true"
nota

Este paso es necesario si:

  • Debe crear o actualizar una política de instantáneas con scripts previos o posteriores que utilice un rol de IAM personalizado.

  • La línea de comandos se utiliza para crear o actualizar una política de instantáneas habilitada para scripts previos o posteriores que utilice el rol predeterminado.

Si utiliza la consola para crear o actualizar una política de instantáneas previa o posterior a las secuencias de comandos que utilice la función predeterminada para gestionar las instantáneas () AWSDataLifecycleManagerDefaultRole, omita este paso. En este caso, asociamos automáticamente la política a ese rol. AWSDataLifecycleManagerSSMFullAccess

Debe asegurarse de que el rol de IAM que utilice para la política conceda permiso a Amazon Data Lifecycle Manager para realizar las acciones de SSM necesarias para ejecutar scripts previos y posteriores en las instancias incluidas en la política.

Amazon Data Lifecycle Manager proporciona una política gestionada (AWSDataLifecycleManagerSSMFullAccess) que incluye los permisos necesarios. Puede asociar esta política a su rol de IAM para administrar las instantáneas y asegurarse de que incluya los permisos.

importante

La política AWSDataLifecycleManagerSSMFullAccess gestionada utiliza la clave de aws:ResourceTag condición para restringir el acceso a documentos SSM específicos cuando se utilizan scripts previos y posteriores. Para permitir que Amazon Data Lifecycle Manager acceda a los documentos de SSM, debe asegurarse de que sus documentos de SSM estén etiquetados con DLMScriptsAccess:true.

Como alternativa, puede crear manualmente una política personalizada o asignar los permisos necesarios directamente al rol de IAM que utilice. Puede utilizar los mismos permisos que se definen en la política AWSDataLifecycleManagerSSMFullAccess gestionada; sin embargo, la clave de aws:ResourceTag condición es opcional. Si decide no incluir esa clave de condición, no necesitará etiquetar sus documentos de SSM con DLMScriptsAccess:true.

Utilice uno de los siguientes métodos para añadir la AWSDataLifecycleManagerSSMFullAccesspolítica a su función de IAM.

Console
Asociación de la política administrada a su rol personalizado
  1. Abra la consola de IAM en https://console.aws.amazon.com/iam/.

  2. En el panel de navegación, elija Roles.

  3. Busque y seleccione el rol personalizado para administrar instantáneas.

  4. En la pestaña Permisos, elija Agregar permisos, Asociar políticas.

  5. Busque y seleccione la política AWSDataLifecycleManagerSSMFullAccessgestionada y, a continuación, elija Añadir permisos.

AWS CLI
Asociación de la política administrada a su rol personalizado

Utilice el comando attach-role-policy. En ---role-name, especifique el nombre de su rol personalizado. En --policy-arn, especifique arn:aws:iam::aws:policy/AWSDataLifecycleManagerSSMFullAccess.

$ aws iam attach-role-policy \ --policy-arn arn:aws:iam::aws:policy/AWSDataLifecycleManagerSSMFullAccess \ --role-name your_role_name

Para automatizar las instantáneas coherentes con la aplicación, debe crear una política de ciclo de vida de las instantáneas que englobe las instancias y configurar los scripts previos y posteriores para esa política.

Console
Creación de una política de ciclo de vida de las instantáneas
  1. Abra la consola de Amazon EC2 en https://console.aws.amazon.com/ec2/.

  2. En el panel de navegación, elija Elastic Block Store, Lifecycle Manager (Administrador de ciclo de vida) y, a continuación, Create lifecycle policy (Crear política de ciclo de vida).

  3. En la pantalla Select policy type (Seleccionar el tipo de política), elija EBS snapshot policy (Política de instantáneas de EBS) y, luego, seleccione Next (Siguiente).

  4. En la sección Target resources (Recursos de destino), haga lo siguiente:

    1. En Tipos de recursos de destino, elija Instance.

    2. En Etiquetas de recursos de destino, especifique las etiquetas de recursos que identifican las instancias de las que se va a realizar una copia de seguridad. Solo se realizará una copia de seguridad de los recursos que tengan las etiquetas especificadas.

  5. Para el rol de IAM, elija AWSDataLifecycleManagerDefaultRole(el rol predeterminado para administrar las instantáneas) o elija un rol personalizado que haya creado y preparado para los guiones previos y posteriores.

  6. Configure las programaciones y las opciones adicionales según sea necesario. Le recomendamos que programe las horas de creación de las instantáneas para periodos de tiempo que coincidan con su carga de trabajo; por ejemplo, durante los periodos de mantenimiento.

    En el caso de SAP HANA, le recomendamos que habilite la restauración rápida de instantáneas.

    nota

    Si habilita una programación para las copias de seguridad de VSS, no podrá habilitar la opción Excluir volúmenes de datos específicos ni Copiar etiquetas del origen.

  7. En la sección Scripts previos y posteriores, seleccione Habilitar scripts previos y posteriores y, a continuación, haga lo siguiente, en función de su carga de trabajo:

    • Para crear instantáneas coherentes con las aplicaciones de Windows, seleccione Copias de seguridad de VSS.

    • Para crear instantáneas coherentes con las aplicaciones de sus cargas de trabajo de SAP HANA, seleccione SAP HANA.

    • Para crear instantáneas coherentes con las aplicaciones de todas las demás bases de datos y cargas de trabajo, incluidas las bases de datos MySQL, PostgreSQL o InterSystems IRIS autogestionadas, mediante un documento SSM personalizado, seleccione Documento SSM personalizado.

      1. En Automatizar opción, seleccione Scripts previos y posteriores.

      2. En Documento de SSM, seleccione el documento de SSM que ha preparado.

  8. En función de la opción que haya seleccionado, configure las siguientes opciones adicionales:

    • Tiempo de espera del script: (solo documento de SSM personalizado) el periodo de espera tras el cual Amazon Data Lifecycle Manager no logra ejecutar el script si no se ha completado. Si un script no se completa dentro de su periodo de espera, Amazon Data Lifecycle Manager devuelve un error. El periodo de espera se aplica individualmente a los scripts previos y posteriores. El valor mínimo y predeterminado del periodo de espera es de 10 segundos. Y el periodo de espera máximo es de 120 segundos.

    • Reintentar los scripts fallidos: seleccione esta opción para volver a intentar ejecutar los scripts que no se completen dentro del periodo de espera. Si el script previo falla, Amazon Data Lifecycle Manager vuelve a intentar todo el proceso de creación de instantáneas, incluida la ejecución de los scripts previos y posteriores. Si se produce un error en el script posterior, Amazon Data Lifecycle Manager vuelve a intentarlo únicamente con el script posterior; en este caso, el script previo se habrá completado y es posible que se haya creado la instantánea.

    • Instantáneas coherentes ante bloqueos predeterminadas: seleccione esta opción para utilizar de forma predeterminada las instantáneas coherentes ante bloqueos si el script previo no se ejecuta. Este es el comportamiento de creación de instantáneas predeterminado para Amazon Data Lifecycle Manager si los scripts previos y posteriores no están habilitados. Si ha habilitado los reintentos, Amazon Data Lifecycle Manager utilizará de forma predeterminada las instantáneas coherentes ante bloqueos solo después de que se hayan agotado todos los reintentos. Si el script previo falla y no utiliza de forma predeterminada instantáneas coherentes ante bloqueos, Amazon Data Lifecycle Manager no creará instantáneas para la instancia durante esa ejecución programada.

      nota

      Si va a crear instantáneas para SAP HANA, puede que desee deshabilitar esta opción. Las instantáneas coherentes ante bloqueos de las cargas de trabajo de SAP HANA no se pueden restaurar de la misma manera.

  9. Elija Crear política predeterminada.

    nota

    Si detecta un error Role with name AWSDataLifecycleManagerDefaultRole already exists, consulte Resolución de problemas para obtener más información.

AWS CLI
Creación de una política de ciclo de vida de las instantáneas

Utilice el comando create-lifecycle-policy e incluya los parámetros Scripts en CreateRule. Para obtener más información sobre los parámetros, consulte la Referencia de la API de Amazon Data Lifecycle Manager.

$ aws dlm create-lifecycle-policy \ --description "policy_description" \ --state ENABLED \ --execution-role-arn iam_role_arn \ --policy-details file://policyDetails.json

Donde policyDetails.json incluye una de las siguientes acciones, en función de su caso de uso:

  • Copias de seguridad de VSS

    { "PolicyType": "EBS_SNAPSHOT_MANAGEMENT", "ResourceTypes": [ "INSTANCE" ], "TargetTags": [{ "Key": "tag_key", "Value": "tag_value" }], "Schedules": [{ "Name": "schedule_name", "CreateRule": { "CronExpression": "cron_for_creation_frequency", "Scripts": [{ "ExecutionHandler":"AWS_VSS_BACKUP", "ExecuteOperationOnScriptFailure":true|false, "MaximumRetryCount":retries (0-3) }] }, "RetainRule": { "Count": retention_count } }] }
  • Copias de seguridad de SAP HANA

    { "PolicyType": "EBS_SNAPSHOT_MANAGEMENT", "ResourceTypes": [ "INSTANCE" ], "TargetTags": [{ "Key": "tag_key", "Value": "tag_value" }], "Schedules": [{ "Name": "schedule_name", "CreateRule": { "CronExpression": "cron_for_creation_frequency", "Scripts": [{ "Stages": ["PRE","POST"], "ExecutionHandlerService":"AWS_SYSTEMS_MANAGER", "ExecutionHandler":"AWSSystemsManagerSAP-CreateDLMSnapshotForSAPHANA", "ExecuteOperationOnScriptFailure":true|false, "ExecutionTimeout":timeout_in_seconds (10-120), "MaximumRetryCount":retries (0-3) }] }, "RetainRule": { "Count": retention_count } }] }
  • Documento de SSM personalizado

    { "PolicyType": "EBS_SNAPSHOT_MANAGEMENT", "ResourceTypes": [ "INSTANCE" ], "TargetTags": [{ "Key": "tag_key", "Value": "tag_value" }], "Schedules": [{ "Name": "schedule_name", "CreateRule": { "CronExpression": "cron_for_creation_frequency", "Scripts": [{ "Stages": ["PRE","POST"], "ExecutionHandlerService":"AWS_SYSTEMS_MANAGER", "ExecutionHandler":"ssm_document_name|arn", "ExecuteOperationOnScriptFailure":true|false, "ExecutionTimeout":timeout_in_seconds (10-120), "MaximumRetryCount":retries (0-3) }] }, "RetainRule": { "Count": retention_count } }] }

Consideraciones sobre las copias de seguridad de VSS con Amazon Data Lifecycle Manager

Con Amazon Data Lifecycle Manager, puede realizar copias de seguridad y restaurar aplicaciones de Windows habilitadas para VSS (Servicio de instantáneas de volumen) que se ejecuten en instancias de Amazon EC2. Si la aplicación tiene un escritor VSS registrado en Windows VSS, Amazon Data Lifecycle Manager crea una instantánea que sea coherente con esa aplicación.

nota

Amazon Data Lifecycle Manager actualmente solo admite copias de seguridad coherentes con las aplicaciones de recursos que se ejecutan en Amazon EC2, específicamente para situaciones de copias de seguridad en las que los datos de la aplicación se pueden restaurar al sustituir una instancia existente por una nueva creada a partir de la copia de seguridad. No todos los tipos de instancia o aplicaciones son compatibles con las copias de seguridad de VSS. Para obtener más información, consulte ¿Qué es VSS? AWS en la Guía del usuario de Amazon EC2.

Tipos de instancias no admitidos

No se admiten los siguientes tipos de instancias de Amazon EC2 para las copias de seguridad de VSS. Si su política se dirige a uno de estos tipos de instancias, Amazon Data Lifecycle Manager puede seguir creando copias de seguridad de VSS, pero es posible que las instantáneas no se etiqueten con las etiquetas de sistema requeridas. Sin estas etiquetas, Amazon Data Lifecycle Manager no administrará las instantáneas tras su creación. Puede ser que necesite eliminar estas instantáneas manualmente.

  • T3: t3.nano | t3.micro

  • T3a: t3a.nano | t3a.micro

  • T2: t2.nano | t2.micro

Responsabilidad compartida de instantáneas coherentes con las aplicaciones

Debe asegurarse de que:
  • El agente SSM está instalado y se está ejecutando en las instancias de destino up-to-date

  • Systems Manager tenga permisos para realizar las acciones necesarias en las instancias de destino

  • Amazon Data Lifecycle Manager tiene permisos para realizar las acciones de Systems Manager necesarias para ejecutar scripts previos y posteriores en las instancias de destino.

  • Para las cargas de trabajo personalizadas, como las bases de datos MySQL, PostgreSQL o InterSystems IRIS autogestionadas, el documento SSM que utilice incluye las acciones correctas y necesarias para congelar, vaciar y descongelar las E/S de la configuración de la base de datos.

  • Las horas de creación de instantáneas se ajustan a la programación de su carga de trabajo. Por ejemplo, intente programar la creación de instantáneas durante los periodos de mantenimiento programados.

Amazon Data Lifecycle Manager garantiza que:
  • La creación de instantáneas se inicia dentro de los 60 minutos posteriores a la hora programada para crear instantáneas.

  • Los scripts previos se ejecutan antes de que se inicie la creación de la instantánea.

  • Los scripts posteriores se ejecutan una vez que el script previo se ejecuta correctamente y se ha iniciado la creación de la instantánea. Amazon Data Lifecycle Manager ejecuta el script posterior solo si el script previo se ejecuta correctamente. Si el script previo falla, Amazon Data Lifecycle Manager no ejecutará el script posterior.

  • Las instantáneas se etiquetan con las etiquetas correspondientes en el momento de su creación.

  • CloudWatch las métricas y los eventos se emiten cuando se inician los scripts y cuando fallan o se ejecutan correctamente.