

# Import AWS resources into a CloudFormation stack
<a name="import-resources"></a>

You can import existing resources into a CloudFormation stack. This is useful if you want to start using CloudFormation to manage resources that were created outside of CloudFormation, without having to delete and recreate them.

CloudFormation offers the following options for importing existing resources into a stack:
+ [IaC generator](generate-IaC.md) is a tool that automatically scans your existing resources and generates a CloudFormation template based on their current state. This template can then be used to import those resources into a stack.
+ [Resource import](import-resources-manually.md) is a manual process where you describe the existing resources in your CloudFormation template and then import them into a stack. This approach requires you to manually specify the resource properties and configurations in the template.
+ [Auto-import](import-resources-automatically.md) is an automatic process where you describe existing resources in your CloudFormation template and CloudFormation imports the ones with matching custom names into a stack.
+ [Stack refactoring](stack-refactoring.md) is a feature that simplifies reorganizing the resources in your CloudFormation stacks while still preserving the existing resource properties and data. With stack refactoring, you can move resources between stacks, split monolithic stacks into smaller components, or consolidate multiple stacks into one.

In addition to bringing existing resources under CloudFormation management, the resource import feature can be useful in the following scenarios:
+ **Moving resources between stacks** – You can import resources from one stack into another, allowing you to reorganize your infrastructure as needed.
+ **Nesting existing stacks** – You can import an existing stack as a nested stack within another stack, enabling modular and reusable infrastructure designs.

CloudFormation supports importing a wide range of resources. For more information, see [Resource type support](resource-import-supported-resources.md).

**Topics**
+ [Manually import AWS resources](import-resources-manually.md)
+ [Automatically import AWS resources](import-resources-automatically.md)
+ [Reverting an import operation](resource-import-revert.md)

# Import AWS resources into a CloudFormation stack manually
<a name="import-resources-manually"></a>

With resource import, you can import existing AWS resources into a new or existing CloudFormation stack. During an import operation, you create a change set that imports your existing resources into a stack or creates a new stack from your existing resources. You provide the following during import.
+ A template that describes the entire stack, including both the original stack resources and the resources you're importing. Each resource to import must have a [DeletionPolicy attribute](https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/aws-attribute-deletionpolicy.html).
+ Identifiers for the resources you're importing that CloudFormation can use to map the logical IDs in the template with the existing resources.

**Note**  
CloudFormation only supports one level of nesting using resource import. This means that you can't import a stack into a child stack or import a stack that has children.

**Topics**
+ [Resource identifiers](#resource-import-identifiers-unique-ids)
+ [Validation](#resource-import-validation)
+ [Status codes](#resource-import-status-codes)
+ [Considerations](#resource-import-considerations)
+ [Additional resources](#resource-import-additional-resources)
+ [Creating a stack from existing resources](resource-import-new-stack.md)
+ [Importing existing resources into a stack](resource-import-existing-stack.md)
+ [Moving resources between stacks](refactor-stacks.md)
+ [Nesting an existing stack](resource-import-nested-stacks.md)

## Resource identifiers
<a name="resource-import-identifiers-unique-ids"></a>

You provide two values to identify each resource you're importing.
+ An identifier property. This is a resource property that can be used to identify each resource type. For example, an `AWS::S3::Bucket` resource can be identified using its `BucketName`.

  The resource property that you use to identify the resource you're importing varies with the resource type. You can find the resource property in the CloudFormation console. After you create a template that includes the resource to import, you can initiate the import process, where you'll find the identifier properties for the resources you're importing. For some resource types, there might be multiple ways to identify them, and you can select which property to use in the drop-down lists.

  Alternatively, you can get the identifier properties for the resources you're importing by calling the [get-template-summary](https://docs.aws.amazon.com/cli/latest/reference/cloudformation/get-template-summary.html) CLI command and specifying the S3 URL of the stack template as the value for the `--template-url` option.
+ An identifier value. This is the resource's actual property value. For example, the actual value for the `BucketName` property might be `MyS3Bucket`.

  You can get the value of the identifier property from the service console for the resource.

## Resource import validation
<a name="resource-import-validation"></a>

During an import operation, CloudFormation performs the following validations.
+ The resource to import exists.
+ The properties and configuration values for each resource to import adhere to the resource type schema, which defines its accepted properties, required properties, and supported property values.
+ The required properties are specified in the template. Required properties for each resource type are described in the [AWS resource and property types reference](https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/aws-template-resource-type-ref.html).
+ The resource to import doesn't belong to another stack in the same Region.

CloudFormation doesn't check that the template configuration matches the actual configuration of resource properties.

**Important**  
Verify that resources and their properties defined in the template match the intended configuration of the resource import to avoid unexpected changes.

## Resource import status codes
<a name="resource-import-status-codes"></a>

This table describes the various status types used with the resource import feature.


| Import operation status | Description | 
| --- | --- | 
|  `IMPORT_IN_PROGRESS`  |  The import operation is in progress.  | 
|  `IMPORT_COMPLETE`  |  The import operation completed for all resources in the stack.  | 
|  `IMPORT_ROLLBACK_IN_PROGRESS`  |  The rollback import operation is rolling back the previous template configuration.  | 
|  `IMPORT_ROLLBACK_FAILED`  |  The import rollback operation failed.  | 
|  `IMPORT_ROLLBACK_COMPLETE`  |  The import rolled back to the previous template configuration.  | 

## Considerations during an import operation
<a name="resource-import-considerations"></a>
+ After the import is complete and before performing subsequent stack operations, we recommend running drift detection on imported resources. Drift detection ensures that the template configuration matches the actual configuration. For more information, see [Detect drift on an entire CloudFormation stack](detect-drift-stack.md).
+ Import operations don't allow new resource creations, resource deletions, or changes to property configurations.
+ Each resource to import must have a `DeletionPolicy` attribute for the import operation to succeed. The `DeletionPolicy` can be set to any possible value. Only the resources you're importing need a `DeletionPolicy`. Resources that are already part of the stack don't need a `DeletionPolicy`.
+ You can't import the same resource into multiple stacks.
+ You can use the `cloudformation:ImportResourceTypes` IAM policy condition to control which resource types users can work with during an import operation. For more information, see [Policy condition keys for CloudFormation](control-access-with-iam.md#using-iam-conditions).
+ The CloudFormation stack limits apply when importing resources. For more information on limits, see [Understand CloudFormation quotas](cloudformation-limits.md).

## Additional resources
<a name="resource-import-additional-resources"></a>

To resolve stack drift with a resource import, see [Resolve drift with an import operation](resource-import-resolve-drift.md).

# Creating a stack from existing resources
<a name="resource-import-new-stack"></a>

This topic shows you how to create a stack from existing AWS resources by describing them in a template. To instead scan for existing resources and automatically generate a template that you can use to import existing resources into CloudFormation or replicate resources in a new account, see [Generate templates from existing resources with IaC generator](generate-IaC.md).

**Prerequisites**

Before you begin, you must have the following:
+ A template that describes all of the resources that you want in the new stack. Save the template locally or in an Amazon S3 bucket. 
+ For each resource you want to import, include the following:
  + the properties and property values that define the resource's current configuration.
  + the unique identifier for the resource, such as the resource name. For more information, see [Resource identifiers](import-resources-manually.md#resource-import-identifiers-unique-ids).
  + the [DeletionPolicy attribute](https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/aws-attribute-deletionpolicy.html).

**Topics**
+ [Example template](#resource-import-new-stack-example-template)
+ [Create a stack from existing resources using the AWS Management Console](#resource-import-new-stack-console)
+ [Create a stack from existing resources using the AWS CLI](#resource-import-new-stack-cli)

## Example template
<a name="resource-import-new-stack-example-template"></a>

In this walkthrough, we assume you're using the following example template, called `TemplateToImport.json`, that specifies two DynamoDB tables that were created outside of CloudFormation. `ServiceTable` and `GamesTable` are the targets of the import. 

**Note**  
This template is meant as an example only. To use it for your own testing purposes, replace the sample resources with resources from your account. 

```
{
    "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
                }
            }
        }
    }
}
```

## Create a stack from existing resources using the AWS Management Console
<a name="resource-import-new-stack-console"></a>

1. Sign in to the AWS Management Console and open the CloudFormation console at [https://console.aws.amazon.com/cloudformation](https://console.aws.amazon.com/cloudformation/).

1. On the **Stacks** page, choose **Create stack**, and then choose **With existing resources (import resources)**.  
![\[The Create stack from existing resources option in the console.\]](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/images/create-stack-with-existing-resources.png)

1. Read the **Import overview** page for a list of things you're required to provide during this operation. Then, choose **Next**.

1. On the **Specify template** page, provide your template using one of the following methods, and then choose **Next**.
   + Choose **Amazon S3 URL**, and then specify the URL for your template in the text box.
   + Choose **Upload a template file**, and then browse for your template.

1. On the **Identify resources** page, identify each target resource. For more information, see [Resource identifiers](import-resources-manually.md#resource-import-identifiers-unique-ids).

   1. Under **Identifier property**, choose the type of resource identifier. For example, the `AWS::DynamoDB::Table` resource can be identified using the `TableName` property.

   1. Under **Identifier value**, type the actual property value. For example, the `TableName` for the `GamesTable` resource in the example template is `Games`. 

   1. Choose **Next**.

1. On the **Specify stack details** page, modify any parameters, and then choose **Next**. This automatically creates a change set.
**Important**  
The import operation fails if you modify existing parameters that initiate a create, update, or delete operation.

1. On the **Review *stack-name*** page, confirm that the correct resources are being imported, and then choose **Import resources**. This automatically executes the change set created in the last step.

   The **Events** pane of the **Stack details** page for your new stack displays.  
![\[The Events tab in the console.\]](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/images/import-events.png)

1. (Optional) Run drift detection on the stack to make sure the template and actual configuration of the imported resources match. For more information about detecting drift, see [Detect drift on an entire CloudFormation stack](detect-drift-stack.md).

1. (Optional) If your imported resources don't match their expected template configurations, either correct the template configurations or update the resources directly. In this walkthrough, we correct the template configurations to match their actual configurations.

   1. [Revert the import operation](resource-import-revert.md#resource-import-revert-console) for the affected resources.

   1. Add the import targets to your template again, making sure that the template configurations match the actual configurations.

   1. Repeat steps 2 – 8 using the modified template to import the resources again.

## Create a stack from existing resources using the AWS CLI
<a name="resource-import-new-stack-cli"></a>

1. To learn which properties identify each resource type in the template, run the **get-template-summary** command, specifying the S3 URL of the template. For example, the `AWS::DynamoDB::Table` resource can be identified using the `TableName` property. For the `GamesTable` resource in the example template, the value of `TableName` is `Games`. You'll need this information in the next step.

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

   For more information, see [Resource identifiers](import-resources-manually.md#resource-import-identifiers-unique-ids).

1. Compose a list of the actual resources from your template and their unique identifiers in the following JSON string format.

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

   Alternatively, you can specify the JSON-formatted parameters in a configuration file.

   For example, to import `ServiceTable` and `GamesTable`, you might create a *ResourcesToImport.txt* file that contains the following configuration.

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

1. To create a change set, use the following **create-change-set** command and replace the placeholder text. For the `--change-set-type` option, specify a value of **IMPORT**. For the `--resources-to-import` option, replace the sample JSON string with the actual JSON string you just created.

   ```
   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"}}]'
   ```
**Note**  
`--resources-to-import` doesn't support inline YAML. The requirements for escaping quotes in the JSON string vary depending on your terminal. For more information, see [Using quotation marks inside strings](https://docs.aws.amazon.com/cli/latest/userguide/cli-usage-parameters-quoting-strings.html#cli-usage-parameters-quoting-strings-containing) in the *AWS Command Line Interface User Guide*.

   Alternatively, you can use a file URL as input for the `--resources-to-import` option, as shown in the following example.

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

1. Review the change set to make sure the correct resources will be imported.

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

1. To initiate the change set and import the resources, use the following **execute-change-set** command and replace the placeholder text. On successful completion of the operation `(IMPORT_COMPLETE)`, the resources are successfully imported.

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

1. (Optional) Run drift detection on the `IMPORT_COMPLETE` stack to make sure the template and actual configuration of the imported resources match. For more information on detecting drift, see [Detect drift on individual stack resources](detect-drift-resource.md).

   1. Run drift detection on the specified stack.

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

      If successful, this command returns the following sample output.

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

   1. View the progress of a drift detection operation for the specified stack drift detection ID.

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

   1. View drift information for the resources that have been checked for drift in the specified stack.

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

1. (Optional) If your imported resources don't match their expected template configurations, either correct the template configurations or update the resources directly. In this walkthrough, we correct the template configurations to match their actual configurations.

   1. [Revert the import operation](resource-import-revert.md#resource-import-revert-cli) for the affected resources.

   1. Add the import targets to your template again, making sure that the template configurations match the actual configurations.

   1. Repeat steps 3 – 6 using the modified template to import the resources again.

# Importing existing resources into a stack
<a name="resource-import-existing-stack"></a>

This topic shows you how to import existing AWS resources into an existing stack by describing them in a template. To instead scan for existing resources and automatically generate a template that you can use to import existing resources into CloudFormation or replicate resources in a new account, see [Generate templates from existing resources with IaC generator](generate-IaC.md).

**Prerequisites**

Before you begin, you must have the following:
+ A template that describes the entire stack, including both the resources that are already part of the stack and the resources to import. Save the template locally or in an Amazon S3 bucket. 

  **To get a copy of a running stack's template**

  1. Open the CloudFormation console at [https://console.aws.amazon.com/cloudformation/](https://console.aws.amazon.com/cloudformation/).

  1. From the list of stacks, choose the stack you want to retrieve the template from.

  1. In the stack details pane, choose the **Template** tab, and then choose **Copy to clipboard**.

  1. Paste the code into a text editor to begin adding other resources to the template.
+ For each resource you want to import, include the following:
  + the properties and property values that define the resource's current configuration.
  + the unique identifier for the resource, such as the resource name. For more information, see [Resource identifiers](import-resources-manually.md#resource-import-identifiers-unique-ids).
  + the [DeletionPolicy attribute](https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/aws-attribute-deletionpolicy.html).

**Topics**
+ [Example template](#resource-import-existing-stack-example-template)
+ [Import an existing resource into a stack using the AWS Management Console](#resource-import-existing-stack-console)
+ [Import an existing resource into a stack using the AWS CLI](#resource-import-existing-stack-cli)

## Example template
<a name="resource-import-existing-stack-example-template"></a>

In this walkthrough, we assume you're using the following example template, called `TemplateToImport.json`, that specifies two DynamoDB tables. `ServiceTable` is currently part of the stack, and `GamesTable` is the table you want to import.

**Note**  
This template is meant as an example only. To use it for your own testing purposes, replace the sample resources with resources from your account. 

```
{
    "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
                }
            }
        }
    }
}
```

## Import an existing resource into a stack using the AWS Management Console
<a name="resource-import-existing-stack-console"></a>

**Note**  
The CloudFormation console doesn't support the use of the intrinsic function `Fn::Transform` when importing resources. You can use the AWS CLI to import resources that use the `Fn::Transform` function.

1. Sign in to the AWS Management Console and open the CloudFormation console at [https://console.aws.amazon.com/cloudformation](https://console.aws.amazon.com/cloudformation/).

1. On the **Stacks** page, choose the stack you want to import resources into.

1. Choose **Stack actions**, and then choose **Import resources into stack**.  
![\[The Import resources into stack option in the console.\]](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/images/stack-actions-import.png)

1. Review the **Import overview** page, and then choose **Next**.

1. On the **Specify template** page, provide your updated template using one of the following methods, and then choose **Next**.
   + Choose **Amazon S3 URL**, and then specify the URL for your template in the text box.
   + Choose **Upload a template file**, and then browse for your template.

1. On the **Identify resources** page, identify each target resource. For more information, see [Resource identifiers](import-resources-manually.md#resource-import-identifiers-unique-ids).

   1. Under **Identifier property**, choose the type of resource identifier. For example, the `AWS::DynamoDB::Table` resource can be identified using the `TableName` property.

   1. Under **Identifier value**, type the actual property value. For example, the `TableName` for the `GamesTable` resource in the example template is `Games`.

   1. Choose **Next**.

1. On the **Specify stack details** page, update any parameters, and then choose **Next**. This automatically creates a change set.
**Note**  
The import operation fails if you modify existing parameters that initiate a create, update, or delete operation.

1. On the **Review *stack-name*** page, review the resources to import, and then choose **Import resources**. This automatically executes the change set created in the last step. Any stack-level tags are applied to imported resources at this time. For more information, see [Configure stack options](cfn-console-create-stack.md#configure-stack-options).

   The **Events** page for the stack displays.  
![\[The Events tab in the console.\]](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/images/import-events.png)

1. (Optional) Run drift detection on the stack to make sure the template and actual configuration of the imported resources match. For more information about detecting drift, see [Detect drift on an entire CloudFormation stack](detect-drift-stack.md).

1. (Optional) If your imported resources don't match their expected template configurations, either correct the template configurations or update the resources directly. For more information about importing drifted resources, see [Resolve drift with an import operation](resource-import-resolve-drift.md).

## Import an existing resource into a stack using the AWS CLI
<a name="resource-import-existing-stack-cli"></a>

1. To learn which properties identify each resource type in the template, run the **get-template-summary** command, specifying the S3 URL of the template. For example, the `AWS::DynamoDB::Table` resource can be identified using the `TableName` property. For the `GamesTable` resource in the example template, the value of `TableName` is `Games`. You'll need this information in the next step.

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

   For more information, see [Resource identifiers](import-resources-manually.md#resource-import-identifiers-unique-ids).

1. Compose a list of actual resources to import and their unique identifiers in the following JSON string format.

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

   Alternatively, you can specify the JSON-formatted parameters in a configuration file. 

   For example, to import `GamesTable` , you might create a *ResourcesToImport.txt* file that contains the following configuration.

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

1. To create a change set, use the following **create-change-set** command and replace the placeholder text. For the `--change-set-type` option, specify a value of **IMPORT**. For the `--resources-to-import` option, replace the sample JSON string with the actual JSON string you just created.

   ```
   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"}}]'
   ```
**Note**  
`--resources-to-import` doesn't support inline YAML. The requirements for escaping quotes in the JSON string vary depending on your terminal. For more information, see [Using quotation marks inside strings](https://docs.aws.amazon.com/cli/latest/userguide/cli-usage-parameters-quoting-strings.html#cli-usage-parameters-quoting-strings-containing) in the *AWS Command Line Interface User Guide*.

   Alternatively, you can use a file URL as input for the `--resources-to-import` option, as shown in the following example.

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

1. Review the change set to make sure the correct resources will be imported.

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

1. To initiate the change set and import the resources, use the following **execute-change-set** command and replace the placeholder text. Any stack-level tags are applied to imported resources at this time. For more information, see [Configure stack options](cfn-console-create-stack.md#configure-stack-options). On successful completion of the operation `(IMPORT_COMPLETE)`, the resources are successfully imported.

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

1. (Optional) Run drift detection on the `IMPORT_COMPLETE` stack to make sure the template and actual configuration of the imported resources match. For more information about detecting drift, see [Detect drift on an entire CloudFormation stack](detect-drift-stack.md).

   1. Run drift detection on the specified stack.

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

      If successful, this command returns the following sample output.

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

   1. View the progress of a drift detection operation for the specified stack drift detection ID.

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

   1. View drift information for the resources that have been checked for drift in the specified stack.

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

1. (Optional) If your imported resources don't match their expected template configurations, either correct the template configurations or update the resources directly. For more information about importing drifted resources, see [Resolve drift with an import operation](resource-import-resolve-drift.md).

# Moving resources between stacks
<a name="refactor-stacks"></a>

Using the `resource import` feature, you can move resources between, or *refactor*, stacks. You need to first add a `Retain` deletion policy to the resource you want to move to ensure that the resource is preserved when you remove it from the source stack and import it to the target stack.

If you're new to importing, we recommend that you first review the introductory information in the [Import AWS resources into a CloudFormation stack](import-resources.md) topic.

**Important**  
Not all resources support import operations. See [Resources that support import operations](resource-import-supported-resources.md) before you remove a resource from your stack. If you remove a resource that doesn't support import operations from your stack, you can't import the resource into another stack or bring it back into the source stack.

## Refactor a stack using the AWS Management Console
<a name="refactor-stacks-console"></a>

1. In the source template, specify a `Retain` [DeletionPolicy](https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/aws-attribute-deletionpolicy.html) for the resource you want to move.

   In the following example source template, `Games` is the target of this refactor.  
**Example JSON**  

   ```
   {
       "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
                   }
               }
           }
       }
   }
   ```

1. Open the CloudFormation console to perform a stack update to apply the deletion policy.

   1. On the **Stacks** page, with the stack selected, choose **Update**.

   1. Under **Prepare template**, choose **Replace current template**.

   1. Under **Specify template**, provide the updated source template with the `DeletionPolicy` attribute on `GamesTable`, and then choose **Next**.
      + Choose **Amazon S3 URL**, and then specify the URL to the updated source template in the text box.
      + Choose **Upload a template file**, and then browse for the updated source template file.

   1. On the **Specify stack details** page, no changes are required. Choose **Next**.

   1. On the **Configure stack options** page, no changes are required. Choose **Next**.

   1. On the **Review *SourceStackName*** page, review your changes. If your template contains IAM resources, select **I acknowledge that this template may create IAM resources** to specify that you want to use IAM resources in the template. For more information about using IAM resources in templates, see [Control CloudFormation access with AWS Identity and Access Management](control-access-with-iam.md). Then, either update your source stack by creating a change set or update your source stack directly.

1. Remove the resource, related parameters, and outputs from the source template, and then add them to the target template.

   The source template now looks like the following.  
**Example JSON**  

   ```
   {
       "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
                 }
              }
           }
       }
   }
   ```

   The following example target template currently has the `PlayersTable` resource, and now also contains `GamesTable`.  
**Example JSON**  

   ```
   {
       "AWSTemplateFormatVersion": "2010-09-09",
       "Description": "Import test",
       "Resources": {
           "PlayersTable": {
               "Type": "AWS::DynamoDB::Table",
               "Properties": {
                   "TableName": "Players",
                   "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
                   }
               }
           }
       }
   }
   ```

1. Repeat steps 2 – 3 to update the source stack again, this time to delete the target resource from the stack.

1. Perform an import operation to add `GamesTable` to the target stack.

   1. On the **Stacks** page, with the parent stack selected, choose **Stack actions**, and then choose **Import resources into stack**.  
![\[The Import resources into stack option in the console.\]](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/images/stack-actions-import.png)

   1. Read the **Import overview** page for a list of things you're required to provide during this operation. Then, choose **Next**.

   1. On the **Specify template** page, complete one of the following, and then choose **Next**.
      + Choose **Amazon S3 URL**, and then specify a URL in the text box.
      + Choose **Upload a template file**, and then browse for a file to upload.

   1. On the **Identify resources** page, identify the resource you're moving (in this example, `GamesTable`). For more information, see [Resource identifiers](import-resources-manually.md#resource-import-identifiers-unique-ids).

      1. Under **Identifier property**, choose the type of resource identifier. For example, an `AWS::DynamoDB::Table` resource can be identified using the `TableName` property.

      1. Under **Identifier value**, type the actual property value. For example, `GamesTables`. 

      1. Choose **Next**.

   1. On the **Specify stack details** page, modify any parameters, and then choose **Next**. This automatically creates a change set.
**Important**  
The import operation fails if you modify existing parameters that initiate a create, update, or delete operation.

   1. On the **Review *TargetStackName*** page, confirm that the correct resource is being imported, and then choose **Import resources**. This automatically initiates the change set created in the last step. Any [stack-level tags](cfn-console-create-stack.md#configure-stack-options) are applied to imported resources at this time.

   1. The **Events** pane of the **Stack details** page for your parent stack displays.  
![\[The Events tab in the console.\]](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/images/import-events.png)
**Note**  
It's not necessary to run drift detection on the parent stack after this import operation because the `AWS::CloudFormation::Stack` resource is already managed by CloudFormation.

## Refactor a stack using the AWS CLI
<a name="refactor-stacks-cli"></a>

1. In the source template, specify a `Retain` [DeletionPolicy](https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/aws-attribute-deletionpolicy.html) for the resource you want to move.

   In the following example source template, `GamesTable` is the target of this refactor.  
**Example JSON**  

   ```
   {
       "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
                   }
               }
           }
       }
   }
   ```

1. Update the source stack to apply the deletion policy to the resource.

   ```
   aws cloudformation update-stack --stack-name SourceStackName
   ```

1. Remove the resource, related parameters, and outputs from the source template, and then add them to the target template.

   The source template now looks like the following.  
**Example JSON**  

   ```
   {
       "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
                 }
              }
           }
       }
   }
   ```

   The following example target template currently has the `PlayersTable` resource, and now also contains `GamesTable`.  
**Example JSON**  

   ```
   {
       "AWSTemplateFormatVersion": "2010-09-09",
       "Description": "Import test",
       "Resources": {
           "PlayersTable": {
               "Type": "AWS::DynamoDB::Table",
               "Properties": {
                   "TableName": "Players",
                   "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
                   }
               }
           }
       }
   }
   ```

1. Update the source stack to delete the `GamesTable` resource and its related parameters and outputs from the stack.

   ```
   aws cloudformation update-stack --stack-name SourceStackName
   ```

1. Compose a list of actual resources to import and their unique identifiers in the following JSON string format. For more information, see [Resource identifiers](import-resources-manually.md#resource-import-identifiers-unique-ids).

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

   Alternatively, you can specify the JSON-formatted parameters in a configuration file. 

   For example, to import `GamesTable`, you might create a *ResourcesToImport.txt* file that contains the following configuration.

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

1. To create a change set, use the following **create-change-set** command and replace the placeholder text. For the `--change-set-type` option, specify a value of **IMPORT**. For the `--resources-to-import` option, replace the sample JSON string with the actual JSON string you just created.

   ```
   aws cloudformation create-change-set \
       --stack-name TargetStackName --change-set-name ImportChangeSet \
       --change-set-type IMPORT \
       --template-body file://TemplateToImport.json \
       --resources-to-import "'[{"ResourceType":"AWS::DynamoDB::Table","LogicalResourceId":"GamesTable","ResourceIdentifier":{"TableName":"Games"}}]'"
   ```
**Note**  
`--resources-to-import` doesn't support inline YAML. The requirements for escaping quotes in the JSON string vary depending on your terminal. For more information, see [Using quotation marks inside strings](https://docs.aws.amazon.com/cli/latest/userguide/cli-usage-parameters-quoting-strings.html#cli-usage-parameters-quoting-strings-containing) in the *AWS Command Line Interface User Guide*.

   Alternatively, you can use a file URL as input for the `--resources-to-import` option, as shown in the following example.

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

1. Review the change set to make sure the correct resource is being imported into the target stack.

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

1. To initiate the change set and import the resource, use the following **execute-change-set** command and replace the placeholder text. Any stack-level tags are applied to imported resources at this time. On successful completion of the operation `(IMPORT_COMPLETE)`, the resource is successfully imported.

   ```
   aws cloudformation execute-change-set \
       --change-set-name ImportChangeSet --stack-name TargetStackName
   ```
**Note**  
It's not necessary to run drift detection on the target stack after this import operation because the resource is already managed by CloudFormation.

# Nesting an existing stack
<a name="resource-import-nested-stacks"></a>

Use the `resource import` feature to nest an existing stack within another existing stack. Nested stacks are common components that you declare and reference from within other templates. That way, you can avoid copying and pasting the same configurations into your templates and simplify stack updates. If you have a template for a common component, you can use the `AWS::CloudFormation::Stack` resource to reference this template from within another template. For more information on nested stacks, see [Split a template into reusable pieces using nested stacks](using-cfn-nested-stacks.md).

CloudFormation only supports one level of nesting using `resource import`. This means that you can't import a stack into a child stack or import a stack that has children.

If you're new to importing, we recommend that you first review the introductory information in the [Import AWS resources into a CloudFormation stack manually](import-resources-manually.md) topic.

## Nested stack import validation
<a name="resource-import-nested-stacks-validation"></a>

During a nested stack import operation, CloudFormation performs the following validations.
+ The nested `AWS::CloudFormation::Stack` definition in the parent stack template matches the actual nested stack's template.
+ The tags for the nested `AWS::CloudFormation::Stack` definition in the parent stack template match the tags for the actual nested stack resource.

## Nest an existing stack using the AWS Management Console
<a name="resource-import-nested-stacks-console"></a>

1. Add the `AWS::CloudFormation::Stack` resource to the parent stack template with a `Retain` [DeletionPolicy](https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/aws-attribute-deletionpolicy.html). In the following example parent stack template, `MyNestedStack` is the target of the import.

   **JSON**

   ```
   {
     "AWSTemplateFormatVersion" : "2010-09-09",
     "Resources" : {
       "ServiceTable":{
              "Type":"AWS::DynamoDB::Table",
              "Properties":{
                 "TableName":"Service",
                 "AttributeDefinitions":[
                    {
                       "AttributeName":"key",
                       "AttributeType":"S"
                    }
                 ],
                 "KeySchema":[
                    {
                       "AttributeName":"key",
                       "KeyType":"HASH"
                    }
                 ],
                 "ProvisionedThroughput":{
                    "ReadCapacityUnits":5,
                    "WriteCapacityUnits":1
                 }
              }
           },
       "MyNestedStack" : {
         "Type" : "AWS::CloudFormation::Stack",
         "DeletionPolicy": "Retain",
         "Properties" : {
         "TemplateURL" : "https://s3.amazonaws.com/cloudformation-templates-us-east-2/EC2ChooseAMI.template",
           "Parameters" : {
             "InstanceType" : "t1.micro",
             "KeyName" : "mykey"
           }
         }
       }
     }
   }
   ```

   **YAML**

   ```
   AWSTemplateFormatVersion: 2010-09-09
   Resources:
     ServiceTable:
       Type: AWS::DynamoDB::Table
       Properties:
         TableName: Service
         AttributeDefinitions:
           - AttributeName: key
             AttributeType: S
         KeySchema:
           - AttributeName: key
             KeyType: HASH
         ProvisionedThroughput:
           ReadCapacityUnits: 5
           WriteCapacityUnits: 1
     MyNestedStack:
       Type: AWS::CloudFormation::Stack
       DeletionPolicy: Retain
       Properties:
         TemplateURL: >-
           https://s3.amazonaws.com/cloudformation-templates-us-east-2/EC2ChooseAMI.template
         Parameters:
           InstanceType: t1.micro
           KeyName: mykey
   ```

1. Open the CloudFormation console.

1. On the **Stacks** page, with the parent stack selected, choose **Stack actions**, and then choose **Import resources into stack**.  
![\[The Import resources into stack option in the console.\]](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/images/stack-actions-import.png)

1. Read the **Import overview** page for a list of things you're required to provide during this operation. Then, choose **Next**.

1. On the **Specify template** page, provide the updated parent template using one of the following methods, and then choose **Next**.
   + Choose **Amazon S3 URL**, and then specify the URL for your template in the text box.
   + Choose **Upload a template file**, and then browse for your template.

1. On the **Identify resources** page, identify the `AWS::CloudFormation::Stack` resource.

   1. Under **Identifier property**, choose the type of resource identifier. For example, an `AWS::CloudFormation::Stack` resource can be identified using the `StackId` property.

   1. Under **Identifier value**, type the ARN of the stack you're importing. For example, `arn:aws:cloudformation:us-west-2:12345678910:stack/mystack/5b918d10-cd98-11ea-90d5-0a9cd3354c10`.  
![\[The Identify resources page in the console.\]](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/images/resource-import-stackid.png)

   1. Choose **Next**.

1. On the **Specify stack details** page, modify any parameters, and then choose **Next**. This automatically creates a change set.
**Important**  
The import operation fails if you modify existing parameters that initiate a create, update, or delete operation.

1. On the **Review *MyParentStack*** page, confirm that the correct resource is being imported, and then choose **Import resources**. This automatically executes the change set created in the last step. Any stack-level tags are applied to imported resources at this time.

1. The **Events** pane of the **Stack details** page for your parent stack displays.  
![\[The Events tab in the console.\]](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/images/import-events.png)
**Note**  
It's not necessary to run drift detection on the parent stack after this import operation because the `AWS::CloudFormation::Stack` resource was already managed by CloudFormation.

## Nest an existing stack using the AWS CLI
<a name="resource-import-nested-stacks-cli"></a>

1. Add the `AWS::CloudFormation::Stack` resource to the parent stack template with a `Retain` [DeletionPolicy](https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/aws-attribute-deletionpolicy.html). In the following example parent template, `MyNestedStack` is the target of the import.

   **JSON**

   ```
   {
     "AWSTemplateFormatVersion" : "2010-09-09",
     "Resources" : {
       "ServiceTable":{
              "Type":"AWS::DynamoDB::Table",
              "Properties":{
                 "TableName":"Service",
                 "AttributeDefinitions":[
                    {
                       "AttributeName":"key",
                       "AttributeType":"S"
                    }
                 ],
                 "KeySchema":[
                    {
                       "AttributeName":"key",
                       "KeyType":"HASH"
                    }
                 ],
                 "ProvisionedThroughput":{
                    "ReadCapacityUnits":5,
                    "WriteCapacityUnits":1
                 }
              }
           },
       "MyNestedStack" : {
         "Type" : "AWS::CloudFormation::Stack",
         "DeletionPolicy": "Retain",
         "Properties" : {
         "TemplateURL" : "https://s3.amazonaws.com/cloudformation-templates-us-east-2/EC2ChooseAMI.template",
           "Parameters" : {
             "InstanceType" : "t1.micro",
             "KeyName" : "mykey"
           }
         }
       }
     }
   }
   ```

   **YAML**

   ```
   AWSTemplateFormatVersion: 2010-09-09
   Resources:
     ServiceTable:
       Type: AWS::DynamoDB::Table
       Properties:
         TableName: Service
         AttributeDefinitions:
           - AttributeName: key
             AttributeType: S
         KeySchema:
           - AttributeName: key
             KeyType: HASH
         ProvisionedThroughput:
           ReadCapacityUnits: 5
           WriteCapacityUnits: 1
     MyNestedStack:
       Type: AWS::CloudFormation::Stack
       DeletionPolicy: Retain
       Properties:
         TemplateURL: >-
           https://s3.amazonaws.com/cloudformation-templates-us-east-2/EC2ChooseAMI.template
         Parameters:
           InstanceType: t1.micro
           KeyName: mykey
   ```

1. Compose a JSON string as shown in the following example, with these modifications: 
   + Replace *MyNestedStack* with the logical ID of the target resource as specified in the template.
   + Replace *arn:aws:cloudformation:us-west-2:12345678910:stack/mystack/5b918d10-cd98-11ea-90d5-0a9cd3354c10* with the ARN of the stack you want to import.

   ```
   [{"ResourceType":"AWS::CloudFormation::Stack","LogicalResourceId":"MyNestedStack","ResourceIdentifier":{"StackId":"arn:aws:cloudformation:us-east-2:123456789012:stack/mystack/5b918d10-cd98-11ea-90d5-0a9cd3354c10"}}]
   ```

   Alternatively, you can specify the parameters in a configuration file. 

   For example, to import `MyNestedStack`, you might create a *ResourcesToImport.txt* file that contains the following configuration.

   **JSON**

   ```
   [
     {
         "ResourceType":"AWS::CloudFormation::Stack",
         "LogicalResourceId":"MyNestedStack",
         "ResourceIdentifier": {
           "StackId":"arn:aws:cloudformation:us-west-2:12345678910:stack/mystack/5b918d10-cd98-11ea-90d5-0a9cd3354c10"
         }
     }
   ]
   ```

   **YAML**

   ```
   ResourceType: AWS::CloudFormation::Stack
     LogicalResourceId: MyNestedStack
     ResourceIdentifier:
       StackId: >-
         arn:aws:cloudformation:us-west-2:12345678910:stack/mystack/5b918d10-cd98-11ea-90d5-0a9cd3354c10
   ```

1. To create a change set, use the following **create-change-set** command and replace the placeholder text. For the `--change-set-type` option, specify a value of **IMPORT**. For the `--resources-to-import` option, replace the sample JSON string with the actual JSON string you just created.

   ```
   aws cloudformation create-change-set \
       --stack-name MyParentStack --change-set-name ImportChangeSet \
       --change-set-type IMPORT \
       --template-body file://TemplateToImport.json \
       --resources-to-import '[{"ResourceType":"AWS::CloudFormation::Stack","LogicalResourceId":"MyNestedStack","ResourceIdentifier":{"StackId":"arn:aws:cloudformation:us-west-2:12345678910:stack/mystack/5b918d10-cd98-11ea-90d5-0a9cd3354c10"}}]'
   ```
**Note**  
`--resources-to-import` doesn't support inline YAML. The requirements for escaping quotes in the JSON string vary depending on your terminal. For more information, see [Using quotation marks inside strings](https://docs.aws.amazon.com/cli/latest/userguide/cli-usage-parameters-quoting-strings.html#cli-usage-parameters-quoting-strings-containing) in the *AWS Command Line Interface User Guide*.

   Alternatively, you can use a file URL as input for the `--resources-to-import` option, as shown in the following example.

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

   If successful, this command returns the following sample output.

   ```
   {
       "Id": "arn:aws:cloudformation:us-west-2:12345678910:changeSet/ImportChangeSet/8ad75b3f-665f-46f6-a200-0b4727a9442e",
       "StackId": "arn:aws:cloudformation:us-west-2:12345678910:stack/MyParentStack/4e345b70-1281-11ef-b027-027366d8e82b"
   }
   ```

1. Review the change set to make sure the correct stack is being imported.

   ```
   aws cloudformation describe-change-set --change-set-name ImportChangeSet
   ```

1. To initiate the change set and import the stack into the source parent stack, use the following **execute-change-set** command and replace the placeholder text. Any [stack-level tags](cfn-console-create-stack.md#configure-stack-options) are applied to imported resources at this time. On successful completion of the import operation `(IMPORT_COMPLETE)`, the stack is successfully nested.

   ```
   aws cloudformation execute-change-set --change-set-name ImportChangeSet
   ```
**Note**  
It's not necessary to run drift detection on the parent stack after this import operation because the `AWS::CloudFormation::Stack` resource is already managed by CloudFormation.

# Import AWS resources into a CloudFormation stack automatically
<a name="import-resources-automatically"></a>

You can now import *named resources* automatically when creating or updating CloudFormation stacks. A *named resource* is one with a custom name. For more information, see [Name type](https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/aws-properties-name.html) in the *CloudFormation Template Reference*.

When you initiate auto-import, CloudFormation checks for existing resources that match your template and imports them during deployment. For nested stacks, create the change set from the root stack.

After the import is complete and before performing subsequent stack operations, we recommend running drift detection on imported resources. Drift detection ensures that the template configuration matches the actual configuration. For more information, see [Detect drift on an entire CloudFormation stack](detect-drift-stack.md).

To import a resource, they need to meet the following requirements:
+ The resource must have a static custom name defined in your template. Dynamic names (using \$1Ref or other functions) are not currently supported.
+ The resource must have a `DeletionPolicy` of `Retain` or `RetainExceptOnCreate`.
+ The resource must not already belong to another CloudFormation stack.
+ The resource type must support CloudFormation import operations. For more information, see [Resource type support](resource-import-supported-resources.md).
+ The primary ID for the resource type must be in the template. Primary IDs with read only properties aren't supported. To find out what the primary ID is for a type, look for the `primaryIdentifier` property in the resource schema. For more information on the property, see [primaryIdentifier](https://docs.aws.amazon.com/cloudformation-cli/latest/userguide/resource-type-schema.html#schema-properties-primaryidentifier).

**Example auto-import**  
The following example uses a change set, `CreateChangeSet` to create a stack called `my-stack` based on a template file, `template.yaml`, and imports matching resources automatically.  

```
aws cloudformation create-change-set \
  --stack-name my-stack \
  --change-set-name CreateChangeSet \
  --change-set-type CREATE \
  --template-body file://template.yaml \
  --import-existing-resources
```

## Troubleshooting
<a name="auto-import-troubleshooting"></a>

If auto-import fails, do the following to troubleshoot:
+ Verify the resource name in your template matches the name of the resource exactly
+ Verify that the resource isn't already managed by another stack
+ Make sure the resource type supports import operations
+ Verify your template includes all the required properties for the resource type

# Reverting an import operation
<a name="resource-import-revert"></a>

To revert an import operation, specify a `Retain` deletion policy for the resource you want to remove from the template to ensure that it's preserved when you delete it from the stack.

## Revert an import operation using the AWS Management Console
<a name="resource-import-revert-console"></a>

1. Specify a `Retain` [DeletionPolicy](https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/aws-attribute-deletionpolicy.html) for the resources you want to remove from your stack. In the following example template, `GamesTable` is the target of this revert operation.  
**Example JSON**  

   ```
   {
       "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
                   }
               }
           }
       }
   }
   ```

1. Open the CloudFormation console to perform a stack update to apply the deletion policy.

   1. On the **Stacks** page, with the stack selected, choose **Update**, and then choose **Update stack (standard)**.

   1. Under **Prepare template**, choose **Replace current template**.

   1. Under **Specify template**, provide the updated source template with the `DeletionPolicy` attribute on `GamesTable`, and then choose **Next**.
      + Choose **Amazon S3 URL**, and then specify the URL to the updated source template in the text box.
      + Choose **Upload a template file**, and then browse for the updated source template file.

   1. On the **Specify stack details** page, no changes are required. Choose **Next**.

   1. On the **Configure stack options** page, no changes are required. Choose **Next**.

   1. On the **Review *MyStack*** page, review your changes. If your template contains IAM resources, select **I acknowledge that this template may create IAM resources** to specify that you want to use IAM resources in the template. For more information, see [Acknowledging IAM resources in CloudFormation templates](control-access-with-iam.md#using-iam-capabilities). Then, either update your source stack by creating a change set or update your source stack directly.

1. Remove the resource, related parameters, and outputs from the stack template. In this example, the template now looks like the following.  
**Example JSON**  

   ```
   {
       "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
                 }
              }
           }
       }
   }
   ```

1. Repeat step 2 to delete the resource (`GamesTable`) and its related parameters and outputs from the stack.

## Revert an import operation using the AWS CLI
<a name="resource-import-revert-cli"></a>

1. Specify a `Retain` [DeletionPolicy](https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/aws-attribute-deletionpolicy.html) for the resources you want to remove from your stack. In the following example template, `GamesTable` is the target of this revert operation.  
**Example JSON**  

   ```
   {
       "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
                   }
               }
           }
       }
   }
   ```

1. Update the stack to apply the deletion policy to the resource.

   ```
   aws cloudformation update-stack --stack-name MyStack
   ```

1. Remove the resource, related parameters, and outputs from the stack template. In this example, the template now looks like the following.  
**Example JSON**  

   ```
   {
       "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
                 }
              }
           }
       }
   }
   ```

1. Update the stack to delete the resource (`GamesTable`) and its related parameters and outputs from the stack.

   ```
   aws cloudformation update-stack --stack-name MyStack
   ```