

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

# 將現有資源匯入堆疊
<a name="resource-import-existing-stack"></a>

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

**先決條件**

開始之前，您必須準備好以下項目：
+ 描述整個堆疊的範本，包括已是堆疊一部分的資源，以及要匯入的資源。在本機或 Amazon S3 儲存貯體中儲存範本。

  **取得執行中堆疊範本的副本**

  1. 開啟位在 [https://console.aws.amazon.com/cloudformation/](https://console.aws.amazon.com/cloudformation/) 的 CloudFormation​ 主控台。

  1. 從堆疊清單中，選擇要從中擷取範本的堆疊。

  1. 在堆疊詳細資訊窗格中，選擇**範本**索引標籤，再選擇**複製到剪貼簿**。

  1. 將程式碼貼到文字編輯器中，以開始將其他資源新增至範本。
+ 對於每個您要匯入的資源，需包含下列項目：
  + 定義資源目前組態的屬性與屬性數值。
  + 資源的唯一識別碼，如資源名稱。如需詳細資訊，請參閱[資源識別碼](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-existing-stack-example-template)
+ [使用 將現有資源匯入堆疊 AWS 管理主控台](#resource-import-existing-stack-console)
+ [使用 將現有資源匯入堆疊 AWS CLI](#resource-import-existing-stack-cli)

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

在此逐步說明中，我們假設您使用下列名為 `TemplateToImport.json` 的範例範本，指定兩個 DynamoDB 資料表。`GamesTable` 目前是堆疊的一部分，而 `ServiceTable` 是您要匯入的資料表。

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

```
{
    "AWSTemplateFormatVersion": "2010-09-09",
    "Description": "Import test",
    "Resources": {
        "ServiceTable": {
            "Type": "AWS::DynamoDB::Table",
            "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-existing-stack-console"></a>

**注意**  
CloudFormation 主控台不支援在匯入資源時使用內建函數 `Fn::Transform`。您可以使用 AWS CLI 匯入使用 `Fn::Transform`函數的資源。

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

1. 在 **Stacks (堆疊)** 頁面上，選擇您要匯入資源的堆疊。

1. 選擇 **Stack actions (堆疊動作)**，然後選擇 **Import resources into stack (將資源匯入堆疊)**。  
![\[主控台中 Import resource into stack (將資源匯入堆疊) 的選項。\]](http://docs.aws.amazon.com/zh_tw/AWSCloudFormation/latest/UserGuide/images/stack-actions-import.png)

1. 檢閱 **Import overview (匯入概觀)** 頁面，然後選擇 **Next (下一步)**。

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 (匯入資源)**。這會自動執行在最後一個步驟中建立的變更集合。此時會將任何堆疊層級標籤套用到匯入的資源。如需詳細資訊，請參閱[設定堆疊選項](cfn-console-create-stack.md#configure-stack-options)。

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

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

1. (選用) 如果您匯入的資源與其預期的範本組態不相符，請修正範本組態，或是直接更新資源。如需有關匯入漂移資源的詳細資訊，請參閱 [透過匯入作業解決漂移](resource-import-resolve-drift.md)。

## 使用 將現有資源匯入堆疊 AWS CLI
<a name="resource-import-existing-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"}}]
   ```

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

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

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

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"}}]'
   ```
**注意**  
`--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** 命令，並取代預留位置文字。此時會將任何堆疊層級標籤套用到匯入的資源。如需詳細資訊，請參閱[設定堆疊選項](cfn-console-create-stack.md#configure-stack-options)。成功完成操作 `(IMPORT_COMPLETE)` 後，資源便已順利匯入。

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

1. (選用) 在 `IMPORT_COMPLETE` 堆疊上執行漂移偵測，確認範本和匯入資源的實際組態相符。如需關於偵測漂移的詳細資訊，請參閱 [在整個 CloudFormation 堆疊上偵測偏離](detect-drift-stack.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. (選用) 如果您匯入的資源與其預期的範本組態不相符，請修正範本組態，或是直接更新資源。如需有關匯入漂移資源的詳細資訊，請參閱 [透過匯入作業解決漂移](resource-import-resolve-drift.md)。