Automatizar snapshots consistentes com a aplicação com scripts prévios e posteriores - Amazon EBS

As traduções são geradas por tradução automática. Em caso de conflito entre o conteúdo da tradução e da versão original em inglês, a versão em inglês prevalecerá.

Automatizar snapshots consistentes com a aplicação com scripts prévios e posteriores

Você pode automatizar snapshots consistentes com a aplicação com o Amazon Data Lifecycle Manager habilitando scripts prévios e posteriores nas políticas de ciclo de vida de snapshot que têm as instâncias como alvo.

O Amazon Data Lifecycle Manager se integra ao (Systems AWS Systems Manager Manager) para oferecer suporte a snapshots consistentes com aplicativos. O Amazon Data Lifecycle Manager usa documentos de comando do Systems Manager (SSM) que incluem scripts prévios e posteriores para automatizar as ações necessárias para fazer snapshots consistentes com a aplicação. Antes de iniciar a criação de snapshots, o Amazon Data Lifecycle Manager executa os comandos do script prévio para congelar e despejar a E/S. Depois que o Amazon Data Lifecycle Manager inicia a criação de snapshots, ele executa os comandos do script posterior para descongelar a E/S.

Usando o Amazon Data Lifecycle Manager, você pode automatizar os snapshots consistentes com a aplicação dos seguintes itens:

  • Aplicações do Windows que usam o Volume Shadow Copy Service (VSS)

  • SAP HANA usando um documento AWS SSDM gerenciado. Para obter mais informações, consulte Amazon EBS snapshots for SAP HANA.

  • Bancos de dados autogerenciados, como MySQL, PostgreSQL ou IRIS, usando modelos de documentos SSM InterSystems

Conceitos básicos dos snapshots consistentes com a aplicação

Esta seção explica as etapas que você precisa seguir para automatizar snapshots consistentes com a aplicação usando o Amazon Data Lifecycle Manager.

Você precisa preparar as instâncias-alvo para snapshots consistentes com a aplicação usando o Amazon Data Lifecycle Manager. Dependendo do caso de uso, faça um dos procedimentos a seguir.

Prepare for VSS Backups
Para preparar as instâncias-alvo para backups do VSS
  1. Instale o SSM Agent nas instâncias-alvo, se ainda não estiver instalado. Se o SSM Agent já estiver instalado em suas instâncias-alvo, pule esta etapa.

    Para obter mais informações, consulte Instalar o SSM Agent manualmente em instâncias do Amazon EC2 para Windows .

  2. Certifique-se de que o SSM Agent esteja em execução. Para obter mais informações, consulte Verificar o status do SSM Agent e iniciar o agente.

  3. Configure o Systems Manager para instâncias do Amazon EC2. Para obter mais informações, consulte Configuração do Systems Manager para instâncias Amazon EC2 no AWS Systems Manager Guia do usuário do .

  4. Certifique-se de que os requisitos do sistema para backups do VSS sejam atendidos.

  5. Anexe um perfil de instância habilitado para o VSS às instâncias-alvo.

  6. Instale os componentes do VSS.

Prepare for SAP HANA backups
Para preparar as instâncias-alvo para backups do SAP HANA
  1. Prepare o ambiente do SAP HANA nas instâncias-alvo.

    1. Configure a instância com o SAP HANA. Se você ainda não tiver um ambiente do SAP HANA, pode consultar SAP HANA Environment Setup on AWS.

    2. Faça login no SystemDB como um usuário administrador adequado.

    3. Crie um usuário de backup de banco de dados para ser usado com o Amazon Data Lifecycle Manager.

      CREATE USER username PASSWORD password NO FORCE_FIRST_PASSWORD_CHANGE;

      Por exemplo, o comando a seguir criar um usuário denominado dlm_user com a senha password.

      CREATE USER dlm_user PASSWORD password NO FORCE_FIRST_PASSWORD_CHANGE;
    4. Atribua um perfil de BACKUP OPERATOR ao usuário de backup do banco de dados que você criou na etapa anterior.

      GRANT BACKUP OPERATOR TO username

      Por exemplo, o comando a seguir atribui o perfil a um usuário denominado dlm_user.

      GRANT BACKUP OPERATOR TO dlm_user
    5. Faça login no sistema operacional como administrador, por exemplo sidadm.

    6. Crie uma entrada hdbuserstore para armazenar as informações de conexão para que o documento do SSM do SAP HANA possa se conectar ao SAP HANA sem que os usuários precisem inserir as informações.

      hdbuserstore set DLM_HANADB_SNAPSHOT_USER localhost:3hana_instance_number13 username password

      Por exemplo: .

      hdbuserstore set DLM_HANADB_SNAPSHOT_USER localhost:30013 dlm_user password
    7. Teste a conexão.

      hdbsql -U DLM_HANADB_SNAPSHOT_USER "select * from dummy"
  2. Instale o SSM Agent nas instâncias-alvo, se ainda não estiver instalado. Se o SSM Agent já estiver instalado em suas instâncias-alvo, pule esta etapa.

    Para obter mais informações, consulte Instalar o SSM Agent manualmente em instâncias do Amazon EC2 para Linux.

  3. Certifique-se de que o SSM Agent esteja em execução. Para obter mais informações, consulte Verificar o status do SSM Agent e iniciar o agente.

  4. Configure o Systems Manager para instâncias do Amazon EC2. Para obter mais informações, consulte Configuração do Systems Manager para instâncias Amazon EC2 no AWS Systems Manager Guia do usuário do .

Prepare for custom SSM documents
Para preparar os documentos do SSM personalizados das instâncias-alvo
  1. Instale o SSM Agent nas instâncias-alvo, se ainda não estiver instalado. Se o SSM Agent já estiver instalado em suas instâncias-alvo, pule esta etapa.

  2. Certifique-se de que o SSM Agent esteja em execução. Para obter mais informações, consulte Verificar o status do SSM Agent e iniciar o agente.

  3. Configure o Systems Manager para instâncias do Amazon EC2. Para obter mais informações, consulte Configuração do Systems Manager para instâncias Amazon EC2 no AWS Systems Manager Guia do usuário do .

nota

Essa etapa só é necessária para documentos do SSM personalizados. Não é necessária para backup do VSS ou para o SAP HANA. Para backups do VSS e SAP HANA, o Amazon Data Lifecycle Manager AWS usa o documento SSM gerenciado.

Se você estiver automatizando instantâneos consistentes com aplicativos para um banco de dados autogerenciado, como MySQL, PostgreSQL InterSystems ou IRIS, deverá criar um documento de comando SSM que inclua um pré-script para congelar e liberar a E/S antes do início da criação do instantâneo e um pós-script para descongelar a E/S após o início da criação do instantâneo.

Se seu banco de dados MySQL, PostgreSQL ou InterSystems IRIS usa configurações padrão, você pode criar um documento de comando SSM usando o conteúdo de amostra do documento SSM abaixo. Se seu banco de dados MySQL, PostgreSQL ou InterSystems IRIS usa uma configuração não padrão, você pode usar o conteúdo de amostra abaixo como ponto de partida para seu documento de comando SSM e depois personalizá-lo para atender às suas necessidades. Ou então, se quiser criar um novo documento do SSM começando do zero, você pode usar o modelo de documento do SSM em branco abaixo e adicionar seus comandos prévios e posteriores nas seções apropriadas do documento.

Observe o seguinte:
  • É sua responsabilidade garantir que o documento do SSM realize as ações corretas e necessárias para a configuração do banco de dados.

  • Só haverá garantia de que os snapshots sejam consistentes com a aplicação se os scripts prévios e posteriores no documento do SSM puderem congelar, descarregar e descongelar a E/S com sucesso.

  • O documento do SSM deve incluir os campos obrigatórios para allowedValues, incluindo pre-script, post-script e dry-run. O Amazon Data Lifecycle Manager executará os comandos na instância com base no conteúdo dessas seções. Se o documento do SSM não tiver essas seções, o Amazon Data Lifecycle Manager o tratará como uma execução que falhou.

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 obter mais informações, consulte o GitHub repositório.

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."

Quando tiver o conteúdo do documento do SSM, use um dos procedimentos a seguir para criar o documento do SSM personalizado.

Console
Para criar um documento de comando do SSM
  1. Abra o AWS Systems Manager console em https://console.aws.amazon.com//systems-manager/.

  2. No painel de navegação, escolha Documentos e depois Criar documento, Comando ou Sessão.

  3. Em Name (Nome), insira um nome descritivo para o documento.

  4. Em Tipo de destino, selecione/AWS::EC2::Instance.

  5. Para Tipo de documento, selecione Comando.

  6. No campo Conteúdo, selecione YAML e cole o conteúdo do documento.

  7. Na seção Tags do documento, adicione uma tag com uma chave de tag de DLMScriptsAccess e um valor de tag de true.

    Importante

    A DLMScriptsAccess:true tag é exigida pela política AWSDataLifecycleManagerSSMFullAccess AWS gerenciada usada na Etapa 3: Preparar a função IAM do Amazon Data Lifecycle Manager. A política usa a chave de condição aws:ResourceTag para restringir o acesso aos documentos do SSM que tenham essa tag.

  8. Escolha Criar documento.

AWS CLI
Para criar um documento de comando do SSM

Use o comando create-document. Para --name, especifique um nome descritivo para o documento. Em --document-type, especifique Command. Para --content, especifique o caminho para o arquivo .yaml com o conteúdo do documento do SSM. Em --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

Essa etapa é necessária se:

  • Você criar ou atualizar uma política de snapshot habilitada para script prévio/posterior que usa um perfil do IAM personalizado.

  • Você usar a linha de comando para criar ou atualizar uma política de snapshot habilitado para script prévio/posterior.

Se você usar o console para criar ou atualizar uma política de instantâneos ativada antes e depois do script que usa a função padrão para gerenciar snapshots () AWSDataLifecycleManagerDefaultRole, pule esta etapa. Nesse caso, anexamos automaticamente a AWSDataLifecycleManagerSSMFullAccesspolítica a essa função.

Você deve garantir que o perfil do IAM que você usa para a política conceda ao Amazon Data Lifecycle Manager permissão para realizar as ações do SSM necessárias para executar scripts prévios e posteriores nas instâncias-alvo da política.

O Amazon Data Lifecycle Manager fornece uma política gerenciada (AWSDataLifecycleManagerSSMFullAccess) que inclui as permissões necessárias. Você pode anexar essa política ao perfil do IAM para gerenciar snapshots e garantir que ela inclua as permissões.

Importante

A política AWSDataLifecycleManagerSSMFullAccess gerenciada usa a chave de aws:ResourceTag condição para restringir o acesso a documentos SSM específicos ao usar scripts anteriores e posteriores. Para permitir que o Amazon Data Lifecycle Manager acesse os documentos do SSM, você deve garantir que eles estejam marcados com DLMScriptsAccess:true.

Ou então, você pode criar manualmente uma política personalizada ou atribuir as permissões necessárias diretamente ao perfil do IAM que você usa. Você pode usar as mesmas permissões definidas na política AWSDataLifecycleManagerSSMFullAccess gerenciada, no entanto, a chave de aws:ResourceTag condição é opcional. Se você decidir não incluir essa chave de condição, não precisará marcar os documentos do SSM com DLMScriptsAccess:true.

Use um dos métodos a seguir para adicionar a AWSDataLifecycleManagerSSMFullAccesspolítica à sua função do IAM.

Console
Para anexar a política gerenciada ao seu perfil personalizado
  1. Abra o console IAM em https://console.aws.amazon.com/iam/.

  2. No painel de navegação, selecione Roles (Funções).

  3. Pesquise e selecione o perfil personalizado para gerenciar os snapshots.

  4. Na guia Permissões, escolha Adicionar permissões, Anexar políticas.

  5. Pesquise e selecione a política AWSDataLifecycleManagerSSMFullAccessgerenciada e, em seguida, escolha Adicionar permissões.

AWS CLI
Para anexar a política gerenciada ao seu perfil personalizado

Use o comando attach-role-policy. Para ---role-name, especifique o nome do seu perfil personalizado. Em --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 snapshots consistentes com a aplicação, você deve criar uma política de ciclo de vida de snapshots que tenha como alvo as instâncias e configurar scripts prévios e posteriores para essa política.

Console
Para criar uma política de ciclo de vida de snapshots
  1. Abra o console do Amazon EC2 em https://console.aws.amazon.com/ec2/.

  2. No painel de navegação, selecione Elastic Block Store, Lifecycle Manager ((Gerenciador de ciclo de vida) e Create snapshot lifecycle policy (Criar política de ciclo de vida de snapshot).

  3. Na tela Select policy type (Selecionar tipo de política), escolha EBS snapshot policy (Política de snapshot do EBS) e depois Next (Próximo).

  4. Na seção Target resources (Recursos de destino), faça o seguinte:

    1. Para Tipos de recursos-alvo, escolha Instance.

    2. Para Tags de recurso-alvo, especifique as tags de recurso que identificam as instâncias para backup. Só será feito backup dos recursos que têm as tags especificadas.

  5. Para a função do IAM, escolha AWSDataLifecycleManagerDefaultRole(a função padrão para gerenciar instantâneos) ou escolha uma função personalizada que você criou e preparou para scripts anteriores e posteriores.

  6. Configure as agendas e as opções adicionais conforme necessário. Recomendamos que você agende a criação dos snapshots para períodos que atendam à sua workload, como durante janelas de manutenção.

    No SAP HANA, recomendamos que você habilite a restauração rápida de snapshots.

    nota

    Se você habilitar uma agenda para backups do VSS, não poderá habilitar Excluir volumes de dados específicos ou Copiar tags da fonte.

  7. Na seção Scripts prévios e posteriores, selecione Habilitar scripts prévios e posteriores e depois, dependendo da sua workload, faça o seguinte:

    • Para criar snapshots consistentes com a aplicação para as aplicações do Windows, selecione Backup do VSS.

    • Para criar snapshots consistentes com a aplicação de suas workloads do SAP HANA, selecione SAP HANA.

    • Para criar instantâneos consistentes com aplicativos de todos os outros bancos de dados e cargas de trabalho, incluindo seus bancos de dados MySQL, PostgreSQL InterSystems ou IRIS autogerenciados, usando um documento SSM personalizado, selecione Documento SSM personalizado.

      1. Para Opção de automatização, escolha Scripts prévios e posteriores.

      2. Para Documento do SSM, selecione o documento do SSM que você preparou.

  8. Dependendo da opção selecionada, configure as seguintes opções adicionais:

    • Tempo limite do script: (somente documento do SSM personalizado) O tempo limite após o qual o Amazon Data Lifecycle Manager considera que a tentativa de execução do script falhou se não foi concluída. Se um script não for concluído dentro do período limite, o Amazon Data Lifecycle Manager considerará que a tentativa falhou. O período de tempo limite se aplica aos scripts prévios e posteriores individualmente. O limite de tempo mínimo e padrão é de 10 segundos. E o tempo limite máximo é de 120 segundos.

    • Tentar os scripts com falha novamente: selecione essa opção para fazer novas tentativas de executar os scripts que não forem concluídos dentro do período de tempo limite. Se o script prévio falhar, o Amazon Data Lifecycle Manager tentará realizar novamente todo o processo de criação de snapshots, incluindo a execução dos scripts prévios e posteriores. Se o script posterior falhar, o Amazon Data Lifecycle Manager fará nova tentativa de executar apenas o script posterior; nesse caso, o script prévio estará sido concluído e o snapshot poderá ter sido criado.

    • Usar o padrão de snapshots consistentes em caso de falha: selecione essa opção para usar padrão de snapshots consistentes em caso de falha se a execução do script prévio falhar. Esse é o comportamento padrão da criação de snapshots para o Amazon Data Lifecycle Manager se os scripts prévios e posteriores não estiverem habilitados. Se você habilitou novas tentativas, o Amazon Data Lifecycle Manager só usará o padrão de snapshots consistentes em caso de falha após esgotar o todas as tentativas. Se o script prévio falhar e você não usar o padrão de snapshots consistentes em caso de falha, o Amazon Data Lifecycle Manager não criará snapshots para a instância durante da execução agendada.

      nota

      Se você estiver criando snapshots para o SAP HANA, talvez queira desabilitar essa opção. Os snapshots consistentes em caso de falha das workloads do SAP HANA não podem ser restaurados da mesma maneira.

  9. Escolha Criar política padrão.

    nota

    Se receber um erro Role with name AWSDataLifecycleManagerDefaultRole already exists, consulte Solução de problemas para obter mais informações.

AWS CLI
Para criar uma política de ciclo de vida de snapshots

Use o comando create-lifecycle-policy e inclua os parâmetros de Scripts em CreateRule. Para obter mais informações sobre os parâmetros, consulte Amazon Data Lifecycle Manager API Reference.

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

Em que policyDetails.json inclui um dos seguintes itens dependendo do caso de uso:

  • Backup do 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 } }] }
  • Backup do 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 do 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 } }] }

Considerações sobre os backups do VSS com o Amazon Data Lifecycle Manager

Com o Amazon Data Lifecycle Manager, você pode fazer backup e restaurar aplicações do Windows habilitadas para o VSS (Volume Shadow Copy Service) sendo executadas em instâncias do Amazon EC2. Se a aplicação tiver um gravador de VSS registrado no VSS do Windows, o Amazon Data Lifecycle Manager criará um snapshot que será consistente com a aplicação para essa aplicação.

nota

Atualmente, o Amazon Data Lifecycle Manager é compatível com snapshots consistentes com a aplicação apenas dos recursos executados no Amazon EC2, especificamente em cenários de backup em que os dados da aplicação podem ser restaurados substituindo uma instância existente por uma nova instância criada do backup. Nem todos os tipos de instância ou aplicação são compatíveis com os backups do VSS. Para obter mais informações, consulte O que é AWS VSS? no Guia do usuário do Amazon EC2.

Tipos de instâncias não compatíveis

Os seguintes tipos de instância do Amazon EC2 não são compatíveis com backups do VSS. Se sua política tiver como alvo um desses tipos de instância, o Amazon Data Lifecycle Manager ainda poderá criar backups do VSS, mas os snapshots talvez não estejam marcados com as tags de sistema necessárias. Sem essas tags, os snapshots não serão gerenciados pelo Amazon Data Lifecycle Manager após sua criação. Pode ser necessário excluir esses snapshots manualmente.

  • T3: t3.nano | t3.micro

  • T3a: t3a.nano | t3a.micro

  • T2: t2.nano | t2.micro

Responsabilidade compartilhada pelos snapshots consistentes com a aplicação

Você deve garantir que:
  • O agente SSM está instalado e em execução nas instâncias de destino up-to-date

  • O Systems Manager tenha permissões para executar as ações necessárias nas instâncias-alvo

  • O Amazon Data Lifecycle Manager tenha permissões para realizar as ações do Systems Manager necessárias para executar scripts prévios e posteriores nas instâncias-alvo.

  • Para cargas de trabalho personalizadas, como bancos de dados MySQL, PostgreSQL InterSystems ou IRIS autogerenciados, o documento SSM que você usa inclui as ações corretas e necessárias para congelar, limpar e descongelar a E/S da configuração do banco de dados.

  • Os horários de criação de snapshots estejam alinhados com sua agenda de workload. Por exemplo, tente agendar a criação de snapshots durante as janelas de manutenção agendadas.

O Amazon Data Lifecycle Manager garante que:
  • A criação do snapshot seja iniciada dentro de 60 minutos a partir do horário agendado para criação do snapshot.

  • Os scripts prévios sejam executados antes do início da criação do snapshot.

  • Os scripts posteriores sejam executados após o script prévio ser bem-sucedido e a criação do snapshot ter sido iniciada. O Amazon Data Lifecycle Manager só execute o script posterior se o script prévio for bem-sucedido. Se o script prévio falhar, o Amazon Data Lifecycle Manager não executará o script posterior.

  • Os snapshots sejam marcados com as tags apropriadas na criação.

  • CloudWatch métricas e eventos são emitidos quando os scripts são iniciados e quando falham ou são bem-sucedidos.