

本文属于机器翻译版本。若本译文内容与英语原文存在差异，则一律以英文原文为准。

# Data Lifecycle Manager 前置和后置脚本的其他使用场景
<a name="script-other-use-cases"></a>

除了使用前置和后置脚本自动生成应用程序一致性快照外，您还可以同时或单独使用前置和后置脚本，以在创建快照之前或之后自动执行其他管理任务。例如：
+ 创建快照之前使用前置脚本来应用补丁。这可以帮助您在应用每周或每月定期软件更新后创建快照。
**注意**  
如果您选择仅运行前置脚本，则默认情况下会启用**默认创建崩溃一致性快照**。
+ 创建快照后使用后置脚本应用补丁。这可以帮助您在应用每周或每月定期软件更新之前创建快照。

## 其他用例入门
<a name="dlm-script-other"></a>

本节介绍在**应用程序一致性快照以外的用例**中使用 and/or 发布前脚本时需要执行的步骤。

### 步骤 1：准备目标实例
<a name="dlm-script-other-prep-instance"></a>

**为 and/or 发布前脚本准备目标实例**

1. 在目标实例上安装 SSM Agent（如果尚未安装）。如果目标实例上已安装 SSM Agent，请跳过此步骤。
   + （Linux 实例）[在适用于 Linux 的 EC2 实例上手动安装 SSM Agent](https://docs.amazonaws.cn/systems-manager/latest/userguide/manually-install-ssm-agent-linux.html)
   + （Windows 实例）[在适用于 Windows 的 EC2 实例上手动安装 SSM Agent](https://docs.amazonaws.cn/systems-manager/latest/userguide/ssm-agent-windows.html)

1. 确保 SSM Agent 正在运行。有关更多信息，请参阅[正在检查 SSM Agent 状态并启动代理](https://docs.amazonaws.cn/systems-manager/latest/userguide/ssm-agent-status-and-restart.html)。

1. 为 Amazon EC2 实例设置 Systems Manager。有关更多信息，请参阅《Amazon Systems Manager 用户指南》**中的[为 Amazon EC2 实例设置 Systems Manager](https://docs.amazonaws.cn/systems-manager/latest/userguide/systems-manager-setting-up-ec2.html)。

### 步骤 2：准备 SSM 文档
<a name="dlm-script-other-prep-document"></a>

您必须创建一个 SSM 命令文档，其中包含带有要运行的命令的 and/or 发布前脚本。

您可以使用下面的 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 角色的 pre/post 支持脚本的快照策略。
您可以使用命令行创建或更新使用默认值的 pre/post 启用脚本的快照策略。
如果您使用控制台创建或更新使用默认角色管理快照的 pre/post 启用脚本的快照策略（**AWSDataLifecycleManagerDefaultRole**），请跳过此步骤。在这种情况下，我们会自动将**AWSDataLifecycleManagerSSMFull访问**策略附加到该角色。

您必须确保用于策略的 IAM 角色授予 Amazon Data Lifecycle Manager 权限，以执行在策略作为目标的实例上运行前置和后置脚本所需的 SSM 操作的权限。

Amazon Data Lifecycle Manager 提供了包含所需权限的托管策略（**AWSDataLifecycleManagerSSMFull访问**权限）。您可以将此策略附加到您的 IAM 角色以管理快照，从而确保其包含这些权限。

**重要**  
使用预脚本和后置脚本时， AWSDataLifecycleManagerSSMFull访问管理策略使用`aws:ResourceTag`条件键来限制对特定 SSM 文档的访问。要允许 Amazon Data Lifecycle Manager 访问 SSM 文档，您必须确保您的 SSM 文档带有 `DLMScriptsAccess:true` 标签。

或者，您可以手动创建自定义策略或将所需权限直接分配给您使用的 IAM 角色。您可以使用 AWSDataLifecycleManagerSSMFull访问管理策略中定义的相同权限，但是，`aws:ResourceTag`条件键是可选的。如果您决定不使用该条件键，则无需使用 `DLMScriptsAccess:true` 标记您的 SSM 文档。

使用以下方法之一将**AWSDataLifecycleManagerSSMFull访问**策略添加到您的 IAM 角色。

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

**将托管策略附加到您的自定义角色**

1. 使用 [https://console.aws.amazon.com/iam/](https://console.amazonaws.cn/iam/) 打开 IAM 控制台。

1. 在导航面板中，选择 **Roles**（角色）。

1. 搜索并选择用于管理快照的自定义角色。

1. 在**权限**选项卡上，选择**添加权限**、**附加策略**。

1. 搜索并选择**AWSDataLifecycleManagerSSMFull访问**托管策略，然后选择**添加权限**。

------
#### [ Amazon CLI ]

**将托管策略附加到您的自定义角色**  
使用 [ attach-role-policy](https://docs.amazonaws.cn/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.amazonaws.cn/ec2/) 的 Amazon EC2 控制台。

1. 在导航窗格中，依次选择 **Elastic Block Store** 和**生命周期管理器**，然后选择**创建生命周期策略**。

1. 在**选择策略类型**页面上，选择 **EBS 快照策略**，然后选择**下一步**。

1. 在**目标资源**部分中，执行以下操作：

   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) 来了解更多信息。

------
#### [ Amazon CLI ]

**创建快照生命周期策略**  
使用[create-lifecycle-policy](https://docs.amazonaws.cn/cli/latest/reference/dlm/create-lifecycle-policy.html)命令，并将`Scripts`参数包含在中`CreateRule`。有关参数的更多信息，请参阅 [Amazon Data Lifecycle Manager API Reference](https://docs.amazonaws.cn/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}}
        }
    }]
}
```

------