

本文為英文版的機器翻譯版本，如內容有任何歧義或不一致之處，概以英文版為準。

# Data Lifecycle Manager 前置和後置指令碼的其他使用案例
<a name="script-other-use-cases"></a>

除了使用前置和後置指令碼來自動執行應用程式一致快照之外，您也可以同時或分別使用前置和後置指令碼，以便在建立快照之前或之後自動執行其他管理工作。例如：
+ 使用前置指令碼以在建立快照前套用修補程式。這可協助您在套用每週或每月定期軟體更新後建立快照。
**注意**  
如果您選擇僅執行前置指令碼，預設情況下會啟用**預設為當機一致快照**。
+ 使用後置指令碼以在建立快照後套用修補程式。這可協助您在套用每週或每月定期軟體更新前建立快照。

## 開始使用其他使用案例
<a name="dlm-script-other"></a>

本節說明若要在**應用程式一致快照以外的使用案例**中使用前置和/或後置指令碼，您需要執行的步驟。

### 步驟 1：準備目標執行個體
<a name="dlm-script-other-prep-instance"></a>

**為前置和/或後置指令碼準備目標執行個體**

1. 如果目標執行個體上尚未安裝 SSM 代理程式，請安裝。如果目標執行個體上已安裝 SSM 代理程式，請跳過此步驟。
   + (Linux 執行個體） 在適用於 [ Linux 的 EC2 執行個體上手動安裝 SSM 代理](https://docs.aws.amazon.com/systems-manager/latest/userguide/manually-install-ssm-agent-linux.html)程式
   + (Windows 執行個體） [ 在 Windows Server 的 EC2 執行個體上使用 SSM Agent](https://docs.aws.amazon.com/systems-manager/latest/userguide/ssm-agent-windows.html)

1. 確定 SSM 代理程式執行中。如需詳細資訊，請參閱[檢查 SSM 代理程式狀態和啟動代理程式](https://docs.aws.amazon.com/systems-manager/latest/userguide/ssm-agent-status-and-restart.html)。

1. 設定 Amazon EC2 執行個體的 Systems Manager。如需詳細資訊，請參閱《AWS Systems Manager 使用者指南》**中的[為 Amazon EC2 執行個體設定 Systems Manager](https://docs.aws.amazon.com/systems-manager/latest/userguide/systems-manager-setting-up-ec2.html)。

### 步驟 2：準備 SSM 文件
<a name="dlm-script-other-prep-document"></a>

您必須建立 SSM 命令文件，其中包含您要執行之命令的前置和/或後置指令碼。

您可以使用下方的空白 SSM 文件範本建立 SSM 文件，並在適當的文件區段中新增前置和後置指令碼命令。

**注意下列事項：**  
您有責任確保 SSM 文件會針對工作負載執行正確且必要的動作。
SSM 文件必須包含 `allowedValues` 的必要欄位，包括 `pre-script`、`post-script` 和 `dry-run`。Amazon Data Lifecycle Manager 會根據這些區段的內容，在執行個體上執行命令。如果您的 SSM 文件沒有這些區段，Amazon Data Lifecycle Manager 便會將其視為執行失敗。

```
###===============================================================================###
# 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."
```

### 步驟 3：準備 Amazon Data Lifecycle Manager IAM 角色
<a name="dlm-script-other-prep-role"></a>

**注意**  
在下列情況中，需執行此步驟：  
您可以建立或更新使用自訂 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` 條件索引鍵是選用的。如果您決定不使用該條件索引鍵，就不需要使用 `DLMScriptsAccess:true` 來標記 SSM 文件。

使用下列其中一種方法，將 **AWSDataLifecycleManagerSSMFullAccess** 政策新增至您的 IAM 角色。

------
#### [ Console ]

**將受管政策連接至自訂角色**

1. 前往 [https://console.aws.amazon.com/iam/](https://console.aws.amazon.com/iam/) 開啟 IAM 主控台。

1. 在導覽窗格中，選擇 **Roles** (角色)。

1. 搜尋並選取您要管理快照的自訂角色。

1. 在**許可**索引標籤上，依序選擇**新增許可**、**連接政策**。

1. 搜尋並選取 **AWSDataLifecycleManagerSSMFullAccess** 受管政策，然後選擇**新增權限**。

------
#### [ AWS CLI ]

**將受管政策連接至自訂角色**  
使用 [attach-role-policy](https://docs.aws.amazon.com/cli/latest/reference/iam/attach-role-policy.html) 命令。在 `---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}}
```

------

### 建立快照生命週期政策
<a name="dlm-script-other-prep-policy"></a>

------
#### [ Console ]

**建立快照生命週期政策**

1. 前往 [https://console.aws.amazon.com/ec2/](https://console.aws.amazon.com/ec2/) 開啟 Amazon EC2 主控台。

1. 在導覽窗格中，選擇 **Elastic Block Store**、**Lifecycle Manager (生命週期管理員)**，然後選擇 **Create lifecycle policy (建立生命週期政策)**。

1. 在 **Select policy type** (選取政策類型) 畫面中，選取 **EBS snapshot policy** (EBS 快照政策)，然後選取 **Next** (下一步)。

1. 在 **Target resources** (目標資源) 區段中，執行下列動作：

   1. 針對**目標資源類型**，選擇 `Instance`。

   1. 在**目標資源標籤**，指定用來識別待備份磁碟區或執行個體的資源標籤。系統只會備份具有指定標籤的資源。

1. 在 **IAM 角色**選擇 **AWSDataLifecycleManagerDefaultRole** (管理快照的預設角色)，或選擇您為前置和後置指令碼建立並準備好的自訂角色。

1. 根據需要設定排程和其他選項。建議您針對配合工作負載的期間 (例如維護時段) 排程快照建立時間。

1. 在**前置和後置指令碼**區段中，選取**啟用前置和後置指令碼**，然後執行下列操作：

   1. 選取**自訂 SSM 文件**。

   1. 在**自動執行選項**選擇與您要執行的指令碼相符的選項。

   1. 在 **SSM 文件**選取您準備好的 SSM 文件。

1. 視需要設定下列其他選項：
   + **指令碼逾時**：此逾時期間過後，如果指令碼未完成，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 就不會在該排程執行期間為執行個體建立快照。

1. 選擇**建立預設政策**。
**注意**  
如果出現 `Role with name AWSDataLifecycleManagerDefaultRole already exists` 錯誤，請參閱 [對 Amazon Data Lifecycle Manager 問題進行故障診斷](dlm-troubleshooting.md) 以取得更多資訊。

------
#### [ AWS CLI ]

**建立快照生命週期政策**  
使用 [create-lifecycle-policy](https://docs.aws.amazon.com/cli/latest/reference/dlm/create-lifecycle-policy.html) 命令，並在 `CreateRule` 中包含 `Scripts` 參數。如需有關參數的詳細資訊，請參閱 [https://docs.aws.amazon.com/dlm/latest/APIReference/API_Script.html](https://docs.aws.amazon.com/dlm/latest/APIReference/API_Script.html)。

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

`policyDetails.json` 包括以下項目。

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

------