

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

# 使用基础设施即代码（IaC）管理计划
<a name="manage-schedules-using-infrastructure-as-code-iac"></a>

**重要**  
在中心堆栈部署完成后，使用单独的模板部署计划。

AWS 上的实例调度器提供了自定义资源 (`ServiceInstanceSchedule`)，您可以使用该资源通过 AWS CloudFormation 配置和管理计划。自定义资源使用的 PascalCase 密钥与 Amazon DynamoDB 中的实例计划程序配置表相同（有关示例，请参阅下面的模板）。有关计划的字段的更多信息，请参阅[计划定义](schedule-reference.md#schedule-definitions)。有关时段的字段的更多信息，请参阅[时段定义](period-reference.md#period-definitions)。

在使用自定义资源创建计划时，默认情况下，该计划的名称是自定义资源的逻辑资源名称。要指定其他名称，请使用自定义资源的 Name 属性。默认情况下，该解决方案还会将堆栈名称作为前缀添加到计划名称中。如果您不想添加堆栈名称作为前缀，请使用 `NoStackPrefix` 属性。

在使用 Name 和 `NoStackPrefix` 属性时，请确保选择唯一的计划名称。如果已存在同名计划，将不会创建或更新资源。

要开始使用 IaC 管理计划，请复制并粘贴以下示例模板，然后根据需要自定义任意数量的计划。将文件另存为.template 文件（例如：`my-schedules.template`），然后使用 AWS CloudFormation 部署您的新模板。有关完整的计划模板的示例，请参阅[示例计划](period-reference.md#period-definitions)。

```
AWSTemplateFormatVersion: 2010-09-09
Parameters:
  ServiceInstanceScheduleServiceTokenARN:
    Type: String
    Description: (Required) service token arn taken from InstanceScheduler outputs
Metadata:
  'AWS::CloudFormation::Designer': {}
Resources:
  SampleSchedule1:
    Type: 'Custom::ServiceInstanceSchedule'
    Properties:
      ServiceToken: !Ref ServiceInstanceScheduleServiceTokenARN #do not edit this line
      NoStackPrefix: 'False'
      Name: my-renamed-sample-schedule
      Description: a full sample template for creating cfn schedules showing all possible values
      Timezone: America/New_York
      Enforced: 'True'
      Hibernate: 'True'
      RetainRunning: 'True'
      StopNewInstances: 'True'
      UseMaintenanceWindow: 'True'
      SsmMaintenanceWindow: 'my_window_name'
      Periods:
      - Description: run from 9-5 on the first 3 days of March
        BeginTime: '9:00'
        EndTime: '17:00'
        InstanceType: 't2.micro'
        MonthDays: '1-3'
        Months: '3'
      - Description: run from 2pm-5pm on the weekends
        BeginTime: '14:00'
        EndTime: '17:00'
        InstanceType: 't2.micro'
        WeekDays: 'Sat-Sun'

  SampleSchedule2:
    Type: 'Custom::ServiceInstanceSchedule'
    Properties:
      ServiceToken: !Ref ServiceInstanceScheduleServiceTokenARN #do not edit this line
      NoStackPrefix: 'True'
      Description: a sample template for creating simple cfn schedules
      Timezone: Europe/Amsterdam
      Periods:
      - Description: stop at 5pm every day
        EndTime: '17:00'
```

部署模板时，您必须为在 AWS 上部署实例计划程序提供 ServiceToken ARN。此 ARN 可以在其中找到，方法是导航 CloudFormation 到已部署的实例调度程序堆栈，选择**输出**，然后查找 `ServiceInstanceScheduleServiceToken.` 

**重要**  
请不要使用 DynamoDB 控制台或计划程序 CLI 来删除或修改已使用自定义资源配置的计划和时段。如果您执行此操作，则会导致堆栈中存储的参数与表中的值产生冲突。此外，请不要在使用 DynamoDB 控制台或计划程序 CLI 创建的计划中使用通过自定义资源配置的时段。

在删除主实例计划程序堆栈之前，必须先删除所有其他包含已使用自定义资源创建的计划和时段的堆栈，因为自定义资源堆栈包含主堆栈的 DynamoDB 表的依赖项。

在配置 DynamoDB 表中，已通过自定义资源配置的计划和时段可由 **configured\_in\_stack** 属性标识。该属性包含已用于创建项目的堆栈的 Amazon 资源名称。