

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

# 引導 Windows 型 CloudFormation 堆疊
<a name="cfn-windows-stacks-bootstrapping"></a>

本主題說明如何引導 Windows 堆疊和疑難排解堆疊建立問題。

**Topics**
+ [EC2 執行個體中的使用者資料](#cfn-windows-bootstrapping-user-data)
+ [CloudFormation 協助程式指令碼](#cfn-windows-bootstrapping-helper-scripts)
+ [引導 Windows 堆疊的範例](#cfn-windows-bootstrapping-example)
+ [Windows 檔案路徑中的轉義反斜線](#cfn-windows-stacks-escape-backslashes)
+ [管理 Windows 服務](#cfn-windows-stacks-manage-windows-services)
+ [疑難排解堆疊建立問題](#cfn-windows-stacks-troubleshooting)

## EC2 執行個體中的使用者資料
<a name="cfn-windows-bootstrapping-user-data"></a>

使用者資料是一種 Amazon EC2 功能，可讓您在啟動時將指令碼或組態資訊傳遞給 EC2 執行個體。

對於 Windows EC2 執行個體：
+ 可以使用批次指令碼 (使用 `<script>` 標籤) 或 PowerShell 指令碼 (使用`<powershell>` 標籤)。
+ 由 EC2Launch 處理指令碼執行。

**重要**  
如果要建立自己的 Windows AMI 以搭配 CloudFormation 使用，請確保已正確設定 EC2Launch v2。CloudFormation 引導工具需要 EC2Launch v2，才能在堆疊建立期間正確初始化和設定 Windows 執行個體。如需詳細資訊，請參閱《Amazon EC2 使用者指南》中的[在 EC2 Windows 執行個體啟動期間使用 EC2Launch v2 代理程式來執行任務](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2launch-v2.html)。**  
如需 AMIs的相關資訊 AWS Windows，請參閱 [AWS Windows AMI 參考](https://docs.aws.amazon.com/ec2/latest/windows-ami-reference/windows-amis.html)。

## CloudFormation 協助程式指令碼
<a name="cfn-windows-bootstrapping-helper-scripts"></a>

協助程式指令碼是在引導程序期間設定執行個體的公用程式。與 Amazon EC2 使用者資料搭配使用，其可提供強大的組態選項。

CloudFormation 提供下列 Python 協助程式指令碼，您可以使用這些指令碼在當做堆疊一部分建立的 Amazon EC2 執行個體上安裝軟體及啟動服務：
+  `cfn-init` – 用來擷取及解釋資源中繼資料、安裝套件、建立檔案及啟動服務。
+  `cfn-signal` – 用來透過 `CreationPolicy` 發出訊號，讓您可以在先決條件資源或應用程式就緒時，同步堆疊中的其他資源。
+  `cfn-get-metadata` – 用來擷取資源的中繼資料或特定金鑰的路徑。
+  `cfn-hup` – 用來檢查是否有中繼資料更新，並在偵測到變更時執行自訂勾點。

您可以直接從範本呼叫指令碼。指令碼會搭配同一個範本中定義的資源中繼資料使用。指令碼會在堆疊建立程序期間於 Amazon EC2 執行個體上執行。

如需詳細資訊，請參閱《CloudFormation 範本參考指南》中的 [CloudFormation 協助程式指令碼參考](https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/cfn-helper-scripts-reference.html)。**

## 引導 Windows 堆疊的範例
<a name="cfn-windows-bootstrapping-example"></a>

讓我們檢查執行下列動作的 Windows Server 範本中的範例程式碼片段：
+ 從 Windows Server 2022 AMI 中啟動名為 `TestInstance` 的 EC2 執行個體。
+ 建立簡單的測試檔案以驗證 `cfn-init` 是否正常運作。
+ 設定 `cfn-hup` 以進行持續的組態管理。
+ 使用 `CreationPolicy` 來確保執行個體發出成功完成的訊號。

`cfn-init` 協助程式指令碼用於根據範本中 `AWS::CloudFormation::Init` 資源中的資訊來執行這些動作中的每個動作。

`AWS::CloudFormation::Init` 區段名為 `TestInstance`，開頭為下列宣告。

```
TestInstance:
  Type: AWS::EC2::Instance
  Metadata:
    AWS::CloudFormation::Init:
      configSets:
        default:
          - create_files
          - start_services
```

在此之後，將宣告 `AWS::CloudFormation::Init` 的 `files` 區段：

```
      create_files:
        files:
          c:\cfn\test.txt:
            content: !Sub |
              Hello from ${AWS::StackName}
          c:\cfn\cfn-hup.conf:
            content: !Sub |
              [main]
              stack=${AWS::StackName}
              region=${AWS::Region}
              interval=2
          c:\cfn\hooks.d\cfn-auto-reloader.conf:
            content: !Sub |
              [cfn-auto-reloader-hook]
              triggers=post.update
              path=Resources.TestInstance.Metadata.AWS::CloudFormation::Init
              action=cfn-init.exe -v -s ${AWS::StackName} -r TestInstance -c default --region ${AWS::Region}
```

在此建立三個檔案，並放在伺服器執行個體的 `C:\cfn` 目錄中：
+ `test.txt`，一種簡單的測試檔案，可驗證 `cfn-init` 是否正常運作，並可建立具有動態內容的檔案。
+ `cfn-hup.conf`，`cfn-hup` 的組態檔案，具有 2 分鐘檢查間隔。
+ `cfn-auto-reloader.conf`，`cfn-hup` 使用的掛接組態檔案，當 `AWS::CloudFormation::Init` 中的中繼資料變更時，用於啟動更新 (呼叫 `cfn-init`)。

接下來是 `start_services` 區段，它可設定 Windows 服務。

```
      start_services:
        services:
          windows:
            cfn-hup:
              enabled: true
              ensureRunning: true
              files:
                - c:\cfn\cfn-hup.conf
                - c:\cfn\hooks.d\cfn-auto-reloader.conf
```

本節可確保 `cfn-hup` 服務已啟動，並在修改組態檔案時自動重新啟動。服務會監控 CloudFormation 中繼資料的變更，並在偵測到更新時重新執行 `cfn-init`。

接下來是 `Properties` 區段。

```
TestInstance:
  Type: AWS::EC2::Instance
  CreationPolicy:
    ResourceSignal:
      Timeout: PT20M
  Metadata:
    AWS::CloudFormation::Init:
      # ... metadata configuration ...
  Properties:
    InstanceType: t2.large
    ImageId: '{{resolve:ssm:/aws/service/ami-windows-latest/Windows_Server-2022-English-Full-Base}}'
    SecurityGroupIds:
      - !Ref InstanceSecurityGroup
    KeyName: !Ref KeyPairName
    UserData:
      Fn::Base64: !Sub |
        <powershell>
        cfn-init.exe -v -s ${AWS::StackName} -r TestInstance -c default --region ${AWS::Region}
        cfn-signal.exe -e $lastexitcode --stack ${AWS::StackName} --resource TestInstance --region ${AWS::Region}
        </powershell>
```

在此區段中，`UserData` 屬性包含 EC2Launch 將執行的 PowerShell 指令碼，被包圍在 `<powershell>` 標籤中。指令碼使用 `default` configSet 來執行 `cfn-init`，然後使用 `cfn-signal` 向 CloudFormation 回報結束碼。`CreationPolicy` 用於確保在堆疊建立視為完成之前正確設定執行個體。

`ImageId` 屬性會使用 Systems Manager Parameter Store 公有參數自動擷取最新的 Windows Server 2022 AMI ID。此方法不需要區域特定的 AMI 映射，並確保您始終取得最新的 AMI。針對 AMI ID 使用 Systems Manager 參數是維護目前 AMI 參考的最佳實務。如果打算連線到執行個體，請確保 `SecurityGroupIds` 屬性可參考允許 RDP 存取的安全群組。

`CreationPolicy` 會宣告為資源屬性的一部分，並指定逾時期間。執行個體組態完成時，使用者資料中的 `cfn-signal` 命令會發出訊號：

```
TestInstance:
  Type: AWS::EC2::Instance
  CreationPolicy:
    ResourceSignal:
      Timeout: PT20M
  Properties:
    # ... other properties ...
```

由於引導程序很小，而且只會建立檔案並啟動服務，因此 `CreationPolicy` 會在逾時前等待 20 分鐘 (PT20M)。使用 ISO 8601 持續時間格式來指定逾時。請注意，Windows 執行個體啟動所需的時間通常比 Linux 執行個體長，因此請進行徹底測試，以確定滿足您需求的最佳逾時值。

如果一切順利，`CreationPolicy` 會成功完成，而且您可以使用執行個體的公有 IP 位址來存取 Windows Server 執行個體。堆疊建立完成後，執行個體 ID 和公有 IP 位址將顯示在 CloudFormation 主控台的**輸出**標籤中。

```
Outputs:
  InstanceId:
    Value: !Ref TestInstance
    Description: Instance ID of the Windows Server
  PublicIP:
    Value: !GetAtt TestInstance.PublicIp
    Description: Public IP address of the Windows Server
```

也可以手動驗證引導是否正常運作，方法是透過 RDP 連線至執行個體，並檢查檔案 `C:\cfn\test.txt` 是否存在並包含預期的內容。如需有關連線至 Windows 執行個體的詳細資訊，請參閱《Amazon EC2 使用者指南》中的[使用 RDP 連線至 Windows 執行個體](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/connecting_to_windows_instance.html)。**

## Windows 檔案路徑中的轉義反斜線
<a name="cfn-windows-stacks-escape-backslashes"></a>

在 CloudFormation 範本中參考 Windows 路徑時，請務必記得根據您使用的範本格式正確轉義反斜線 (`\`)。
+ 對於 JSON 範本，必須在 Windows 檔案路徑中使用雙反斜線，因為 JSON 會將反斜線視為轉義字元。第一個反斜線會轉義第二個斜線，導致解譯單一常值反斜線。

  ```
  "commands" : {
    "1-extract" : {
      "command" : "C:\\SharePoint\\SharePointFoundation2010.exe /extract:C:\\SharePoint\\SPF2010 /quiet /log:C:\\SharePoint\\SharePointFoundation2010-extract.log"
    }
  }
  ```
+ 對於 YAML 範本，單一反斜線通常就足夠。

  ```
  commands:
    1-extract:
      command: C:\SharePoint\SharePointFoundation2010.exe /extract:C:\SharePoint\SPF2010 /quiet /log:C:\SharePoint\SharePointFoundation2010-extract.log
  ```

## 管理 Windows 服務
<a name="cfn-windows-stacks-manage-windows-services"></a>

您管理 Windows 服務的方式與管理 Linux 服務的方式相同，但使用的是 `windows` 鍵而非 `sysvinit`。下列範例會啟動 `cfn-hup` 服務，並將其設為「自動」，如果 `cfn-init` 修改 `c:\cfn\cfn-hup.conf` 或 `c:\cfn\hooks.d\cfn-auto-reloader.conf` 組態檔案，則會重新啟動服務。

```
        services:
          windows:
            cfn-hup:
              enabled: true
              ensureRunning: true
              files:
                - c:\cfn\cfn-hup.conf
                - c:\cfn\hooks.d\cfn-auto-reloader.conf
```

可以使用該名稱而非顯示名稱來參考服務，以相同的方式管理其他 Windows 服務。

## 疑難排解堆疊建立問題
<a name="cfn-windows-stacks-troubleshooting"></a>

如果堆疊在建立期間失敗，預設行為是復原故障。雖然這樣的預設行為一般而言是好的，因其可避免不必要的額外費用，但卻會對堆疊建立失敗原因進行除錯時造成困難。

若要在使用 CloudFormation 主控台建立或更新堆疊時關閉此行為，請選擇**堆疊失敗選項**下的**保留成功佈建的資源**選項。如需詳細資訊，請參閱[選擇佈建資源時的失敗處理方式](stack-failure-options.md)。這可讓您登入執行個體並檢視日誌檔案，以找出執行啟動指令碼時發生的問題。

要查看的重要日誌如下：
+ EC2 組態日誌，位於 `%ProgramData%\Amazon\EC2Launch\log\agent.log`
+ `C:\cfn\log\cfn-init.log` 中的 **cfn-init** 日誌 (檢查特定故障點的結束代碼和錯誤訊息)

如需更多日誌，請參閱《Amazon EC2 使用者指南》**中的下列主題：
+ [EC2Launch 目錄結構](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2config-service.html#UsingConfigXML_WinAMI)
+ [EC2Launch v2 目錄結構](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2launch-v2.html#ec2launch-v2-directory)

如需有關對引導問題進行疑難排解的詳細資訊，請參閱[如何使用 Windows 執行個體對 CloudFormation 堆疊中不會引導的協助程式指令碼進行疑難排解？](https://repost.aws/knowledge-center/cloudformation-helper-scripts-windows)。