사전 및 사후 스크립트로 애플리케이션에 일관되게 적용되는 스냅샷 자동화 - Amazon EBS

기계 번역으로 제공되는 번역입니다. 제공된 번역과 원본 영어의 내용이 상충하는 경우에는 영어 버전이 우선합니다.

사전 및 사후 스크립트로 애플리케이션에 일관되게 적용되는 스냅샷 자동화

Amazon Data Lifecycle Manager를 사용하면 인스턴스를 대상으로 하는 스냅샷 수명 주기 정책에서 사전 및 사후 스크립트를 활성화하여 애플리케이션에 일관되게 적용되는 스냅샷을 자동화할 수 있습니다.

Amazon Data Lifecycle Manager는 AWS Systems Manager (Systems Manager) 와 통합되어 애플리케이션 정합성이 보장되는 스냅샷을 지원합니다. Amazon Data Lifecycle Manager는 사전 및 사후 스크립트가 포함된 Systems Manager(SSM) 명령 문서를 사용하여 애플리케이션에 일관되게 적용되는 스냅샷을 완성하는 데 필요한 작업을 자동화합니다. Amazon Data Lifecycle Manager는 스냅샷 생성을 시작하기 전에 사전 스크립트의 명령을 실행하여 I/O를 동결하고 플러시합니다. Amazon Data Lifecycle Manager가 스냅샷 생성을 시작한 후 사후 스크립트의 명령을 실행하여 I/O를 재개합니다.

Amazon Data Lifecycle Manager를 사용하면 다음과 같은 애플리케이션에 일관되게 적용되는 스냅샷을 자동화할 수 있습니다.

  • 볼륨 섀도 복사본 서비스(VSS)를 사용하는 Windows 애플리케이션

  • SAP HANA는 관리형 SSDM 문서를 사용합니다. AWS 자세한 내용은 Amazon EBS snapshots for SAP HANA를 참조하세요.

  • SSM 문서 템플릿을 사용하는 자체 관리형 데이터베이스 (예: MySQL, InterSystems PostgreSQL 또는 IRIS)

애플리케이션에 일관되게 적용되는 스냅샷 시작하기

이 섹션에서는 Amazon Data Lifecycle Manager를 사용하여 애플리케이션에 일관되게 적용되는 스냅샷을 자동화하기 위해 따라야 하는 단계를 설명합니다.

Amazon Data Lifecycle Manager를 사용하여 애플리케이션에 일관되게 적용되는 스냅샷을 위한 대상 인스턴스를 준비해야 합니다. 사용 사례에 따라 다음 중 하나를 수행합니다.

Prepare for VSS Backups
VSS 백업을 위한 대상 인스턴스 준비
  1. SSM Agent가 아직 설치되지 않은 경우 대상 인스턴스에 SSM Agent를 설치합니다. SSM Agent가 대상 인스턴스에 이미 설치되어 있는 경우 이 단계를 건너뜁니다.

    자세한 내용은 Windows용 Amazon EC2 인스턴스에 수동으로 SSM Agent 설치를 참조하세요.

  2. SSM Agent가 실행 중인지 확인합니다. 자세한 내용은 SSM Agent 상태 확인 및 에이전트 시작을 참조하세요.

  3. Amazon EC2 인스턴스용 Systems Manager를 설정합니다. 자세한 내용은 AWS Systems Manager 사용 설명서의 Amazon EC2 인스턴스용 Systems Manager 설정을 참조하세요.

  4. VSS 백업에 대한 시스템 요구 사항이 충족되는지 확인합니다.

  5. VSS 사용 인스턴스 프로파일을 대상 인스턴스에 연결합니다.

  6. VSS 구성 요소를 설치합니다.

Prepare for SAP HANA backups
SAP HANA 백업을 위한 대상 인스턴스 준비
  1. 대상 인스턴스에서 SAP HANA 환경을 준비합니다.

    1. SAP HANA로 인스턴스를 설정합니다. 기존 SAP HANA 환경이 아직 없는 경우 SAP HANA Environment Setup on AWS를 참조할 수 있습니다.

    2. 적절한 관리자 사용자로 SystemDB에 로그인합니다.

    3. Amazon Data Lifecycle Manager에서 사용할 데이터베이스 백업 사용자를 생성합니다.

      CREATE USER username PASSWORD password NO FORCE_FIRST_PASSWORD_CHANGE;

      예를 들어, 다음 명령은 이름이 dlm_user이고 암호가 password인 사용자를 생성합니다.

      CREATE USER dlm_user PASSWORD password NO FORCE_FIRST_PASSWORD_CHANGE;
    4. 이전 단계에서 생성한 데이터베이스 백업 사용자에게 BACKUP OPERATOR 역할을 할당합니다.

      GRANT BACKUP OPERATOR TO username

      예를 들어, 다음 명령은 dlm_user라는 사용자에게 역할을 할당합니다.

      GRANT BACKUP OPERATOR TO dlm_user
    5. 운영 체제에 관리자(예: sidadm)로 로그인합니다.

    6. 사용자가 정보를 입력하지 않고도 SAP HANA SSM 문서가 SAP HANA에 연결할 수 있도록 연결 정보를 저장할 hdbuserstore 항목을 생성합니다.

      hdbuserstore set DLM_HANADB_SNAPSHOT_USER localhost:3hana_instance_number13 username password

      예:

      hdbuserstore set DLM_HANADB_SNAPSHOT_USER localhost:30013 dlm_user password
    7. 연결을 테스트합니다.

      hdbsql -U DLM_HANADB_SNAPSHOT_USER "select * from dummy"
  2. SSM Agent가 아직 설치되지 않은 경우 대상 인스턴스에 SSM Agent를 설치합니다. SSM Agent가 대상 인스턴스에 이미 설치되어 있는 경우 이 단계를 건너뜁니다.

    자세한 내용은 Linux용 Amazon EC2 인스턴스에 수동으로 SSM Agent 설치를 참조하세요.

  3. SSM Agent가 실행 중인지 확인합니다. 자세한 내용은 SSM Agent 상태 확인 및 에이전트 시작을 참조하세요.

  4. Amazon EC2 인스턴스용 Systems Manager를 설정합니다. 자세한 내용은 AWS Systems Manager 사용 설명서의 Amazon EC2 인스턴스용 Systems Manager 설정을 참조하세요.

Prepare for custom SSM documents
대상 인스턴스의 사용자 지정 SSM 문서 준비
  1. SSM Agent가 아직 설치되지 않은 경우 대상 인스턴스에 SSM Agent를 설치합니다. SSM Agent가 대상 인스턴스에 이미 설치되어 있는 경우 이 단계를 건너뜁니다.

  2. SSM Agent가 실행 중인지 확인합니다. 자세한 내용은 SSM Agent 상태 확인 및 에이전트 시작을 참조하세요.

  3. Amazon EC2 인스턴스용 Systems Manager를 설정합니다. 자세한 내용은 AWS Systems Manager 사용 설명서의 Amazon EC2 인스턴스용 Systems Manager 설정을 참조하세요.

참고

이 단계는 사용자 지정 SSM 문서에만 필요합니다. VSS 백업 또는 SAP HANA에는 필요하지 않습니다. VSS 백업 및 SAP HANA의 경우 Amazon 데이터 라이프사이클 관리자는 AWS 관리형 SSM 문서를 사용합니다.

MySQL, PostgreSQL 또는 InterSystems IRIS 등의 자체 관리형 데이터베이스에 대해 애플리케이션 정합성이 보장되는 스냅샷을 자동화하는 경우 스냅샷 생성이 시작되기 전에 I/O를 고정 및 플러시하는 사전 스크립트와 스냅샷 생성이 시작된 후 I/O를 동결시키는 사후 스크립트가 포함된 SSM 명령 문서를 생성해야 합니다.

MySQL, PostgreSQL 또는 InterSystems IRIS 데이터베이스에서 표준 구성을 사용하는 경우 아래 샘플 SSM 문서 콘텐츠를 사용하여 SSM 명령 문서를 만들 수 있습니다. MySQL, PostgreSQL 또는 InterSystems IRIS 데이터베이스가 비표준 구성을 사용하는 경우 아래 샘플 콘텐츠를 SSM 명령 문서의 시작점으로 사용한 다음 요구 사항에 맞게 사용자 정의할 수 있습니다. 또는 SSM 문서를 처음부터 새로 생성하려면 아래의 빈 SSM 문서 템플릿을 사용하여 해당 문서 섹션에 사전 및 사후 명령을 추가합니다.

유의할 사항:
  • SSM 문서가 데이터베이스 구성에 필요한 올바른 작업을 수행하는지 확인하는 것은 사용자의 책임입니다.

  • SSM 문서의 사전 및 사후 스크립트가 I/O를 성공적으로 동결, 플러시 및 재개할 수 있는 경우에만 스냅샷이 애플리케이션에 일관되게 적용됩니다.

  • SSM 문서에는 pre-script, post-scriptdry-run을 포함하여 allowedValues에 대한 필수 필드가 포함되어야 합니다. Amazon Data Lifecycle Manager는 이러한 섹션의 내용을 기반으로 인스턴스에서 명령을 실행합니다. SSM 문서에 이러한 섹션이 없는 경우 Amazon Data Lifecycle Manager는 해당 문서를 실패한 실행으로 간주합니다.

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

자세한 내용은 리포지토리를 참조하십시오. 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."

SSM 문서 내용이 있는 경우 다음 절차 중 하나를 사용하여 사용자 지정 SSM 문서를 생성합니다.

Console
SSM 명령 문서 생성
  1. https://console.aws.amazon.com//systems-manager/ 에서 AWS Systems Manager 콘솔을 엽니다.

  2. 탐색 창에서 문서를 선택한 다음 문서 생성, 명령 또는 세션을 선택합니다.

  3. [이름(Name)]에 문서에 대한 설명이 포함된 이름을 입력합니다.

  4. 대상 유형으로는 /를 선택합니다AWS::EC2::Instance.

  5. 문서 유형에서 명령을 선택합니다.

  6. 콘텐츠 필드에서 YAML을 선택한 다음 문서 내용을 붙여넣습니다.

  7. 문서 태그 섹션에서 태그 키가 DLMScriptsAccess이고 태그 값이 true인 태그를 추가합니다.

    중요

    DLMScriptsAccess:true태그는 3단계: Amazon Data Lifecycle Manager IAM 역할 준비에서 사용된 AWSDataLifecycleManagerSSMFullAccess AWS 관리형 정책에 필요합니다. 정책은 aws:ResourceTag 조건 키를 사용하여 이 태그가 있는 SSM 문서에 대한 액세스를 제한합니다.

  8. 문서 생성을 선택합니다.

AWS CLI
SSM 명령 문서 생성

create-document 명령을 사용합니다. --name에 문서에 대한 설명이 포함된 이름을 지정합니다. --document-type에서 Command를 지정합니다. --content에 대해 SSM 문서 내용이 포함된 .yaml 파일의 경로를 지정합니다. --tags에서 "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"
참고

이 단계는 다음과 같은 경우 필요합니다.

  • 사용자 지정 IAM 역할을 사용하는 사전/사후 스크립트 지원 스냅샷 정책을 생성하거나 업데이트합니다.

  • 명령줄을 사용하여 기본값을 사용하는 사전/사후 스크립트 지원 스냅샷 정책을 생성하거나 업데이트합니다.

콘솔을 사용하여 스냅샷 (AWSDataLifecycleManagerDefaultRole) 관리를 위한 기본 역할을 사용하는 사전/사후 스크립트 지원 스냅샷 정책을 생성하거나 업데이트하는 경우 이 단계를 건너뛰십시오. 이 경우 정책을 해당 역할에 자동으로 연결합니다. AWSDataLifecycleManagerSSMFullAccess

정책에 사용하는 IAM 역할이 Amazon Data Lifecycle Manager에 정책 대상 인스턴스에서 사전 및 사후 스크립트를 실행하는 데 필요한 SSM 작업을 수행할 수 있는 권한을 부여하는지 확인해야 합니다.

Amazon Data Lifecycle Manager는 필요한 권한이 포함된 관리형 정책 (AWSDataLifecycleManagerSSMFullAccess) 을 제공합니다. 이 정책을 스냅샷 관리를 위한 IAM 역할에 연결하여 권한이 포함되도록 할 수 있습니다.

중요

AWSDataLifecycleManagerSSMFullAccess 관리형 정책은 사전 및 사후 스크립트를 사용할 때 aws:ResourceTag 조건 키를 사용하여 특정 SSM 문서에 대한 액세스를 제한합니다. Amazon Data Lifecycle Manager가 SSM 문서에 액세스할 수 있도록 하려면 SSM 문서에 DLMScriptsAccess:true 태그가 지정되어 있는지 확인해야 합니다.

또는 사용자 지정 정책을 수동으로 생성하거나 사용하는 IAM 역할에 필요한 권한을 직접 할당할 수 있습니다. AWSDataLifecycleManagerSSMFullAccess 관리형 정책에 정의된 것과 동일한 권한을 사용할 수 있지만 aws:ResourceTag 조건 키는 선택 사항입니다. 해당 조건 키를 포함하지 않기로 결정하면 SSM 문서에 DLMScriptsAccess:true로 태그를 지정할 필요가 없습니다.

다음 방법 중 하나를 사용하여 IAM 역할에 AWSDataLifecycleManagerSSMFullAccess정책을 추가합니다.

Console
사용자 지정 역할에 관리형 정책 연결
  1. https://console.aws.amazon.com/iam/에서 IAM 콘솔을 엽니다.

  2. 탐색 창에서 [역할(Roles)]을 선택합니다.

  3. 스냅샷 관리를 위한 사용자 지정 역할을 검색하고 선택합니다.

  4. 권한 탭에서 권한 추가, 정책 연결을 선택합니다.

  5. AWSDataLifecycleManagerSSMFullAccess관리형 정책을 검색하여 선택한 다음 Add permissions (권한 추가) 를 선택합니다.

AWS CLI
사용자 지정 역할에 관리형 정책 연결

attach-role-policy 명령을 사용합니다. ---role-name에 대해 사용자 지정 역할의 이름을 지정합니다. --policy-arn에서 arn:aws:iam::aws:policy/AWSDataLifecycleManagerSSMFullAccess를 지정합니다.

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

애플리케이션에 일관되게 적용되는 스냅샷을 자동화하려면 인스턴스를 대상으로 하는 스냅샷 수명 주기 정책을 생성하고 해당 정책에 대한 사전 및 사후 스크립트를 구성해야 합니다.

Console
스냅샷 수명 주기 정책 생성
  1. https://console.aws.amazon.com/ec2/에서 Amazon EC2 콘솔을 엽니다.

  2. 탐색 창에서 Elastic Block Store, Lifecycle Manager수명 주기 정책 생성을 차례로 선택합니다.

  3. 정책 유형 선택(Select policy type) 화면에서 EBS 스냅샷 정책(EBS snapshot policy)을 선택한 후 다음(Next)을 선택합니다.

  4. 대상 리소스(Target resources) 섹션에서 다음을 수행합니다.

    1. 대상 리소스 유형에서는 Instance를 선택합니다.

    2. 대상 리소스 태그에서 백업할 인스턴스를 식별하는 리소스 태그를 지정합니다. 지정된 태그가 있는 리소스만 백업됩니다.

  5. IAM 역할의 경우 AWSDataLifecycleManagerDefaultRole(스냅샷 관리를 위한 기본 역할) 을 선택하거나 사전 및 사후 스크립트용으로 만들고 준비한 사용자 지정 역할을 선택합니다.

  6. 필요에 따라 일정과 추가 옵션을 구성합니다. 유지 관리 기간과 같이 워크로드에 맞는 기간으로 스냅샷 생성 시간을 예약하는 것이 좋습니다.

    SAP HANA의 경우 빠른 스냅샷 복원을 활성화하는 것이 좋습니다.

    참고

    VSS 백업에 대해 일정을 활성화하는 경우 특정 데이터 볼륨 제외 또는 소스에서 태그 복사를 활성화할 수 없습니다.

  7. 사전 및 사후 스크립트 섹션에서 사전 및 사후 스크립트 활성화를 선택하고 워크로드에 따라 다음을 수행합니다.

    • Windows 애플리케이션의 애플리케이션에 일관되게 적용되는 스냅샷을 생성하려면 VSS 백업을 선택합니다.

    • SAP HANA 워크로드의 애플리케이션에 일관되게 적용되는 스냅샷을 생성하려면 SAP HANA를 선택합니다.

    • 사용자 정의 SSM 문서를 사용하여 자체 관리형 MySQL, PostgreSQL 또는 InterSystems IRIS 데이터베이스를 비롯한 다른 모든 데이터베이스 및 워크로드의 애플리케이션 정합성이 보장되는 스냅샷을 생성하려면 사용자 지정 SSM 문서를 선택합니다.

      1. 자동화 옵션에서 사전 및 사후 스크립트를 선택합니다.

      2. SSM 문서에서 준비한 SSM 문서를 선택합니다.

  8. 선택한 옵션에 따라 다음과 같은 추가 옵션을 구성합니다.

    • 스크립트 제한 시간 - (사용자 지정 SSM 문서에만 해당) Amazon Data Lifecycle Manager에서 완료되지 않은 스크립트 실행 시도가 실패하기 전까지의 제한 시간입니다. 스크립트가 제한 시간 내에 완료되지 않으면 Amazon Data Lifecycle Manager에서 시도는 실패합니다. 제한 시간은 사전 스크립트와 사후 스크립트에 개별적으로 적용됩니다. 최소 및 기본 제한 시간은 10초입니다. 최대 제한 시간은 120초입니다.

    • 실패한 스크립트 재시도 - 제한 시간 내에 완료되지 않은 스크립트를 재시도하려면 이 옵션을 선택합니다. 사전 스크립트가 실패할 경우 Amazon Data Lifecycle Manager는 사전 및 사후 스크립트 실행을 포함하여 전체 스냅샷 생성 프로세스를 재시도합니다. 사후 스크립트가 실패할 경우 Amazon Data Lifecycle Manager는 사후 스크립트만 재시도합니다. 이 경우 사전 스크립트가 완료되고 스냅샷이 생성되었을 수 있습니다.

    • 중단 일관성 스냅샷으로 기본 설정 - 사전 스크립트 실행에 실패할 경우 중단 일관성 스냅샷을 기본값으로 설정하려면 이 옵션을 선택합니다. 이는 사전 및 사후 스크립트가 활성화되지 않은 경우 Amazon Data Lifecycle Manager의 기본 스냅샷 생성 동작입니다. 재시도를 활성화한 경우 Amazon Data Lifecycle Manager는 모든 재시도가 소진된 후에만 중단 일관성 스냅샷으로 기본 설정됩니다. 사전 스크립트가 실패하고 중단 일관성 스냅샷을 기본으로 설정하지 않으면 Amazon Data Lifecycle Manager는 해당 일정 실행 중에 인스턴스에 대한 스냅샷을 생성하지 않습니다.

      참고

      SAP HANA용 스냅샷을 생성하는 경우 이 옵션을 비활성화하는 것이 좋습니다. SAP HANA 워크로드의 중단 일관성 스냅샷은 동일한 방식으로 복원할 수 없습니다.

  9. 기본 정책 생성을 선택합니다.

    참고

    Role with name AWSDataLifecycleManagerDefaultRole already exists 오류가 발생하는 경우 자세한 내용은 문제 해결 섹션을 참조하세요.

AWS CLI
스냅샷 수명 주기 정책 생성

create-lifecycle-policy 명령을 사용하고 CreateRuleScripts 파라미터를 포함시킵니다. 파라미터에 대한 자세한 내용은 Amazon Data Lifecycle Manager API 참조를 확인하세요.

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

사용 사례에 따라 policyDetails.json에 다음 중 하나가 포함됩니다.

  • 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 } }] }
  • 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 } }] }
  • 사용자 지정 SSM 문서

    { "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 } }] }

Amazon Data Lifecycle Manager를 사용한 VSS 백업 고려 사항

Amazon Data Lifecycle Manager를 사용하면 Amazon EC2 인스턴스에서 실행되는 VSS(Volume Shadow Copy Service) 지원 Windows 애플리케이션을 백업 및 복원할 수 있습니다. 애플리케이션에 Windows VSS에 등록된 VSS 작성기가 있는 경우 Amazon Data Lifecycle Manager는 해당 애플리케이션에 일관되게 적용되는 스냅샷을 생성합니다.

참고

Amazon Data Lifecycle Manager는 현재 Amazon EC2에서 실행되는 리소스의 애플리케이션에 일관되게 적용되는 스냅샷만 지원합니다. 특히 기존 인스턴스를 백업에서 생성된 새 인스턴스로 교체하여 애플리케이션 데이터를 복원할 수 있는 백업 시나리오에 적합합니다. 모든 인스턴스 유형 또는 애플리케이션이 VSS 백업에 대해 지원되는 것은 아닙니다. 자세한 내용은 VSS란 무엇입니까? 를 참조하십시오. AWS Amazon EC2 사용 설명서에서 확인할 수 있습니다.

지원되지 않는 인스턴스 유형

다음 Amazon EC2 인스턴스 유형은 VSS 백업에 지원되지 않습니다. 정책이 이러한 인스턴스 유형 중 하나를 대상으로 하는 경우 Amazon Data Lifecycle Manager는 여전히 VSS 백업을 생성할 수 있지만 스냅샷에 필수 시스템 태그가 지정되지 않을 수 있습니다. 이러한 태그가 없으면 스냅샷은 생성 후 Amazon Data Lifecycle Manager에 의해 관리되지 않습니다. 이러한 스냅샷을 수동으로 삭제해야 할 수도 있습니다.

  • T3: t3.nano | t3.micro

  • T3a: t3a.nano | t3a.micro

  • T2: t2.nano | t2.micro

애플리케이션에 일관되게 적용되는 스냅샷에 대한 공동 책임

다음을 확인해야 합니다.
  • SSM 에이전트가 대상 인스턴스에 up-to-date 설치되어 실행되고 있습니다.

  • Systems Manager는 대상 인스턴스에 대해 필요한 작업을 수행할 수 있는 권한이 있습니다.

  • Amazon Data Lifecycle Manager는 대상 인스턴스에서 사전 및 사후 스크립트를 실행하는 데 필요한 Systems Manager 작업을 수행할 권한이 있습니다.

  • 자체 관리형 MySQL, PostgreSQL InterSystems 또는 IRIS 데이터베이스와 같은 사용자 지정 워크로드의 경우 사용하는 SSM 문서에는 데이터베이스 구성의 I/O를 고정, 비우기 및 해제하는 데 필요한 올바른 조치가 포함되어 있습니다.

  • 스냅샷 생성 시간은 워크로드 일정에 따라 조정됩니다. 예를 들어, 예약된 유지 관리 기간 동안 스냅샷 생성을 예약해 보세요.

Amazon Data Lifecycle Manager는 다음을 보장합니다.
  • 예약된 스냅샷 생성 시간으로부터 60분 내에 스냅샷 생성이 시작됩니다.

  • 스냅샷 생성이 시작되기 전에 사전 스크립트가 실행됩니다.

  • 사전 스크립트가 성공하고 스냅샷 생성이 시작된 후 사후 스크립트가 실행됩니다. Amazon Data Lifecycle Manager는 사전 스크립트가 성공한 경우에만 사후 스크립트를 실행합니다. 사전 스크립트가 실패하는 경우 Amazon Data Lifecycle Manager는 사후 스크립트를 실행하지 않습니다.

  • 생성 시 스냅샷애 적절한 태그가 지정됩니다.

  • CloudWatch 메트릭과 이벤트는 스크립트가 시작되거나 실패 또는 성공할 때 발생합니다.