

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

# 使用基礎設施即程式碼 (IaC) 管理排程
<a name="manage-schedules-using-infrastructure-as-code-iac"></a>

**重要**  
在中樞堆疊部署完成後，使用個別範本部署排程。

AWS 上的執行個體排程器提供自訂資源 (`ServiceInstanceSchedule`)，您可以透過 AWS CloudFormation 來設定和管理排程。自訂資源針對與 Amazon DynamoDB 中執行個體排程器組態資料表相同的資料使用 PascalCase 金鑰 （範例請參閱下列範本）。如需排程欄位的詳細資訊，請參閱[排程定義](schedule-reference.md#schedule-definitions)。如需期間欄位的詳細資訊，請參閱[期間定義](period-reference.md#period-definitions)。

當您使用自訂資源建立排程時，該排程的名稱預設為自訂資源的邏輯資源名稱。若要指定不同的名稱，請使用自訂資源的名稱屬性。根據預設，解決方案也會將堆疊名稱新增至排程名稱做為字首。如果您不想將堆疊名稱新增為字首，請使用 `NoStackPrefix` 屬性。

當您使用名稱和`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 上部署執行個體排程器提供 ServiceTokenARN。您可以在 CloudFormation 中找到此 ARN，方法是導覽至您部署的執行個體排程器堆疊、選取**輸出**，以及尋找 `ServiceInstanceScheduleServiceToken.` 

**重要**  
請勿使用 DynamoDB 主控台或排程器 CLI 來刪除或修改使用自訂資源設定的排程和期間。如果您這樣做，您將在堆疊中的預存參數與資料表中的值之間建立衝突。此外，請不要在使用 DynamoDB 主控台或排程器 CLI 建立的排程中使用自訂資源設定的期間。

在刪除主要執行個體排程器堆疊之前，您必須刪除包含使用自訂資源建立之排程和期間的所有額外堆疊，因為自訂資源堆疊包含主要堆疊 DynamoDB 資料表的相依性。

在組態 DynamoDB 資料表中，可透過 **configured\$1in\$1stack** 屬性來識別使用自訂資源設定的排程和期間。屬性包含用於建立項目之堆疊的 Amazon Resource Name。