

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

# 從現有資源建立堆疊
<a name="resource-import-new-stack"></a>

本主題說明如何透過在範本中描述現有 AWS 資源來建立堆疊。若要改為掃描現有資源並自動產生範本，以用於將現有資源匯入 CloudFormation 或在新帳戶中複製資源，請參閱 [使用 IaC 產生器從現有資源中產生範本](generate-IaC.md)。

**先決條件**

開始之前，您必須準備好以下項目：
+ 描述您在新堆疊中所需全部資源的範本。在本機或 Amazon S3 儲存貯體中儲存範本。
+ 對於每個您要匯入的資源，需包含下列項目：
  + 定義資源目前組態的屬性與屬性數值。
  + 資源的唯一識別碼，如資源名稱。如需詳細資訊，請參閱[資源識別碼](import-resources-manually.md#resource-import-identifiers-unique-ids)。
  + [DeletionPolicy 屬性](https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/aws-attribute-deletionpolicy.html)。

**Topics**
+ [範例 範本](#resource-import-new-stack-example-template)
+ [使用 從現有資源建立堆疊 AWS 管理主控台](#resource-import-new-stack-console)
+ [使用 從現有資源建立堆疊 AWS CLI](#resource-import-new-stack-cli)

## 範例 範本
<a name="resource-import-new-stack-example-template"></a>

在此逐步說明中，假設您使用下列名為 `TemplateToImport.json` 的範例範本，指定在 CloudFormation 外部建立的兩個 DynamoDB 資料表。`ServiceTable` 和 `GamesTable` 是匯入的目標。

**注意**  
此範本僅供範例參考。若要用於自身測試，請將範例資源替換為您帳戶中的資源。

```
{
    "AWSTemplateFormatVersion": "2010-09-09",
    "Description": "Import test",
    "Resources": {
        "ServiceTable": {
            "Type": "AWS::DynamoDB::Table",
            "DeletionPolicy": "Retain",
            "Properties": {
                "TableName": "Service",
                "AttributeDefinitions": [
                    {
                        "AttributeName": "key",
                        "AttributeType": "S"
                    }
                ],
                "KeySchema": [
                    {
                        "AttributeName": "key",
                        "KeyType": "HASH"
                    }
                ],
                "ProvisionedThroughput": {
                    "ReadCapacityUnits": 5,
                    "WriteCapacityUnits": 1
                }
            }
        },
        "GamesTable": {
            "Type": "AWS::DynamoDB::Table",
            "DeletionPolicy": "Retain",
            "Properties": {
                "TableName": "Games",
                "AttributeDefinitions": [
                    {
                        "AttributeName": "key",
                        "AttributeType": "S"
                    }
                ],
                "KeySchema": [
                    {
                        "AttributeName": "key",
                        "KeyType": "HASH"
                    }
                ],
                "ProvisionedThroughput": {
                    "ReadCapacityUnits": 5,
                    "WriteCapacityUnits": 1
                }
            }
        }
    }
}
```

## 使用 從現有資源建立堆疊 AWS 管理主控台
<a name="resource-import-new-stack-console"></a>

1. 登入 AWS 管理主控台 並在 https：//[https://console.aws.amazon.com/cloudformation](https://console.aws.amazon.com/cloudformation/) 開啟 CloudFormation 主控台。

1. 在 **Stacks (堆疊)** 頁面上，選擇 **Create stack (建立堆疊)**，然後選擇 **With existing resources (import resources) (使用現有資源 (匯入資源))**。  
![\[主控台中 Create stack from existing resources (從現有資源建立堆疊) 的選項。\]](http://docs.aws.amazon.com/zh_tw/AWSCloudFormation/latest/UserGuide/images/create-stack-with-existing-resources.png)

1. 請閱讀 **Import overview (匯入概觀)** 頁面，以取得您在此操作期間必須提供的項目清單。然後選擇**下一步**。

1. 在 **Specify template (指定範本)** 頁面上，使用以下其中一種方法提供您的範本，然後選擇 **Next (下一步)**。
   + 選擇 **Amazon S3 URL**，然後在文字方塊中為您的範本指定 URL。
   + 選擇 **Upload a template file (上傳範本檔案)**，然後瀏覽您的範本。

1. 在 **Identify resources (識別資源)** 頁面上，識別每個目標資源。如需詳細資訊，請參閱[資源識別碼](import-resources-manually.md#resource-import-identifiers-unique-ids)。

   1. 在 **Identifer property (識別碼屬性)** 下方，選擇資源識別碼類型。例如，`AWS::DynamoDB::Table` 資源可以使用 `TableName` 屬性進行識別。

   1. 在 **Identifer value (識別碼值)** 下方，輸入實際的屬性值。例如，範例範本中 `GamesTable` 資源的 `TableName` 是 `Games`。

   1. 選擇**下一步**。

1. 在 **Specify stack details (識別堆疊詳細資訊)** 頁面上，修改任何參數，然後選擇 **Next (下一步)**。這會自動建立變更集合。
**重要**  
如果您修改了啟動建立、更新或刪除操作的現有參數，匯入操作便會失敗。

1. 在 **Review *stack-name* (檢閱 stack-name)** 頁面上，確認您正在匯入正確的資源，然後選擇 **Import resources (匯入資源)**。這會自動執行在最後一個步驟中建立的變更集合。

   隨即會顯示新堆疊 **Stack details** (堆疊詳細資訊) 頁面的 **Events** (事件) 窗格。  
![\[主控台中的 Events (事件) 標籤。\]](http://docs.aws.amazon.com/zh_tw/AWSCloudFormation/latest/UserGuide/images/import-events.png)

1. (選用) 在 堆疊上執行漂移偵測，確認範本和匯入資源的實際組態相符。如需關於偵測漂移的詳細資訊，請參閱 [在整個 CloudFormation 堆疊上偵測偏離](detect-drift-stack.md)。

1. (選用) 如果您匯入的資源與其預期的範本組態不相符，請修正範本組態，或是直接更新資源。在本演練中，我們會修正範本組態，使其與資源的實際組態相符。

   1. 針對受影響的資源[還原匯入操作](resource-import-revert.md#resource-import-revert-console)。

   1. 再次將匯入目標新增至您的範本，確認範本組態與實際組態相符。

   1. 使用修改後的範本重複步驟 2 到 8，再次匯入資源。

## 使用 從現有資源建立堆疊 AWS CLI
<a name="resource-import-new-stack-cli"></a>

1. 若要了解範本中哪些屬性用於識別每種資源類型，請執行 **get-template-summary** 命令，並指定範本的 S3 網址。例如，`AWS::DynamoDB::Table` 資源可以使用 `TableName` 屬性進行識別。針對範例範本中的 `GamesTable` 資源，`TableName` 的值是 `Games`。在下一個步驟中，您將需要這項資訊。

   ```
   aws cloudformation get-template-summary \
       --template-url https://amzn-s3-demo-bucket.s3.us-west-2.amazonaws.com/TemplateToImport.json
   ```

   如需詳細資訊，請參閱[資源識別碼](import-resources-manually.md#resource-import-identifiers-unique-ids)。

1. 以下列 JSON 字串格式編寫您範本中實際資源的清單，以及這些資源的唯一識別碼。

   ```
   [{"ResourceType":"AWS::DynamoDB::Table","LogicalResourceId":"GamesTable","ResourceIdentifier":{"TableName":"Games"}},{"ResourceType":"AWS::DynamoDB::Table","LogicalResourceId":"ServiceTable","ResourceIdentifier":{"TableName":"Service"}}]
   ```

   您也可以在組態檔案中指定 JSON 格式參數。

   例如，若要匯入 `ServiceTable` 和 `GamesTable`，您可以建立名為 *ResourcesToImport.txt* 的檔案，並包含下列組態。

   ```
   [
      {
         "ResourceType":"AWS::DynamoDB::Table",
         "LogicalResourceId":"GamesTable",
         "ResourceIdentifier":{
            "TableName":"Games"
         }
      },
      {
         "ResourceType":"AWS::DynamoDB::Table",
         "LogicalResourceId":"ServiceTable",
         "ResourceIdentifier":{
            "TableName":"Service"
         }
      }
   ]
   ```

1. 要建立變更集，請使用下列 **create-change-set** 命令並取代預留位置文字。對於 `--change-set-type` 選項，請指定值為 **IMPORT**。對於 `--resources-to-import` 選項，請將範例 JSON 字串取代為您剛建立的實際 JSON 字串。

   ```
   aws cloudformation create-change-set \
       --stack-name TargetStack --change-set-name ImportChangeSet \
       --change-set-type IMPORT \
       --template-url https://amzn-s3-demo-bucket.s3.us-west-2.amazonaws.com/TemplateToImport.json \
       --resources-to-import '[{"ResourceType":"AWS::DynamoDB::Table","LogicalResourceId":"GamesTable","ResourceIdentifier":{"TableName":"Games"}},{"ResourceType":"AWS::DynamoDB::Table","LogicalResourceId":"ServiceTable","ResourceIdentifier":{"TableName":"Service"}}]'
   ```
**注意**  
`--resources-to-import` 不支援內嵌 YAML。JSON 字串中轉義引號的請求有所不同，這取決於您的終端。如需詳細資訊，請參閱《AWS Command Line Interface 使用者指南**》中的[在字串內使用引號](https://docs.aws.amazon.com/cli/latest/userguide/cli-usage-parameters-quoting-strings.html#cli-usage-parameters-quoting-strings-containing)。

   或者，您可以如下列範例所示，使用檔案 URL 做為 `--resources-to-import` 選項的輸入。

   ```
   --resources-to-import file://ResourcesToImport.txt
   ```

1. 檢閱變更集合，確認您將匯入正確的資源。

   ```
   aws cloudformation describe-change-set \
       --change-set-name ImportChangeSet --stack-name TargetStack
   ```

1. 若要啟動變更集並匯入資源，請使用下列 **execute-change-set** 命令，並取代預留位置文字。成功完成操作 `(IMPORT_COMPLETE)` 後，資源便已順利匯入。

   ```
   aws cloudformation execute-change-set \
       --change-set-name ImportChangeSet --stack-name TargetStack
   ```

1. (選用) 在 `IMPORT_COMPLETE` 堆疊上執行漂移偵測，確認範本和匯入資源的實際組態相符。如需關於偵測漂移的詳細資訊，請參閱 [在個別堆疊資源上偵測偏離](detect-drift-resource.md)。

   1. 在指定的堆疊上執行漂移偵測。

      ```
      aws cloudformation detect-stack-drift --stack-name TargetStack
      ```

      如果成功，此命令傳回的下列範例輸出。

      ```
      { "Stack-Drift-Detection-Id" : "624af370-311a-11e8-b6b7-500cexample" }
      ```

   1. 檢視指定堆疊漂移偵測 ID 的漂移偵測操作進度。

      ```
      aws cloudformation describe-stack-drift-detection-status \
          --stack-drift-detection-id 624af370-311a-11e8-b6b7-500cexample
      ```

   1. 檢視特定堆疊中已檢查是否漂移的資源的漂移資訊。

      ```
      aws cloudformation describe-stack-resource-drifts --stack-name TargetStack
      ```

1. (選用) 如果您匯入的資源與其預期的範本組態不相符，請修正範本組態，或是直接更新資源。在本演練中，我們會修正範本組態，使其與資源的實際組態相符。

   1. 針對受影響的資源[還原匯入操作](resource-import-revert.md#resource-import-revert-cli)。

   1. 再次將匯入目標新增至您的範本，確認範本組態與實際組態相符。

   1. 使用修改後的範本重複步驟 3 – 6，以再次匯入資源。