

# Managing stacks across accounts and Regions with StackSets
<a name="what-is-cfnstacksets"></a>

CloudFormation StackSets extends the capability of stacks by allowing you to create, update, or delete stacks across multiple accounts and AWS Regions with a single operation. Using an administrator account, you define and manage a CloudFormation template, and use the template as the basis for provisioning stacks into selected target accounts across specified AWS Regions.

![\[A StackSet is a collection of resources in a template, that's deployed across multiple accounts and regions.\]](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/images/stack_set_conceptual_sv.png)


This section helps you get started using StackSets, and answers common questions about how to work with and troubleshoot StackSet creation, updates, and deletion.

**Topics**
+ [StackSets concepts](stacksets-concepts.md)
+ [Prerequisites for using CloudFormation StackSets](stacksets-prereqs.md)
+ [Get started with StackSets using a sample template](stacksets-getting-started.md)
+ [Create CloudFormation StackSets with self-managed permissions](stacksets-getting-started-create-self-managed.md)
+ [Create CloudFormation StackSets with service-managed permissions](stacksets-orgs-associate-stackset-with-org.md)
+ [Enable or disable automatic deployments for StackSets in AWS Organizations](stacksets-orgs-manage-auto-deployment.md)
+ [Update CloudFormation StackSets](stacksets-update.md)
+ [Add stacks to CloudFormation StackSets](stackinstances-create.md)
+ [Override parameter values on stacks within your CloudFormation StackSet](stackinstances-override.md)
+ [Delete stacks from CloudFormation StackSets](stackinstances-delete.md)
+ [Delete CloudFormation StackSets](stacksets-delete.md)
+ [Prevent failed StackSets deployments using target account gates](stacksets-account-gating.md)
+ [Choose the Concurrency Mode for CloudFormation StackSets](concurrency-mode.md)
+ [Performing drift detection on CloudFormation StackSets](stacksets-drift.md)
+ [Import stacks into CloudFormation StackSets](stacksets-import.md)
+ [Best practices for using CloudFormation StackSets](stacksets-bestpractices.md)
+ [CloudFormation StackSets sample templates](stacksets-sampletemplates.md)
+ [Troubleshooting CloudFormation StackSets](stacksets-troubleshooting.md)

# StackSets concepts
<a name="stacksets-concepts"></a>

The following terminology and concepts are central to your understanding and use of StackSets.

**Topics**
+ [Administrator and target accounts](#stacksets-concepts-accts)
+ [CloudFormation StackSets](#stacksets-concepts-stackset)
+ [Permission models for StackSets](#stacksets-concepts-stackset-permission-models)
+ [Stack instances](#stacksets-concepts-stackinstances)
+ [StackSet operations](#stacksets-concepts-ops)
+ [StackSet operation options](#stackset-ops-options)
+ [Tags](#stackset-concepts-tags)
+ [StackSets status codes](#stackset-status-codes)
+ [Stack instance status codes](#stack-instance-status-codes)

## Administrator and target accounts
<a name="stacksets-concepts-accts"></a>

An *administrator account* is the AWS account in which you create StackSets. For StackSets with service-managed permissions, the administrator account is either the organization's management account or a delegated administrator account. You can manage a StackSet by signing in to the AWS administrator account that created the StackSet.

A *target account* is the account into which you create, update, or delete one or more stacks in your StackSet. Before you can use a StackSet to create stacks in a target account, set up a trust relationship between the administrator and target accounts.

## CloudFormation StackSets
<a name="stacksets-concepts-stackset"></a>

A *StackSet* serves as a container for multiple stacks that are deployed across specified AWS accounts and Regions. Each stack is based on the same CloudFormation template, but you can customize individual stacks using parameters.

After you've defined a StackSet, you can create, update, or delete stacks in the target accounts and AWS Regions you specify. When you create, update, or delete stacks, you can also specify operation preferences. For example, include the order of Regions you want to perform the operation, the failure tolerance threshold before stack operations stop, and the number of accounts performing stack operations concurrently.

A StackSet is a regional resource. If you create a StackSet in one AWS Region, you can only see or change it when viewing that Region.

## Permission models for StackSets
<a name="stacksets-concepts-stackset-permission-models"></a>

You can create StackSets using either *self-managed* permissions or *service-managed* permissions.

With *self-managed* permissions, you create the IAM roles required by StackSets to deploy across accounts and Regions. These roles are necessary to establish a trusted relationship between the account you're administering the StackSet from and the account you're deploying stack instances to. Using this permissions model, StackSets can deploy to any AWS account in which you have permissions to create an IAM role.

With *service-managed* permissions, you can deploy stack instances to accounts managed by AWS Organizations. Using this permissions model, you don't have to create the necessary IAM roles; StackSets creates the IAM roles on your behalf. With this model, you can also turn on automatic deployments to accounts that you add to your organization in the future.

AWS Organizations integrates with CloudFormation and helps you centrally manage and govern your environment as you scale and grow your AWS resources.
+ Management account – the account that you use to create the organization. For more information, see [Terminology and concepts for AWS Organizations](https://docs.aws.amazon.com/organizations/latest/userguide/orgs_getting-started_concepts.html).
+ Delegated administrator – a compatible AWS service can register an AWS member account in the organization as an administrator for the organization's accounts in that service. For more information, see [AWS services that you can use with AWS Organizations](https://docs.aws.amazon.com/organizations/latest/userguide/orgs_integrate_services_list.html).

For more information about creating and managing StackSets with service-managed permissions, see the following topics:
+ [Activate trusted access for StackSets with AWS Organizations](stacksets-orgs-activate-trusted-access.md)
+ [Register a delegated administrator member account](stacksets-orgs-delegated-admin.md)
+ [Create CloudFormation StackSets with service-managed permissions](stacksets-orgs-associate-stackset-with-org.md)

## Stack instances
<a name="stacksets-concepts-stackinstances"></a>

A *stack instance* is a reference to a stack in a target account within a Region. A stack instance can exist without a stack. For example, if the stack couldn't be created for some reason, the stack instance shows the reason for stack creation failure. A stack instance associates with only one StackSet.

The following figure shows the logical relationships between StackSets, stack operations, and stacks. When you update a StackSet, *all* associated stack instances update throughout all accounts and Regions.

![\[A StackSet can create, update, or delete stacks instances and stacks across accounts and Regions.\]](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/images/stack_sets_operations_stacks_sv.png)


## StackSet operations
<a name="stacksets-concepts-ops"></a>

You can perform the following operations on StackSets.

Create StackSet  
Creating a new StackSet includes specifying a CloudFormation template that you want to use to create stacks, specifying the target accounts in which you want to create stacks, and identifying the AWS Regions in which you want to deploy stacks in your target accounts. A StackSet ensures consistent deployment of the same stack resources, with the same settings, to all specified target accounts within the Regions you choose.

Update StackSet  
When you update a StackSet, you push changes out to stacks in your StackSet. You can update a StackSet in one of the following ways. Your template updates always affect all stacks; you can't selectively update the template for some stacks in the StackSet, but not others.  
+ Change existing settings in the template or add new resources, such as updating parameter settings for a specific service, or adding new Amazon EC2 instances.
+ Replace the template with a different template.
+ Add stacks in existing or additional target accounts, across existing or additional Regions.

Delete stacks  
When you delete stacks, you are removing a stack and all its associated resources from the target accounts you specify, within the Regions you specify. You can delete stacks in the following ways.  
+ Delete stacks from some target accounts, while leaving other stacks in other target accounts running.
+ Delete stacks from some Regions, while leaving stacks in other Regions running.
+ Delete stacks from your StackSet, but save them so they continue to run independently of your StackSet by choosing the **Retain Stacks** option. You can then manage retained stacks outside of your StackSet in CloudFormation.
+ Delete all stacks in your StackSet, in preparation for deleting your entire StackSet.

Delete StackSet  
You can delete your StackSet only when there are no stack instances in it.

## StackSet operation options
<a name="stackset-ops-options"></a>

The options described in this section help to control the time and number of failures allowed to perform successful StackSet operations, and prevent you from losing stack resources.

Maximum concurrent accounts  
This setting, available in create, update, and delete workflows, lets you specify the maximum number or percentage of target accounts in which an operation performs at one time. A lower number or percentage means that an operation performs in fewer target accounts at one time. Operations perform in one Region at a time, in the order specified in the **Deployment order ** box. For example, if you are deploying stacks to 10 target accounts within two Regions, setting **Maximum concurrent accounts** to **50** and **By percentage** deploys stacks to five accounts in the first Region, then the second five accounts within the first Region, before moving on to the next Region and beginning deployment to the first five target accounts.  
When you choose **By percentage**, if the specified percentage doesn't represent a whole number of your specified accounts, CloudFormation rounds down. For example, if you are deploying stacks to 10 target accounts, and you set **Maximum concurrent accounts** to **25** and **By percentage**, CloudFormation rounds down from deploying 2.5 stacks concurrently (which would not be possible) to deploying two stacks concurrently.  
Note that this setting lets you specify the *maximum* for operations. For large deployments, under certain circumstances the actual number of accounts acted upon concurrently may be lower due to service throttling.  
**Maximum concurrent accounts** can depend on the value of **Failure tolerance** depending on your **Concurrency Mode**. If your **Concurrency Mode** is set to **Strict Failure Tolerance** then **Maximum concurrent accounts** can be at most one more than the **Failure tolerance** setting.

Concurrency mode  
This setting, available in create, update, and delete workflows, lets you choose how the concurrency level behaves during StackSet operations. For more information, see [Choose the Concurrency Mode for CloudFormation StackSets](concurrency-mode.md).

Failure tolerance  
This setting, available in create, update, and delete workflows, lets you specify the maximum number or percentage of stack operation failures that can occur, per Region, beyond which CloudFormation stops an operation automatically. A lower number or percentage means that the operation performs on fewer stacks, but you are able to start troubleshooting failed operations faster. For example, if you are updating 10 stacks in 10 target accounts within three Regions, setting **Failure tolerance** to **20** and **By percentage** means that a maximum of two stack updates in a Region can fail for the operation to continue. If a third stack in the same Region fails, CloudFormation stops the operation. If a stack can't update in the first Region, the update operation continues in that Region, and then moves on to the next Region. If two stacks can't update in the second Region, the failure tolerance reaches 20%; if a third stack in the Region fails, CloudFormation stops the update operation, and doesn't go on to subsequent Regions.  
When you choose **By percentage**, if the specified percentage doesn't represent a whole number of your stacks within each Region, CloudFormation rounds down. For example, if you are deploying stacks to 10 target accounts in three Regions, and you set **Failure tolerance** to **25** and **By percentage**, CloudFormation rounds down from a failure tolerance of 2.5 stacks (which would not be possible) to a failure tolerance of two stacks per Region.

Retain stacks  
This setting, available in delete stack workflows, lets you keep stacks and their resources running even after removing stacks from a StackSet. When you retain stacks, CloudFormation leaves stacks in individual accounts and Regions intact. Stacks disassociate from the StackSet, but saves the stack and its resources. After a delete stacks operation is complete, you manage retained stacks in CloudFormation, in the target account (not the administrator account) that created the stacks. 

Region concurrency  
This setting, available in create, update, and delete workflows, lets you choose how StackSets deploy into Regions.  
*Sequential* – Deploy StackSets operation into one Region at a time as specified by Region **Deployment order** box as long as a Region's deployment failures don't exceed a specified failure tolerance. Sequential deployment is the default selection.  
*Parallel* – Deploy StackSets operations into all specified Regions simultaneously as long as a Region's deployment failures don't exceed a specified failure tolerance.

## Tags
<a name="stackset-concepts-tags"></a>

You can add tags during StackSet creation and update operations by specifying key and value pairs. Tags are useful for sorting and filtering StackSet resources for billing and cost allocation. For more information about how to use tags in AWS, see [Organizing and tracking costs using AWS cost allocation tags](https://docs.aws.amazon.com/awsaccountbilling/latest/aboutv2/cost-alloc-tags.html) in the *AWS Billing and Cost Management User Guide*. After you specify the key-value pair, choose **\$1** to save the tag. You can delete tags that you are no longer using by choosing the red **X** to the right of a tag.

Tags that you apply to StackSets apply to all stacks, and to the resources that your stacks create. You can also add tags at the stack-only level in CloudFormation, but those tags might not show up in StackSets.

Although StackSets doesn't add any system-defined tags, you shouldn't start the key names of any tags with the string `aws:`.

## StackSets status codes
<a name="stackset-status-codes"></a>

CloudFormation StackSets generates status codes for StackSet operations.

The following table describes status codes for StackSet operations.

`RUNNING`  
The operation is currently in progress.

`SUCCEEDED`  
The operation finished without exceeding the failure tolerance for the operation.

`FAILED`  
The number of stacks on which the operation couldn't complete exceeded the user-defined failure tolerance. The failure tolerance value you've set for an operation applies for each Region during stack creation and update operations. If the number of failed stacks within a Region exceeds the failure tolerance, the status of the operation in the Region changes to `FAILED`. The status of the operation as a whole is also set to `FAILED`, and CloudFormation cancels the operation in any remaining Regions.

`QUEUED`  
[`Service-managed permissions`] For automatic deployments that require a sequence of operations, the operation enters into a queue to perform. For example:  
+ Moving an account from one organizational unit (OU), `OU1`, to another, `OU2`, triggers an automatic deployment. StackSets runs a delete operation to remove the stack instance from the target `OU1` account in the target Region and queues a create operation to add a stack instance to the target `OU2` account in the target Region.
+ Adding an account `AccountA` to an OU triggers an automatic deployment. StackSets runs a create operation to add a stack instance to `AccountA` in the target Region. If you add another account `AccountB` to the OU while this create operation is running, StackSets queues a second create operation. When the first create operation is complete, StackSets runs the second create operation to add a stack instance to `AccountB` in the target Region.

`STOPPING`  
The operation is in the process of stopping, at the user's request.

`STOPPED`  
The operation has stopped, at the user's request.

## Stack instance status codes
<a name="stack-instance-status-codes"></a>

CloudFormation StackSets generates status codes for stack instances.

The following table describes status codes for stack instances within StackSets.

`CURRENT`  
The stack is up to date with the StackSet.

`OUTDATED`  
The stack isn't up to date with the StackSet for one of the following reasons.  
+ A [https://docs.aws.amazon.com/AWSCloudFormation/latest/APIReference/API_CreateStackSet.html](https://docs.aws.amazon.com/AWSCloudFormation/latest/APIReference/API_CreateStackSet.html) or [https://docs.aws.amazon.com/AWSCloudFormation/latest/APIReference/API_UpdateStackSet.html](https://docs.aws.amazon.com/AWSCloudFormation/latest/APIReference/API_UpdateStackSet.html) operation on the associated stack failed.
+ The stack was part of a [https://docs.aws.amazon.com/AWSCloudFormation/latest/APIReference/API_CreateStackSet.html](https://docs.aws.amazon.com/AWSCloudFormation/latest/APIReference/API_CreateStackSet.html) or [https://docs.aws.amazon.com/AWSCloudFormation/latest/APIReference/API_UpdateStackSet.html](https://docs.aws.amazon.com/AWSCloudFormation/latest/APIReference/API_UpdateStackSet.html) operation that failed, or stopped before creating or updating the stack.

`INOPERABLE`  
A [https://docs.aws.amazon.com/AWSCloudFormation/latest/APIReference/API_DeleteStackInstances.html](https://docs.aws.amazon.com/AWSCloudFormation/latest/APIReference/API_DeleteStackInstances.html) operation has failed and left the stack in an unstable state. Stacks in this state are excluded from further [https://docs.aws.amazon.com/AWSCloudFormation/latest/APIReference/API_UpdateStackSet.html](https://docs.aws.amazon.com/AWSCloudFormation/latest/APIReference/API_UpdateStackSet.html) operations. You might need to perform a [https://docs.aws.amazon.com/AWSCloudFormation/latest/APIReference/API_DeleteStackInstances.html](https://docs.aws.amazon.com/AWSCloudFormation/latest/APIReference/API_DeleteStackInstances.html) operation, with `RetainStacks` set to `true`, to delete the stack instance, and then delete the stack manually.

`CANCELLED`  
The operation in the specified account and Region has been canceled. This happens because a user has stopped the StackSet operation, or because the StackSet operations exceed the failure tolerance.

`FAILED`  
The operation in the specified account and Region failed. If the StackSet operation fails in enough accounts within a Region, the failure tolerance for the StackSet operation as a whole might be exceeded.

`FAILED_IMPORT`  
The import of the stack instance in the specified account and Region failed and left the stack in an unstable state. Once the issues causing the failure are fixed, the import operation can be retried. If enough StackSet operations fail in enough accounts within a Region, the failure tolerance for the StackSet operation as a whole might be exceeded.

`PENDING`  
The operation in the specified account and Region has yet to start.

`RUNNING`  
The operation in the specified account and Region is currently in progress.

`SKIPPED_SUSPENDED_ACCOUNT`  
The operation in the specified account and Region has been skipped because the account was suspended at the time of the operation.

`SUCCEEDED`  
The operation in the specified account and Region completed successfully.

# Prerequisites for using CloudFormation StackSets
<a name="stacksets-prereqs"></a>

StackSets extend the functionality of stacks, so you can create, update, or delete stacks across multiple accounts and Regions with a single operation.

Because StackSets perform stack operations across multiple accounts, before you can create your first StackSet you need the necessary permissions defined in your AWS accounts.

You can manage StackSets using *self-managed* or *service-managed* permissions. 
+ For *self-managed* StackSets, you must create and manage IAM roles in each target account and AWS Region. For more information, see [Grant self-managed permissions](stacksets-prereqs-self-managed.md).
+ For *service-managed* StackSets, you don't need to manually create and manage IAM roles in each account; AWS handles the role creation and permissions for you. For more information, see [Activate trusted access](stacksets-orgs-activate-trusted-access.md).

**Topics**
+ [Prepare to perform StackSet operations in AWS Regions that are disabled by default](stacksets-opt-in-regions.md)
+ [Grant self-managed permissions](stacksets-prereqs-self-managed.md)
+ [Activate trusted access for StackSets with AWS Organizations](stacksets-orgs-activate-trusted-access.md)

# Prepare to perform StackSet operations in AWS Regions that are disabled by default
<a name="stacksets-opt-in-regions"></a>

AWS Regions introduced after March 20, 2019, such as Asia Pacific (Hong Kong), are disabled by default. You must enable these Regions for your account(s) before you can use them. For more information, see [Enable or disable AWS Regions in your account](https://docs.aws.amazon.com/accounts/latest/reference/manage-acct-regions.html) in the *AWS Account Management Reference Guide*.

To create a StackSet from a StackSet's administrator account (if using self-managed permissions) or organization's management account (if using service-managed permissions) in a Region that is disabled by default, you must first enable that Region for the administrator or management account.

For CloudFormation to successfully create or update a stack instance:
+ The target account must reside in a Region that's currently enabled for that target account.
+ The StackSet's administrator account or organization's management account must have the same Region enabled as the target account.

**Important**  
Be aware that during StackSet operations, administrator and target accounts exchange metadata regarding the accounts themselves, in addition to the StackSet and StackSet instances involved.  
In addition, if you disable a Region that contains an account in which StackSet instances reside, you are responsible for deleting any such instances or resources, if desired. In addition, be aware that metadata regarding the target account in the disabled Region will be retained in the administrator account.

# Grant self-managed permissions
<a name="stacksets-prereqs-self-managed"></a>

This topic provides instructions on how to create the IAM service roles required by StackSets to deploy across accounts and AWS Regions with *self-managed* permissions. These roles are necessary to establish a trusted relationship between the account you're administering the StackSet from and the account you're deploying stack instances to. Using this permissions model, StackSets can deploy to any AWS account in which you have permissions to create an IAM role. 

To use *service-managed* permissions, see [Activate trusted access](stacksets-orgs-activate-trusted-access.md) instead.

**Topics**
+ [Self-managed permissions overview](#prereqs-self-managed-permissions)
+ [Give all users of the administrator account permissions to manage stacks in all target accounts](#stacksets-prereqs-accountsetup)
+ [Set up advanced permissions options for StackSet operations](#stacksets-prereqs-advanced-perms)
+ [Set up global keys to mitigate confused deputy problems](#confused-deputy-mitigation)

## Self-managed permissions overview
<a name="prereqs-self-managed-permissions"></a>

Before you create a StackSet with self-managed permissions, you must have created IAM service roles in each account.

The basic steps are:

1. Determine which AWS account is the *administrator account*.

   StackSets are created in this administrator account. A *target account* is the account in which you create individual stacks that belong to a StackSet.

1. Determine how you want to structure permissions for the StackSet.

   The simplest (and most permissive) permissions configuration is where you give *all* users and groups in the administrator account the ability to create and update *all* the StackSets managed through that account. If you need finer-grained control, you can set up permissions to specify:
   + Which users and groups can perform StackSet operations in which target accounts.
   + Which resources users and groups can include in their StackSets.
   + Which StackSet operations specific users and groups can perform.

1. Create the necessary IAM service roles in your administrator and target accounts to define the permissions you want. 

   Specifically, the two required roles are:
   + **AWSCloudFormationStackSetAdministrationRole** – This role is deployed to the administrator account.
   + **AWSCloudFormationStackSetExecutionRole** – This role is deployed to all accounts where you create stack instances.

## Give all users of the administrator account permissions to manage stacks in all target accounts
<a name="stacksets-prereqs-accountsetup"></a>

This section shows you how to set up permissions to allow all users and groups of the administrator account to perform StackSet operations in all target accounts. It guides you through creating the required IAM service roles in your administrator and target accounts. Anyone in the administrator account can then create, update, or delete any stacks across any of the target accounts. 

By structuring permissions in this manner, users don't pass an administration role when creating or updating a StackSet.

![\[Any user in the administrator account can then create any StackSet in target accounts after setting up a trust relationship.\]](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/images/stacksets_perms_master_target.png)


------
#### [ Administrator account ]

In the administrator account, create an IAM role named **AWSCloudFormationStackSetAdministrationRole**. 

You can do this by creating a stack from the CloudFormation template available from [https://s3.amazonaws.com/cloudformation-stackset-sample-templates-us-east-1/AWSCloudFormationStackSetAdministrationRole.yml](https://s3.amazonaws.com/cloudformation-stackset-sample-templates-us-east-1/AWSCloudFormationStackSetAdministrationRole.yml). 

**Example permissions policy**  
The administration role created by the preceding template includes the following permissions policy.     
****  

```
{
  "Version":"2012-10-17",		 	 	 
  "Statement": [
    {
      "Action": [
        "sts:AssumeRole"
      ],
      "Resource": [
        "arn:aws:iam::*:role/AWSCloudFormationStackSetExecutionRole"
      ],
      "Effect": "Allow"
    }
  ]
}
```

**Example trust policy 1**  
The preceding template also includes the following trust policy that grants the service permission to use the administration role and the permissions attached to the role.    
****  

```
{
  "Version":"2012-10-17",		 	 	 
  "Statement": [
    {
      "Effect": "Allow",
      "Principal": {
        "Service": "cloudformation.amazonaws.com"
      },
      "Action": "sts:AssumeRole"
    }
  ]
}
```

**Example trust policy 2**  
To deploy stack instances into a target account that resides in a Region that's disabled by default, you must also include the regional service principal for that Region. Each Region that's disabled by default will have its own regional service principal.  
The following example trust policy grants the service permission to use the administration role in the Asia Pacific (Hong Kong) Region (`ap-east-1`), a Region that's disabled by default.     
****  

```
{
  "Version":"2012-10-17",		 	 	 
  "Statement": [
    {
      "Effect": "Allow",
      "Principal": {
        "Service": [
            "cloudformation.amazonaws.com",
            "cloudformation.ap-east-1.amazonaws.com"
         ]
      },
      "Action": "sts:AssumeRole"
    }
  ]
}
```
For more information, see [Prepare to perform StackSet operations in AWS Regions that are disabled by default](stacksets-opt-in-regions.md). For a list of Region codes, see [Regional endpoints](https://docs.aws.amazon.com/general/latest/gr/rande.html#regional-endpoints) in the *AWS General Reference Guide*.

------
#### [ Target accounts ]

In each target account, create a service role named **AWSCloudFormationStackSetExecutionRole** that trusts the administrator account. The role must have this exact name. You can do this by creating a stack from the CloudFormation template available from [https://s3.amazonaws.com/cloudformation-stackset-sample-templates-us-east-1/AWSCloudFormationStackSetExecutionRole.yml](https://s3.amazonaws.com/cloudformation-stackset-sample-templates-us-east-1/AWSCloudFormationStackSetExecutionRole.yml). When you use this template, you are prompted to provide the account ID of the administrator account with which your target account must have a trust relationship.

**Important**  
Be aware that this template grants administrator access. After you use the template to create a target account execution role, you must scope the permissions in the policy statement to the types of resources that you are creating by using StackSets.

The target account service role requires permissions to perform any operations that are specified in your CloudFormation template. For example, if your template is creating an S3 bucket, then you need permissions to create new objects for S3. Your target account always needs full CloudFormation permissions, which include permissions to create, update, delete, and describe stacks. 

**Example permissions policy 1**  
The role created by this template enables the following policy on a target account.    
****  

```
{
  "Version":"2012-10-17",		 	 	 
  "Statement": [
    {
      "Effect": "Allow",
      "Action": "*",
      "Resource": "*"
    }
  ]
}
```

**Example permissions policy 2**  
The following example shows a policy statement with the *minimum* permissions for StackSets to work. To create stacks in target accounts that use resources from services other than CloudFormation, you must add those service actions and resources to the **AWSCloudFormationStackSetExecutionRole** policy statement for each target account.    
****  

```
{
  "Version":"2012-10-17",		 	 	 
  "Statement": [
    {
      "Effect": "Allow",
      "Action": [
         "cloudformation:*"
      ],
      "Resource": "*"
    }
  ]
}
```

**Example trust policy**  
The following trust relationship is created by the template. The administrator account's ID is shown as *admin\$1account\$1id*.    
****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Effect": "Allow",
            "Principal": {
                "AWS": "arn:aws:iam::111122223333:root"
            },
            "Action": "sts:AssumeRole"
        }
    ]
}
```
You can configure the trust relationship of an existing target account execution role to trust a specific role in the administrator account. If you delete the role in the administrator account, and create a new one to replace it, you must configure your target account trust relationships with the new administrator account role, represented by *admin\$1account\$1id* in the preceding example.

------

## Set up advanced permissions options for StackSet operations
<a name="stacksets-prereqs-advanced-perms"></a>

If you require finer-grained control over the StackSets that users and groups are creating through a single administrator account, you can use IAM roles to specify:
+ Which users and groups can perform StackSet operations in which target accounts.
+ Which resources users and groups can include in their StackSets.
+ Which StackSet operations specific users and groups can perform.

### Control which users can perform StackSet operations in specific target accounts
<a name="stacksets-prereqs-multiadmin"></a>

Use customized administration roles to control which users and groups can perform StackSet operations in which target accounts. You might want to control which users of the administrator account can perform StackSet operations in which target accounts. To do this, you create a trust relationship between each target account and a specific customized administration role, rather than creating the **AWSCloudFormationStackSetAdministrationRole** service role in the administrator account itself. You then activate specific users and groups to use the customized administration role when performing StackSet operations in a specific target account.

For example, you can create Role A and Role B within your administrator account. You can give Role A permissions to access target account 1 through account 8. You can give Role B permissions to access target account 9 through account 16.

![\[A trust relationship between a customized administration role and target accounts that allows users to create a StackSet.\]](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/images/stacksets_perms_admin_target.png)


Setting up the necessary permissions involves defining a customized administration role, creating a service role for the target account, and granting users permission to pass the customized administration role when performing StackSet operations.

In general, here's how it works once you have the necessary permissions in place: When creating a StackSet, the user must specify a customized administration role. The user must have permission to pass the role to CloudFormation. In addition, the customized administration role must have a trust relationship with the target accounts specified for the StackSet. CloudFormation creates the StackSet and associates the customized administration role with it. When updating a StackSet, the user must explicitly specify a customized administration role, even if it's the same customized administration role used with this StackSet previously. CloudFormation uses that role to update the stack, subject to the requirements above.

------
#### [ Administrator account ]

**Example permissions policy**  
For each StackSet, create a customized administration role with permissions to assume the target account execution role.   
The target account execution role name must be the same in every target account. If the role name is **AWSCloudFormationStackSetExecutionRole**, StackSets uses it automatically when creating a StackSet. If you specify a custom role name, users must provide the execution role name when creating a StackSet.  
Create an [IAM service role](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_create_for-service.html) with a custom name and the following permissions policy. In the examples below, *custom\$1execution\$1role* refers to the execution role in the target accounts.     
****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Action": [
                "sts:AssumeRole"
            ],
            "Resource": [
                "arn:aws:iam::111122223333:role/custom_execution_role"
            ],
            "Effect": "Allow"
        }
    ]
}
```
To specify multiple accounts in a single statement, separate them with commas.  

```
"Resource": [
  "arn:aws:iam::target_account_id_1:role/custom_execution_role", 
  "arn:aws:iam::target_account_id_2:role/custom_execution_role"
]
```
You can specify all target accounts by using a wildcard (\$1) instead of an account ID.  

```
"Resource": [
  "arn:aws:iam::*:role/custom_execution_role"
]
```

**Example trust policy 1**  
You must provide a trust policy for the service role to defines which IAM principals can assume the role.    
****  

```
{ 
  "Version":"2012-10-17",		 	 	  
  "Statement": [ 
    { 
      "Effect": "Allow", 
      "Principal": { 
        "Service": "cloudformation.amazonaws.com" 
      }, 
      "Action": "sts:AssumeRole" 
    } 
  ] 
}
```

**Example trust policy 2**  
To deploy stack instances into a target account that resides in a Region that's disabled by default, you must also include the regional service principal for that Region. Each Region that's disabled by default will have its own regional service principal.  
The following example trust policy grants the service permission to use the administration role in the Asia Pacific (Hong Kong) Region (`ap-east-1`), a Region that's disabled by default.     
****  

```
{
  "Version":"2012-10-17",		 	 	 
  "Statement": [
    {
      "Effect": "Allow",
      "Principal": {
        "Service": [
            "cloudformation.amazonaws.com",
            "cloudformation.ap-east-1.amazonaws.com"
         ]
      },
      "Action": "sts:AssumeRole"
    }
  ]
}
```
For more information, see [Prepare to perform StackSet operations in AWS Regions that are disabled by default](stacksets-opt-in-regions.md). For a list of Region codes, see [Regional endpoints](https://docs.aws.amazon.com/general/latest/gr/rande.html#regional-endpoints) in the *AWS General Reference Guide*.

**Example pass role policy**  
You also need an IAM permissions policy for your IAM users that allows the user to pass the customized administration role when performing StackSet operations. For more information, see [Granting a user permissions to pass a role to an AWS service](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_use_passrole.html).  
In the example below, *customized\$1admin\$1role* refers to the administration role the user needs to pass.    
****  

```
{
  "Version":"2012-10-17",		 	 	 
  "Statement": [
    {
      "Effect": "Allow",
      "Action": [
        "iam:GetRole",
        "iam:PassRole"
      ],
      "Resource": "arn:aws:iam::*:role/customized_admin_role"
    }
  ]
}
```

------
#### [ Target accounts ]

In each target account, create a service role that trusts the customized administration role you want to use with this account. 

The target account role requires permissions to perform any operations that are specified in your CloudFormation template. For example, if your template is creating an S3 bucket, then you need permissions to create new objects in S3. Your target account always needs full CloudFormation permissions, which include permissions to create, update, delete, and describe stacks.

The target account role name must be the same in every target account. If the role name is **AWSCloudFormationStackSetExecutionRole**, StackSets uses it automatically when creating a StackSet. If you specify a custom role name, users must provide the execution role name when creating a StackSet.

**Example permissions policy**  
The following example shows a policy statement with the *minimum* permissions for StackSets to work. To create stacks in target accounts that use resources from services other than CloudFormation, you must add those service actions and resources to the permissions policy.    
****  

```
{
  "Version":"2012-10-17",		 	 	 
  "Statement": [
    {
      "Effect": "Allow",
      "Action": [
        "cloudformation:*"
      ],
      "Resource": "*"
    }
  ]
}
```

**Example trust policy**  
You must provide the following trust policy when you create the role to define the trust relationship.    
****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Effect": "Allow",
            "Principal": {
                "AWS": "arn:aws:iam::111122223333:role/customized_admin_role"
            },
            "Action": "sts:AssumeRole"
        }
    ]
}
```

------

### Control the resources that users can include in specific StackSets
<a name="stacksets-prereqs-executionrole"></a>

Use customized execution roles to control which stack resources users and groups can include in their StackSets. For example, you might want to set up a group that can only include Amazon S3-related resources in the StackSets they create, while another team can only include DynamoDB resources. To do this, you create a trust relationship between the customized administration role for each group and a customized execution role for each set of resources. The customized execution role defines which stack resources can be included in StackSets. The customized administration role resides in the administrator account, while the customized execution role resides in each target account in which you want to create StackSets using the defined resources. You then activate specific users and groups to use the customized administration role when performing StackSets operations.

For example you can create customized administration roles A, B, and C in the administrator account. Users and groups with permission to use Role A can create StackSets containing the stack resources specifically listed in customized execution role X, but not those in roles Y or Z, or resource not included in any execution role.

![\[A trust relationship between a custom admin role and custom execution role in target accounts, allowing users to create a StackSet.\]](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/images/stacksets_perms_admin_execution.png)


When updating a StackSet, the user must explicitly specify a customized administration role, even if it's the same customized administration role used with this StackSet previously. CloudFormation performs the update using the customized administration role specified, so long as the user has permissions to perform operations on that StackSet.

Similarly, the user can also specify a customized execution role. If they specify a customized execution role, CloudFormation uses that role to update the stack, subject to the requirements above. If the user doesn't specify a customized execution role, CloudFormation performs the update using the customized execution role previously associated with the StackSet, so long as the user has permissions to perform operations on that StackSet.

------
#### [ Administrator account ]

Create a customized administration role in your administrator account, as detailed in [Control which users can perform StackSet operations in specific target accounts](#stacksets-prereqs-multiadmin). Include a trust relationship between the customized administration role and the customized execution roles that you want it to use.

**Example permissions policy**  
The following example is a permissions policy for both the **AWSCloudFormationStackSetExecutionRole** defined for the target account, in addition to a customized execution role.    
****  

```
{
  "Version":"2012-10-17",		 	 	 
   "Statement": [
    {
      "Sid": "Stmt1487980684000",
      "Effect": "Allow",
      "Action": [
        "sts:AssumeRole" 
      ],
      "Resource": [ 
        "arn:aws:iam::*:role/AWSCloudFormationStackSetExecutionRole",
        "arn:aws:iam::*:role/custom_execution_role" 
      ]
    } 
  ]
}
```

------
#### [ Target accounts ]

In the target accounts in which you want to create your StackSets, create a customized execution role that grants permissions to the services and resources that you want users and groups to be able to include in the StackSets.

**Example permissions policy**  
The following example provides the minimum permissions for StackSets, along with permission to create Amazon DynamoDB tables.    
****  

```
{
  "Version":"2012-10-17",		 	 	 
  "Statement": [
    {
      "Effect": "Allow",
      "Action": [
        "cloudformation:*"
      ],
      "Resource": "*"
    },
    {
      "Effect": "Allow",
      "Action": [
        "dynamoDb:createTable"
      ],
      "Resource": "*"
    }
  ]
}
```

**Example trust policy**  
You must provide the following trust policy when you create the role to define the trust relationship.    
****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Effect": "Allow",
            "Principal": {
                "AWS": "arn:aws:iam::111122223333:role/customized_admin_role"
            },
            "Action": "sts:AssumeRole"
        }
    ]
}
```

------

### Set up permissions for specific StackSet operations
<a name="stacksets-prereqs-iam-actions"></a>

In addition, you can set up permissions for which user and groups can perform specific StackSet operations, such as creating, updating, or deleting StackSets or stack instances. For more information, see [Actions, resources, and condition keys for CloudFormation](https://docs.aws.amazon.com/service-authorization/latest/reference/list_awscloudformation.html) in the *Service Authorization Reference*.

## Set up global keys to mitigate confused deputy problems
<a name="confused-deputy-mitigation"></a>

The confused deputy problem is a security issue where an entity that doesn't have permission to perform an action can coerce a more-privileged entity to perform the action. In AWS, cross-service impersonation can result in the confused deputy problem. Cross-service impersonation can occur when one service (the *calling service*) calls another service (the *called service*). The calling service can be manipulated to use its permissions to act on another customer's resources in a way it shouldn't otherwise have permission to access. To prevent this, AWS provides tools that help you protect your data for all services with service principals that have been given access to resources in your account.

We recommend using the [https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_condition-keys.html#condition-keys-sourcearn](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_condition-keys.html#condition-keys-sourcearn) and [https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_condition-keys.html#condition-keys-sourceaccount](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_condition-keys.html#condition-keys-sourceaccount) global condition context keys in resource policies to limit the permissions that CloudFormation StackSets gives another service to the resource. If you use both global condition context keys, the `aws:SourceAccount` value and the account in the `aws:SourceArn` value must use the same account ID when used in the same policy statement.

The most effective way to protect against the confused deputy problem is to use the `aws:SourceArn` global condition context key with the full ARN of the resource. If you don't know the full ARN of the resource or if you are specifying multiple resources, use the `aws:SourceArn` global context condition key with wildcards (`*`) for the unknown portions of the ARN. For example, `arn:aws:cloudformation::123456789012:*`. Whenever possible, use `aws:SourceArn`, because it's more specific. Use `aws:SourceAccount` only when you can't determine the correct ARN or ARN pattern.

When StackSets assumes the **Administration** role in your **administrator** account, StackSets populates your **administrator** account ID and StackSets Amazon Resource Name (ARN). Therefore, you can define conditions for [global keys](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_condition-keys.html#condition-keys-sourceaccount) `aws:SourceAccount` and `aws:SourceArn` in the trust relationships to prevent [confused deputy problems](https://docs.aws.amazon.com/IAM/latest/UserGuide/confused-deputy.html). The following example shows how you can use the `aws:SourceArn` and `aws:SourceAccount` global condition context keys in StackSets to prevent the confused deputy problem.

------
#### [ Administrator account ]

**Example Global keys for `aws:SourceAccount` and `aws:SourceArn`**  
When using StackSets, define the global keys `aws:SourceAccount` and `aws:SourceArn` in your **AWSCloudFormationStackSetAdministrationRole** trust policy to prevent confused deputy problems.    
****  

```
{
  "Version":"2012-10-17",		 	 	 
  "Statement": [
    {
      "Effect": "Allow",
      "Principal": {
        "Service": "cloudformation.amazonaws.com"
      },
      "Action": "sts:AssumeRole",
      "Condition": {
        "StringEquals": {
          "aws:SourceAccount": "111122223333"
        },
        "ArnLike": {
          "aws:SourceArn": "arn:aws:cloudformation:*:111122223333:stackset/*"
        }
      }
    }
  ]
}
```

**Example StackSets ARNs**  
Specify your associated StackSets ARNs for finer control.    
****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Effect": "Allow",
            "Principal": {
                "Service": "cloudformation.amazonaws.com"
            },
            "Action": "sts:AssumeRole",
            "Condition": {
                "StringEquals": {
                    "aws:SourceAccount": "111122223333",
                    "aws:SourceArn": [
                        "arn:aws:cloudformation:STACKSETS-REGION:111122223333:stackset/STACK-SET-ID-1",
                        "arn:aws:cloudformation:STACKSETS-REGION:111122223333:stackset/STACK-SET-ID-2"
                    ]
                }
            }
        }
    ]
}
```

------

# Activate trusted access for StackSets with AWS Organizations
<a name="stacksets-orgs-activate-trusted-access"></a>

This topic provides instructions on how to activate trusted access with AWS Organizations, which is required by StackSets to deploy across accounts and AWS Regions using *service-managed* permissions. To use *self-managed* permissions, see [Grant self-managed permissions](stacksets-prereqs-self-managed.md) instead.

Before you create a StackSet with service-managed permissions, you must first complete the following tasks:
+ [Enable all features](https://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_org_support-all-features.html) in AWS Organizations. With only consolidated billing features enabled, you can't create a StackSet with service-managed permissions.
+ Activate trusted access with AWS Organizations. This action allows CloudFormation to create a service-linked role in the management account. After trusted access is activated, when you create a StackSet with service-managed permissions, CloudFormation creates both the necessary service-linked role and a service role named `stacksets-exec-*` in the target (member) accounts.

  With trusted access activated, the management account and delegated administrator accounts can create and manage service-managed StackSets for their organization.

To activate trusted access, you must be an administrator user in the management account. An *administrator user* is a user with full permissions to your AWS account. For more information, [Create an administrator user](https://docs.aws.amazon.com/accounts/latest/reference/getting-started-step4.html) in the *AWS Account Management Reference Guide*. For recommendations for protecting the security of the management account, see [Best practices for the management account](https://docs.aws.amazon.com/organizations/latest/userguide/orgs_best-practices_mgmt-acct.html) in the *AWS Organizations User Guide*.

**To activate trusted access**

1. Sign in to AWS as an administrator of the management account and open the CloudFormation console at [https://console.aws.amazon.com/cloudformation](https://console.aws.amazon.com/cloudformation).

1. From the navigation pane, choose **StackSets**. If trusted access is deactivated, a banner displays that prompts you to activate trusted access.  
![\[Activate trusted access banner.\]](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/images/console-stacksets-enable-trusted-access-from-stacksets-list-new.png)

1. Choose **Activate trusted access**.

   Trusted access is successfully activated when the following banner displays.  
![\[Trusted access is successfully activated banner.\]](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/images/console-stackset-trusted-access-enabled-banner-new.png)
**Note**  
Activate Organizations Access is the same as Enable Organizations Access, and Deactivate Organizations Access is the same as Disable Organizations Access. These terms have been updated based on marketing guidelines. 

**To deactivate trusted access**  
See [CloudFormation StackSets and AWS Organizations](https://docs.aws.amazon.com/organizations/latest/userguide/services-that-can-integrate-cloudformation.html) in the *AWS Organizations User Guide*.

Before you can deactivate trusted access with AWS Organizations, you must deregister all delegated administrators. For more information, see [Register a delegated administrator](stacksets-orgs-delegated-admin.md).

**Note**  
For information about using API operations instead of the console to activate or deactivate trusted access, see:  
[https://docs.aws.amazon.com/AWSCloudFormation/latest/APIReference/API_ActivateOrganizationsAccess.html](https://docs.aws.amazon.com/AWSCloudFormation/latest/APIReference/API_ActivateOrganizationsAccess.html)
[https://docs.aws.amazon.com/AWSCloudFormation/latest/APIReference/API_DeactivateOrganizationsAccess.html](https://docs.aws.amazon.com/AWSCloudFormation/latest/APIReference/API_DeactivateOrganizationsAccess.html)
[https://docs.aws.amazon.com/AWSCloudFormation/latest/APIReference/API_DescribeOrganizationsAccess.html](https://docs.aws.amazon.com/AWSCloudFormation/latest/APIReference/API_DescribeOrganizationsAccess.html)

## Service-linked roles
<a name="stacksets-orgs-service-linked-roles"></a>

The management account uses the **AWSServiceRoleForCloudFormationStackSetsOrgAdmin** service-linked role. You can modify or delete this role only if trusted access with AWS Organizations is deactivated. 

Each target account uses a **AWSServiceRoleForCloudFormationStackSetsOrgMember** service-linked role. You can modify or delete this role only under two conditions: if trusted access with AWS Organizations is deactivated, or if the account is removed from the target organization or organizational unit (OU).

For more information, see [CloudFormation StackSets and AWS Organizations](https://docs.aws.amazon.com/organizations/latest/userguide/services-that-can-integrate-cloudformation.html) in the *AWS Organizations User Guide*.

# Register a delegated administrator member account
<a name="stacksets-orgs-delegated-admin"></a>

In addition to your organization's management account, member accounts with delegated administrator permissions can create and manage StackSets with service-managed permissions for the organization. StackSets with service-managed permissions are created in the management account, including StackSets created by delegated administrators. To be registered as a delegated administrator for your organization, your member account must be in the organization. For more information about joining an organization, see [Inviting an AWS account to join your organization](https://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_accounts_invites.html).

Your organization can have up to five registered delegated administrators at one time. Delegated administrators can choose to deploy to all accounts in your organization or specific OUs. Trusted access with AWS Organizations must be activated before delegated administrators can deploy to accounts managed by Organizations. For more information, see [Activate trusted access for StackSets with AWS Organizations](stacksets-orgs-activate-trusted-access.md).

**Important**  
Please be aware of the following:  
Delegated administrators have full permissions to deploy to accounts in your organization. The management account can't limit delegated administrator permissions to deploy to specific OUs or to perform specific StackSet operations.
Make sure your delegated administrators have `organizations:ListDelegatedAdministrators` permissions to avoid any potential errors.

You can register delegated administrators for your organization in the following Regions: US East (Ohio), US East (N. Virginia), US West (N. California), US West (Oregon), Asia Pacific (Mumbai), Asia Pacific (Seoul), Asia Pacific (Singapore), Asia Pacific (Sydney), Asia Pacific (Tokyo), Canada (Central), Europe (Frankfurt), Europe (Ireland), Europe (London), Europe (Paris), Europe (Stockholm), Israel (Tel Aviv), South America (São Paulo), AWS GovCloud (US-East), and AWS GovCloud (US-West).

You can register and deregister delegated administrators using the [CloudFormation console](https://console.aws.amazon.com/cloudformation/), [AWS CLI](https://aws.amazon.com/cli/), or [AWS SDKs](https://aws.amazon.com/developer/tools/).

## To register a delegated administrator (console)
<a name="stacksets-orgs-register-delegated-admin-console"></a>

1. Sign in to AWS as an administrator of the management account and open the CloudFormation console at [https://console.aws.amazon.com/cloudformation/](https://console.aws.amazon.com/cloudformation/).

1. From the navigation pane, choose **StackSets**.

1. Under **Delegated administrators**, choose **Register delegated administrator**.

1. In the **Register delegated administrator** dialog box, choose **Register delegated administrator**.

   The success message indicates that the member account has successfully been registered as a delegated administrator.

## To deregister a delegated administrator (console)
<a name="stacksets-orgs-deregister-delegated-admin-console"></a>

1. Sign in to AWS as an administrator of the management account and open the CloudFormation console at [https://console.aws.amazon.com/](https://console.aws.amazon.com/).

1. From the navigation pane, choose **StackSets**.

1. Under **Delegated administrators**, select the account that you want to deregister, and then choose **Deregister**.

   The success message indicates that the member account has successfully been deregistered as a delegated administrator.

   You can register this account again at any time.

## To register a delegated administrator (AWS CLI)
<a name="stacksets-orgs-register-delegated-admin-cli"></a>

1. Open the AWS CLI.

1. Run the `register-delegated-administrator` command.

   ```
   $ aws organizations register-delegated-administrator \
     --service-principal=member.org.stacksets.cloudformation.amazonaws.com \
     --account-id="memberAccountId"
   ```

1. Run the `list-delegated-administrators` command to verify that the specified member account is successfully registered as a delegated administrator.

   ```
   $ aws organizations list-delegated-administrators \
     --service-principal=member.org.stacksets.cloudformation.amazonaws.com
   ```

## To deregister a delegated administrator (AWS CLI)
<a name="stacksets-orgs-deregister-delegated-admin-cli"></a>

1. Open the AWS CLI.

1. Run the `deregister-delegated-administrator` command.

   ```
   $ aws organizations deregister-delegated-administrator \
     --service-principal=member.org.stacksets.cloudformation.amazonaws.com \
     --account-id="memberAccountId"
   ```

1. Run the `list-delegated-administrators` command to verify that the specified member account is successfully deregistered as a delegated administrator.

   ```
   $ aws organizations list-delegated-administrators \
     --service-principal=member.org.stacksets.cloudformation.amazonaws.com
   ```

   You can register this account again at any time.

# Get started with StackSets using a sample template
<a name="stacksets-getting-started"></a>

This tutorial will help you get started with StackSets using the AWS Management Console. It guides you through creating a StackSet using a sample template. You'll learn how to deploy stacks across multiple Regions, monitor StackSet operations, and view the results.

In this tutorial, you'll create a StackSet that enables AWS Config in your AWS account within the US West (Oregon) Region (`us-west-2`) and US East (N. Virginia) Region (`us-east-1`). With StackSets, you can create, update, or delete stacks across multiple accounts and Regions with a single operation, making it an ideal solution for managing infrastructure at scale. While this tutorial uses a single account for simplicity, it effectively demonstrates the multi-region capabilities of StackSets. 

The sample template is available in the following S3 bucket: [https://s3.amazonaws.com/cloudformation-stackset-sample-templates-us-east-1/EnableAWSConfig.yml](https://s3.amazonaws.com/cloudformation-stackset-sample-templates-us-east-1/EnableAWSConfig.yml).

**Note**  
StackSets is free, but you'll be charged for the AWS resources you create with it, such as AWS Config in this tutorial. For more information, see [AWS Config pricing](https://aws.amazon.com/config/pricing/).

**Topics**
+ [Prerequisites](#stacksets-tutorial-prerequisites)
+ [Create a StackSet with a sample template from the console](#stacksets-tutorial-create-stackset)
+ [Monitor StackSet creation](#stacksets-tutorial-monitor-creation)
+ [View StackSet results](#stacksets-tutorial-view-results)
+ [Update your StackSet](#stacksets-tutorial-update-stackset)
+ [Add stacks to your StackSet](#stacksets-tutorial-add-stacks)
+ [Clean up](#stacksets-tutorial-clean-up)
+ [Next steps](#stacksets-tutorial-next-steps)

## Prerequisites
<a name="stacksets-tutorial-prerequisites"></a>

Before you begin this tutorial, make sure you have completed the following prerequisites:
+ You must have set up the required IAM roles for self-managed permissions. To create a StackSet and deploy stacks within a single account, you need the following roles in your account:
  + `AWSCloudFormationStackSetAdministrationRole`
  + `AWSCloudFormationStackSetExecutionRole`

  For detailed instructions on setting up these roles, see [Grant self-managed permissions](stacksets-prereqs-self-managed.md).

## Create a StackSet with a sample template from the console
<a name="stacksets-tutorial-create-stackset"></a>

**To create a StackSet that enables AWS Config**

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

1. On the navigation bar at the top of the screen, choose the AWS Region that you want to manage the StackSet from.

   You can choose any Region that supports StackSets. The Region you select doesn't affect which Regions you can deploy to with your StackSet.

1. From the navigation pane, choose **StackSets**.

1. From the top of the **StackSets** page, choose **Create StackSet**.

1. Under **Permissions**, choose **Self-service permissions** and choose the IAM roles you created in the prerequisites.
   + For IAM admin role, choose **AWSCloudFormationStackSetAdministrationRole**.
   + For IAM execution role name, choose **AWSCloudFormationStackSetExecutionRole**. 

1. Under **Prerequisite - Prepare template**, choose **Use a sample template**.

1. Under **Select a sample template**, choose the **Enable AWS Config** template. Then, choose **Next**.

   This template creates the necessary resources to enable AWS Config in your account, including a configuration recorder and delivery channel.

1. On the **Specify StackSet details** page, for **StackSet name**, enter **my-awsconfig-stackset**.

1. For **StackSet description**, enter **A StackSet that enables Config across multiple Regions**.

1. Under **Parameters**, configure the AWS Config settings as follows:

   1. For **Support all resource types**, keep the default value, **true**, to record all supported resource types.

   1. For **Include global resource types**, keep the default value, **false**, to exclude global resources like IAM roles.

   1. Leave **List of resource types if not all supported** set to **<All>**.

   1. For **The region containing the Config service-linked role resource**, replace **<DeployToAnyRegion>** with **us-west-2**.

      This means that the service-linked role named `AWSServiceRoleForConfig` will only be created if a stack is deployed to the US West (Oregon) Region. You'll choose the deployment Regions later in this procedure.

   1. For **Configuration recorder recording frequency**, choose **DAILY** recording.

1. Choose **Next** to continue.

1. On the **Configure StackSet options** page, choose **Add new tag** and add a tag by specifying a key and value pair:

   1. For **Key**, enter **Stage**.

   1. For **Value**, enter **Test**.

   Tags that you apply to StackSets are applied to resources that are created by your stacks.

1. For **Execution configuration**, choose **Active** to enable CloudFormation's optimized operation handling:
   + Non-conflicting operations run concurrently for faster deployment times.
   + Conflicting operations are automatically queued and processed in the order they were requested.

   While operations are running or queued, CloudFormation queues all incoming operations even if they're non-conflicting. You can't change execution settings during this time.

1. Choose **Next**.

1. On the **Set deployment options** page, for **Add stacks to StackSet**, choose **Deploy new stacks**.

1. For **Accounts**, choose **Deploy stacks in accounts**.

1. In the text box, enter your AWS account ID.

1. For **Specify regions**, select the following Regions in this order:

   1. US West (Oregon) Region (`us-west-2`)

   1. US East (N. Virginia) Region (`us-east-1`)

   Use the up arrow next to US West (Oregon) Region to move it to be the first entry in the list if needed. The order of the Regions determines their deployment order.

1. For **Deployment options**, configure the following settings:

   1. For **Maximum concurrent accounts**, keep the defaults of **Number** and **1**.

      For multi-account deployments, this setting means that CloudFormation deploys your stack in only one account at a time.

   1. For **Failure tolerance**, keep the defaults of **Number** and **0**.

      This means that a maximum of zero stack deployments can fail in one of your specified Regions before CloudFormation stops deployment in the current Region and cancels deployments in remaining Regions.

   1. For **Region concurrency**, choose **Sequential** (default).

      This setting ensures that CloudFormation completes deployments in one Region before moving to the next.

   1. For **Concurrency mode**, keep the default of **Strict failure tolerance**.

      For multi-account deployments, this reduces the account concurrency level when failures occur, staying within **Failure tolerance** \$11.

1. Choose **Next**.

1. On the **Review** page, review your choices. To make changes, choose **Edit** on the related section.

1. When you are ready to create your StackSet, choose **Submit**.

## Monitor StackSet creation
<a name="stacksets-tutorial-monitor-creation"></a>

After you choose **Submit**, CloudFormation begins creating your StackSet and deploying stacks to the specified Regions in your account. The StackSet details page opens automatically, where you can monitor the progress of the operation.

**To monitor the StackSet creation**

1. On the StackSet details page, the **Operations** tab is displayed by default, showing the current operation in progress.

1. The operation status should be `RUNNING` initially. CloudFormation creates stacks in the Regions you specified according to the deployment options you configured.

1. To see more details about the operation, select the operation ID in the list.

1. On the operation details page, you can view the status of stack instances being created in each Region.

1. Wait for the operation status to change to `SUCCEEDED`, which indicates that the StackSet and all its stack instances were created successfully.

## View StackSet results
<a name="stacksets-tutorial-view-results"></a>

After the StackSet creation is complete, you can view the deployed stack instances and verify that AWS Config has been enabled in your account across the specified Regions.

**To view the StackSet results**

1. On the StackSet details page, choose the **Stack instances** tab.

1. You should see a list of stack instances that were created in your account across the specified Regions. Each stack instance should have a status of `SUCCEEDED`, indicating that it was successfully deployed.

1. To verify that AWS Config is enabled in your account, you can check the AWS Config console in each of the deployed Regions.

## Update your StackSet
<a name="stacksets-tutorial-update-stackset"></a>

After creating your StackSet, you might want to update it to modify parameter values or add more Regions. This section shows you how to update the AWS Config recording frequency parameter.

**To update your StackSet**

1. On the **StackSets** page, select your **my-awsconfig-stackset**.

1. With the StackSet selected, choose **Edit StackSet details** from the **Actions** menu.

1. On the **Choose a template** page, for **Prerequisite - Prepare template**, choose **Use current template**.

1. Choose **Next**.

1. On the **Specify StackSet details** page, under **Parameters**, find **Configuration recorder recording frequency** and change it from **DAILY** to **CONTINUOUS**.

1. Choose **Next**.

1. On the **Configure StackSet options** page, leave the settings as they are and choose **Next**.

1. On the **Set deployment options** page, specify your account ID and the same Regions that you used when creating the StackSet.

1. For **Deployment options**, keep the same settings as before.

1. Choose **Next**.

1. On the **Review** page, review your changes and choose **Submit**.

1. CloudFormation starts updating your StackSet. You can monitor the progress on the **Operations** tab of the StackSet details page.

## Add stacks to your StackSet
<a name="stacksets-tutorial-add-stacks"></a>

You can add more stacks to your StackSet by deploying to additional Regions. This section shows you how to add stacks to a new Region.

**To add stacks to your StackSet**

1. On the **StackSets** page, select your **my-awsconfig-stackset**.

1. With the StackSet selected, choose **Add stacks to StackSet** from the **Actions** menu.

1. On the **Set deployment options** page, for **Add stacks to StackSet**, choose **Deploy new stacks**.

1. For **Accounts**, choose **Deploy stacks in accounts** and enter your account ID.

1. For **Specify regions**, select a new Region, such as **Europe (Ireland)** (`eu-west-1`).

1. For **Deployment options**, keep the same settings as before.

1. Choose **Next**.

1. On the **Specify Overrides** page, leave the property values as specified and choose **Next**.

1. On the **Review** page, review your choices and choose **Submit**.

1. CloudFormation starts creating new stacks in the specified Region. You can monitor the progress on the **Operations** tab of the StackSet details page.

## Clean up
<a name="stacksets-tutorial-clean-up"></a>

To avoid incurring charges for unwanted AWS Config resources, you should clean up by deleting the stacks from your StackSet, deleting the StackSet itself, and removing the IAM roles you created for this tutorial. Since all resources are deployed within your account, cleanup is straightforward.

**To delete stacks from your StackSet**

1. On the **StackSets** page, select your **my-awsconfig-stackset**.

1. With the StackSet selected, choose **Delete stacks from StackSet** from the **Actions** menu.

1. On the **Set deployment options** page, for **Accounts**, choose **Deploy stacks in accounts** and enter your account ID.

1. For **Specify regions**, select all the Regions where you deployed stacks.

1. For **Deployment options**, keep the default settings.

1. Make sure **Retain stacks** is *not* turned on, so that the stacks and their resources are deleted.

1. Choose **Next**.

1. On the **Review** page, review your choices and choose **Submit**.

1. CloudFormation starts deleting the stacks from your StackSet. You can monitor the progress on the **Operations** tab of the StackSet details page.

**To delete your StackSet**

1. After all stacks have been deleted, on the **StackSets** page, select your **my-awsconfig-stackset**.

1. With the StackSet selected, choose **Delete StackSet** from the **Actions** menu.

1. When prompted to confirm, choose **Delete**.

**To delete the IAM service roles**

Since you deployed only to your account, you only need to delete the IAM roles from this single account, making cleanup much simpler than multi-account deployments.

1. Open the [IAM console](https://console.aws.amazon.com/iam/).

1. From the navigation pane, choose **Roles**.

1. In the search box, enter **AWSCloudFormationStackSet** to find the roles you created for this tutorial.

1. Select the checkbox next to **AWSCloudFormationStackSetAdministrationRole**.

1. Choose **Delete** from the top of the page.

1. In the confirmation dialog box, enter **delete** and choose **Delete**.

1. Repeat the same process to delete the **AWSCloudFormationStackSetExecutionRole**.

After deleting the StackSet, an Amazon S3 bucket will remain in each AWS Region due to the `DeletionPolicy` attribute on the `AWS::S3::Bucket` resource. This preserves your AWS Config history data. If you no longer need this data, you can safely delete the bucket manually. Before you can delete a bucket, you must first empty it. Emptying a bucket deletes all objects in it.

**To empty and delete the Amazon S3 buckets**

1. Open the [Amazon S3 console](https://console.aws.amazon.com/s3/).

1. In the navigation pane on the left side of the console, choose **Buckets**.

1. In the **Buckets** list, you'll see buckets created for this StackSet in each Region where you deployed. Select the option next to the name of the bucket created for this StackSet, and then choose **Empty**.

1. On the **Empty bucket** page, confirm that you want to empty the bucket by typing **permanently delete** into the text field, and then choose **Empty**.

1. Monitor the progress of the bucket emptying process on the **Empty bucket: Status** page. 

1. To return to your bucket list, choose **Exit**.

1. Select the option next to the name of the bucket, and then choose **Delete**.

1. When prompted for confirmation, type the name of the bucket and then choose **Delete bucket**.

1. Monitor the progress of the bucket deletion process from the **Buckets** list. When Amazon S3 completes the deletion of the bucket, it removes the bucket from the list.

1. Repeat this process for each bucket created by the StackSet in the different Regions.

## Next steps
<a name="stacksets-tutorial-next-steps"></a>

Congratulations\$1 You've successfully created a StackSet using a sample template, deployed stacks to multiple Regions within your account, updated the StackSet, added more stacks, and cleaned up your resources. By focusing on single-account deployment, you've simplified the cleanup process while still learning the core multi-region capabilities of StackSets.

To learn more about StackSets, explore the following topics:
+ [Override parameter values on stacks within your CloudFormation StackSet](stackinstances-override.md) – Learn how to override parameter values for specific accounts and Regions.
+ [Create CloudFormation StackSets with service-managed permissions](stacksets-orgs-associate-stackset-with-org.md) – Explore creating StackSets for multi-account deployments with AWS Organizations.

# Create CloudFormation StackSets with self-managed permissions
<a name="stacksets-getting-started-create-self-managed"></a>

This topic describes how to create StackSets with *self-managed* permissions to deploy stacks across AWS accounts and Regions. 

**Note**  
Before you continue, create the IAM service roles required by StackSets to establish a trusted relationship between the account you're administering the StackSet from and the account you're deploying stacks to. For more information, see [Grant self-managed permissions](stacksets-prereqs-self-managed.md).

**Topics**
+ [Create a StackSet with self-managed permissions (console)](#stacksets-getting-started-create-self-managed-console)
+ [Create a StackSet with self-managed permissions (AWS CLI)](#stacksets-getting-started-self-managed-cli)

## Create a StackSet with self-managed permissions (console)
<a name="stacksets-getting-started-create-self-managed-console"></a>

**To create a StackSet**

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 navigation bar at the top of the screen, choose the AWS Region that you want to manage the StackSet from.

1. From the navigation pane, choose **StackSets**.

1. From the top of the **StackSets** page, choose **Create StackSet**.

1. Under **Permissions**, choose **Self-service permissions** and choose the IAM roles you created.

1. Under **Prerequisite - Prepare template**, choose **Template is ready**.

1. Under **Specify template**, choose to either specify the URL for the S3 bucket that contains your stack template or upload a stack template file. Then, choose **Next**.

1. On the **Specify StackSet details** page, provide a name for the StackSet, specify any parameters, and then choose **Next**.

1. Choose **Next** to continue.

1. On the **Configure StackSet options** page, under **Tags**, specify any tags to apply to resources in your stack. For more information about how tags are used in AWS, see [Organizing and tracking costs using AWS cost allocation tags](https://docs.aws.amazon.com/awsaccountbilling/latest/aboutv2/cost-alloc-tags.html) in the *AWS Billing and Cost Management User Guide*.

1. For **Execution configuration**, choose **Active** to enable CloudFormation's optimized operation handling:
   + Non-conflicting operations run concurrently for faster deployment times.
   + Conflicting operations are automatically queued and processed in the order they were requested.

   While operations are running or queued, CloudFormation queues all incoming operations even if they're non-conflicting. You can't change execution settings during this time.

1. If your template contains IAM resources, for **Capabilities**, choose **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).

1. Choose **Next**.

1. On the **Set deployment options** page, for **Add stacks to StackSet**, choose **Deploy new stacks**.

1. For **Accounts**, choose **Deploy stacks in accounts**. Paste your target AWS account numbers in the text box, separating multiple numbers with commas.
**Note**  
You can include your administrator account ID if you want to deploy stacks in that account as well.

1. Under **Specify regions**, choose the Regions you want to deploy stacks in.

1. For **Deployment options**, do the following:
   + For **Maximum concurrent accounts**, specify how many accounts are processed concurrently.
   + For **Failure tolerance**, specify the maximum number of account failures allowed per Region. The operation will stop and won't proceed to other Regions once this limit is reached.
   + For **Region concurrency**, choose how to process Regions: **Sequential** (one Region at a time) or **Parallel** (multiple Regions concurrently).
   + For **Concurrency mode**, choose how concurrency behaves during operation execution.
     + **Strict failure tolerance** – Reduces account concurrency level when failures occur, staying within **Failure tolerance** \$11.
     + **Soft failure tolerance** – Maintains your specified concurrency level (the value of **Maximum concurrent accounts**) regardless of failures. 

1. Choose **Next**.

1. On the **Review** page, review your choices. To make changes, choose **Edit** on the related section.

1. When you are ready to create your StackSet, choose **Submit**.

   CloudFormation starts creating your StackSet. View the progress and status of the creation of the stacks in your StackSet in the StackSet details page that opens when you choose **Submit**.

## Create a StackSet with self-managed permissions (AWS CLI)
<a name="stacksets-getting-started-self-managed-cli"></a>

Follow the steps in this section to use the AWS CLI to:
+ Create the StackSet container.
+ Deploy stack instances.

**To create a StackSet**

1. Use the [https://docs.aws.amazon.com/cli/latest/reference/cloudformation/create-stack-set.html](https://docs.aws.amazon.com/cli/latest/reference/cloudformation/create-stack-set.html) command to create a new StackSet named `my-stackset`. The following example uses a template stored in an S3 bucket and includes a parameter that sets a `KeyPairName` with the value `TestKey`. 

   ```
   aws cloudformation create-stack-set \
     --stack-set-name my-stackset \
     --template-url https://s3.region-code.amazonaws.com/amzn-s3-demo-bucket/MyApp.template \
     --parameters ParameterKey=KeyPairName,ParameterValue=TestKey
   ```

1. After your **create-stack-set** command is finished, run the [https://docs.aws.amazon.com/cli/latest/reference/cloudformation/list-stack-sets.html](https://docs.aws.amazon.com/cli/latest/reference/cloudformation/list-stack-sets.html) command to see that your StackSet has been created. You should see your new StackSet in the results.

   ```
   aws cloudformation list-stack-sets
   ```

1. Use the [https://docs.aws.amazon.com/cli/latest/reference/cloudformation/create-stack-instances.html](https://docs.aws.amazon.com/cli/latest/reference/cloudformation/create-stack-instances.html) command to deploy stacks within your StackSet. The following example deploys stacks in two AWS accounts (`account_ID_1` and `account_ID_2`) across two Regions (`us-west-2` and `us-east-1`). 

   Set concurrent account processing and other deployment preferences using the `--operation-preferences` option. This example uses count-based settings. Note that `MaxConcurrentCount` must not exceed `FailureToleranceCount` \$1 1. For percentage-based settings, use `FailureTolerancePercentage` or `MaxConcurrentPercentage` instead. 

   ```
   aws cloudformation create-stack-instances \
     --stack-set-name my-stackset \
     --accounts account_ID_1 account_ID_2 \
     --regions us-west-2 us-east-1 \
     --operation-preferences MaxConcurrentCount=1,FailureToleranceCount=0
   ```

   For more information, see [CreateStackInstances](https://docs.aws.amazon.com/AWSCloudFormation/latest/APIReference/API_CreateStackInstances.html) in the *AWS CloudFormation API Reference*.

1. Use the [https://docs.aws.amazon.com/cli/latest/reference/cloudformation/describe-stack-set-operation.html](https://docs.aws.amazon.com/cli/latest/reference/cloudformation/describe-stack-set-operation.html) command to verify that your stacks were created successfully. For the `--operation-id` option, specify the operation ID that was returned as part of the **create-stack-instances** output.

   ```
   aws cloudformation describe-stack-set-operation \
     --stack-set-name my-stackset \
     --operation-id operation_ID
   ```

# Create CloudFormation StackSets with service-managed permissions
<a name="stacksets-orgs-associate-stackset-with-org"></a>

With *service-managed* permissions, you can deploy stacks to accounts managed by AWS Organizations in specific Regions. With this model, you don't need to create IAM roles in each target account and AWS Region. CloudFormation creates the IAM roles on your behalf. For more information, see [Activate trusted access](stacksets-orgs-activate-trusted-access.md).

**Topics**
+ [Considerations](#stacksets-orgs-considerations)
+ [Create a StackSet with service-managed permissions (console)](#stacksets-orgs-associate-stackset-with-org-console)
+ [Create a StackSet with service-managed permissions (AWS CLI)](#stacksets-orgs-associate-stackset-with-org-cli)

## Considerations
<a name="stacksets-orgs-considerations"></a>

Before you create a StackSet with service-managed permissions, consider the following:
+ StackSets with service-managed permissions can be initiated by either your organization's management account or delegated administrator accounts, but all operations are performed by the management account.
+ CloudFormation doesn't deploy stacks to the management account, even if that account is part of your organization or belongs to an organizational unit (OU).
+ Your StackSet can target your entire organization (includes all accounts) or specified OUs. When a StackSet targets a parent OU, it automatically includes any child OUs. By default, when a StackSet targets specific OUs, it includes all accounts within those OUs. However, you can target specific accounts using account filter options.
+ Multiple StackSets can target the same organization or OU.
+ Your can't target accounts outside your organization.
+ Your authorization to deploy StackSets depends on the permissions assigned to the IAM principal (user, role, or group) you use to sign in to the management account. For an example IAM policy that grants permissions to deploy to an organization, see [Restrict stack set operations based on Region and resource types](security_iam_id-based-policy-examples.md#resource-level-permissions-service-managed-stack-set).
+ Delegated administrators have full permissions to deploy to any account in your organization. The management account can't limit delegated administrator permissions to deploy to specific OUs or StackSet operations.
+ Automatic deployment settings apply at the StackSet level. You can't adjust automatic deployments selectively for OUs, accounts, or Regions.
+ StackSets that use service-managed permissions don't support nested stacks or templates that contain macros or transforms.

## Create a StackSet with service-managed permissions (console)
<a name="stacksets-orgs-associate-stackset-with-org-console"></a>

**To create a StackSet**

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 navigation bar at the top of the screen, choose the AWS Region that you want to manage the StackSet from.

1. From the navigation pane, choose **StackSets**.

1. From the top of the **StackSets** page, choose **Create StackSet**.

1. Under **Permissions**, choose **Service-managed permissions**.
**Note**  
If trusted access with AWS Organizations is disabled, a banner displays. Trusted access is required to create or update a StackSet with service-managed permissions. Only the administrator in the organization's management account has permissions to [Activate trusted access for StackSets with AWS Organizations](stacksets-orgs-activate-trusted-access.md).

1. Under **Prerequisite - Prepare template**, choose **Template is ready**.

1. Under **Specify template**, choose to either specify the URL for the S3 bucket that contains your stack template or upload a stack template file. Then, choose **Next**.

1. On the **Specify StackSet details** page, provide a name for the StackSet, specify any parameters, and then choose **Next**.

1. On the **Configure StackSet options** page, under **Tags**, specify any tags to apply to resources in your stack. For more information about how tags are used in AWS, see [Organizing and tracking costs using AWS cost allocation tags](https://docs.aws.amazon.com/awsaccountbilling/latest/aboutv2/cost-alloc-tags.html) in the *AWS Billing and Cost Management User Guide*.

1. For **Execution configuration**, choose **Active** to enable CloudFormation's optimized operation handling:
   + Non-conflicting operations run concurrently for faster deployment times.
   + Conflicting operations are automatically queued and processed in the order they were requested.

   While operations are running or queued, CloudFormation queues all incoming operations even if they're non-conflicting. You can't change execution settings during this time.

1. If your template contains IAM resources, for **Capabilities**, choose **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).

1. Choose **Next** to proceed and to activate trusted access if not already activated.

1. On the **Set deployment options** page, under **Deployment targets**, do one of the following:
   + To deploy to all accounts in your organization, choose **Deploy to organization**. 
   + To deploy to all accounts in specific OUs, choose **Deploy to organizational units (OUs)**. Choose **Add an OU**, and then paste the target OU ID in the text box. Repeat for each new target OU.

   If you chose **Deploy to organizational units (OUs)**, for **Account filter type**, you can set your deployment targets to be specific individual accounts by choosing one of the following options and providing account numbers.
   + **None** (default) – Deploy stacks to all accounts in the specified OUs.
   + **Intersection** – Deploy stacks to specific individual accounts within the selected OUs.
   + **Difference** – Deploy stacks to all accounts in the selected OUs except for specific accounts.
   + **Union** – Deploy stacks to the specified OUs plus additional individual accounts.

1. Under **Automatic deployment**, choose whether to automatically deploy to accounts that are added to the target organization or OUs in the future. For more information, see [Enable or disable automatic deployments for StackSets in AWS Organizations](stacksets-orgs-manage-auto-deployment.md).

1. If you enabled automatic deployment, under **Account removal behavior**, choose whether stack resources are retained or deleted when an account is removed from a target organization or OU.
**Note**  
With **Retain stacks** selected, stacks are removed from your StackSet, but the stacks and their associated resources are retained. The resources stay in their current state, but will no longer be part of the StackSet.

1. Under **Specify regions**, choose the Regions you want to deploy stacks in.

1. For **Deployment options**, do the following:
   + For **Maximum concurrent accounts**, specify how many accounts are processed concurrently.
   + For **Failure tolerance**, specify the maximum number of account failures allowed per Region. The operation will stop and won't proceed to other Regions once this limit is reached.
   + For **Region concurrency**, choose how to process Regions: **Sequential** (one Region at a time) or **Parallel** (multiple Regions concurrently).
   + For **Concurrency mode**, choose how concurrency behaves during operation execution.
     + **Strict failure tolerance** – Reduces account concurrency level when failures occur, staying within **Failure tolerance** \$11.
     + **Soft failure tolerance** – Maintains your specified concurrency level (the value of **Maximum concurrent accounts**) regardless of failures. 
   + For StackSet **dependencies**, add dependent StackSet ARNs, staying within 10 dependencies maximum. For more information, see [Enable or disable automatic deployments for StackSets in AWS Organizations](stacksets-orgs-manage-auto-deployment.md).

1. Choose **Next** to continue.

1. On the **Review** page, verify that your StackSet will deploy to the correct accounts in the correct Regions, and then choose **Create StackSet**.

   The **StackSet details** page opens. You can view the progress and status of the creation of the stacks in your StackSet.

## Create a StackSet with service-managed permissions (AWS CLI)
<a name="stacksets-orgs-associate-stackset-with-org-cli"></a>

Follow the steps in this section to use the AWS CLI to:
+ Create the StackSet container.
+ Deploy stack instances.

**Note**  
When acting as a delegated administrator, you must include `--call-as DELEGATED_ADMIN` in the command.

------
#### [ Deploy to your organization ]

**To create a StackSet**

1. Use the [https://docs.aws.amazon.com/cli/latest/reference/cloudformation/create-stack-set.html](https://docs.aws.amazon.com/cli/latest/reference/cloudformation/create-stack-set.html) command to create a new StackSet named `my-stackset`. The following example uses a template stored in an S3 bucket, enables automatic deployments, and preserves stacks when accounts are removed. For more information, see [Enable or disable automatic deployments for StackSets in AWS Organizations](stacksets-orgs-manage-auto-deployment.md).

   ```
   aws cloudformation create-stack-set \
     --stack-set-name my-stackset \
     --template-url https://s3.region-code.amazonaws.com/amzn-s3-demo-bucket/MyApp.template \
     --permission-model SERVICE_MANAGED \
     --auto-deployment Enabled=true,RetainStacksOnAccountRemoval=true,DependsOn=ARN1,ARN2
   ```

1. Use the [https://docs.aws.amazon.com/cli/latest/reference/cloudformation/list-stack-sets.html](https://docs.aws.amazon.com/cli/latest/reference/cloudformation/list-stack-sets.html) command to confirm that your StackSet was created. Your new StackSet is listed in the results.

   ```
   aws cloudformation list-stack-sets
   ```
   + If you set the `--call-as` option to `DELEGATED_ADMIN` while signed in to your member account, **list-stack-sets** returns all StackSets with service-managed permissions in the organization's management account.
   + If you set the `--call-as` option to `SELF` while signed in to your AWS account, **list-stack-sets** returns all self-managed StackSets in your AWS account.
   + If you set the `--call-as` option to `SELF` while signed in to the organization's management account, **list-stack-sets** returns all StackSets in the organization's management account.

1. Use the [https://docs.aws.amazon.com/cli/latest/reference/cloudformation/create-stack-instances.html](https://docs.aws.amazon.com/cli/latest/reference/cloudformation/create-stack-instances.html) command to add stacks to your StackSet. For the `--deployment-targets` option, specify the organization root ID to deploy to all accounts in your organization. 

   Set concurrent account processing and other deployment preferences using the `--operation-preferences` option. This example uses count-based settings. Note that `MaxConcurrentCount` must not exceed `FailureToleranceCount` \$1 1. For percentage-based settings, use `FailureTolerancePercentage` or `MaxConcurrentPercentage` instead. 

   ```
   aws cloudformation create-stack-instances --stack-set-name my-stackset \
     --deployment-targets OrganizationalUnitIds=r-a1b2c3d4e5 \
     --regions us-west-2 us-east-1 \
     --operation-preferences MaxConcurrentCount=1,FailureToleranceCount=0
   ```

   For more information, see [CreateStackInstances](https://docs.aws.amazon.com/AWSCloudFormation/latest/APIReference/API_CreateStackInstances.html) in the *AWS CloudFormation API Reference*.

1. Using the `operation-id` that was returned as part of the **create-stack-instances** output, use the following [https://docs.aws.amazon.com/cli/latest/reference/cloudformation/describe-stack-set-operation.html](https://docs.aws.amazon.com/cli/latest/reference/cloudformation/describe-stack-set-operation.html) command to verify that your stacks were created successfully.

   ```
   aws cloudformation describe-stack-set-operation \
     --stack-set-name my-stackset \
     --operation-id operation_ID
   ```

------
#### [ Deploy to organizational units (OUs) ]

**To create a StackSet**

1. Use the [https://docs.aws.amazon.com/cli/latest/reference/cloudformation/create-stack-set.html](https://docs.aws.amazon.com/cli/latest/reference/cloudformation/create-stack-set.html) command to create a new StackSet named `my-stackset`. The following example uses a template stored in an S3 bucket and includes a parameter that sets a `KeyPairName` with the value `TestKey`

   ```
   aws cloudformation create-stack-set \
     --stack-set-name my-stackset \
     --template-url https://s3.region-code.amazonaws.com/amzn-s3-demo-bucket/MyApp.template \
     --permission-model SERVICE_MANAGED \
     --parameters ParameterKey=KeyPairName,ParameterValue=TestKey
   ```

1. Use the [https://docs.aws.amazon.com/cli/latest/reference/cloudformation/list-stack-sets.html](https://docs.aws.amazon.com/cli/latest/reference/cloudformation/list-stack-sets.html) command to confirm that your StackSet was created. Your new StackSet is listed in the results.

   ```
   aws cloudformation list-stack-sets
   ```
   + If you set the `--call-as` option to `DELEGATED_ADMIN` while signed in to your member account, **list-stack-sets** returns all StackSets with service-managed permissions in the organization's management account.
   + If you set the `--call-as` option to `SELF` while signed in to your AWS account, **list-stack-sets** returns all self-managed StackSets in your AWS account.
   + If you set the `--call-as` option to `SELF` while signed in to the organization's management account, **list-stack-sets** returns all StackSets in the organization's management account.

1. Use the [https://docs.aws.amazon.com/cli/latest/reference/cloudformation/create-stack-instances.html](https://docs.aws.amazon.com/cli/latest/reference/cloudformation/create-stack-instances.html) command to add stacks to your StackSet. For the `--deployment-targets` option, specify the OU IDs to deploy to.

   Set concurrent account processing and other deployment preferences using the `--operation-preferences` option. This example uses count-based settings. Note that `MaxConcurrentCount` must not exceed `FailureToleranceCount` \$1 1. For percentage-based settings, use `FailureTolerancePercentage` or `MaxConcurrentPercentage` instead. 

   ```
   aws cloudformation create-stack-instances --stack-set-name my-stackset \
     --deployment-targets OrganizationalUnitIds=ou-rcuk-1x5j1lwo,ou-rcuk-slr5lh0a \
     --regions us-west-2 us-east-1 \
     --operation-preferences MaxConcurrentCount=1,FailureToleranceCount=0
   ```

   For more information, see [CreateStackInstances](https://docs.aws.amazon.com/AWSCloudFormation/latest/APIReference/API_CreateStackInstances.html) in the *AWS CloudFormation API Reference*.

1. Using the `operation-id` that was returned as part of the **create-stack-instances** output, use the following [https://docs.aws.amazon.com/cli/latest/reference/cloudformation/describe-stack-set-operation.html](https://docs.aws.amazon.com/cli/latest/reference/cloudformation/describe-stack-set-operation.html) command to verify that your stacks were created successfully.

   ```
   aws cloudformation describe-stack-set-operation \
     --stack-set-name my-stackset \
     --operation-id operation_ID
   ```

------
#### [ Deploy to specific accounts in OUs ]

You can target specific organizational units (OUs) and use account filtering to precisely control which accounts receive stack deployments. By default, stacks deploy to all accounts within specified OUs if no account filtering is specified.

In the AWS CLI, you specify account filtering with the `--deployment-targets` option. For more information, see [DeploymentTargets](https://docs.aws.amazon.com/AWSCloudFormation/latest/APIReference/API_DeploymentTargets.html).

After you create the StackSet container with the **create-stack-set** command, use one of the following examples to deploy stacks to specific accounts.

**Target specific accounts in an OU**  
The following example deploys stacks only to accounts A1 and A2 in OU1.

```
aws cloudformation create-stack-instances --stack-set-name my-stackset \
  --deployment-targets OrganizationalUnitIds=OU1,Accounts=A1,A2,AccountFilterType=INTERSECTION \
  --regions us-west-2 us-east-1
```

**Exclude accounts from an OU**  
The following example deploys stacks to all accounts in OU1 except accounts A1 and A2.

```
aws cloudformation create-stack-instances --stack-set-name my-stackset \
  --deployment-targets OrganizationalUnitIds=OU1,Accounts=A1,A2,AccountFilterType=DIFFERENCE \
  --regions us-west-2 us-east-1
```

------

# Enable or disable automatic deployments for StackSets in AWS Organizations
<a name="stacksets-orgs-manage-auto-deployment"></a>

CloudFormation can automatically deploy additional stacks to new AWS Organizations accounts when they're added to your target organization or organizational units (OUs). You can enable automatic deployments and choose whether to delete or retain stacks and their associated resources when accounts are removed from target OUs. These settings can be modified anytime for StackSets that use service-managed permissions.

## How automatic deployments work
<a name="stacksets-orgs-auto-deployment-example"></a>

When automatic deployments are enabled, they're triggered when accounts are added to a target organization or OU, removed from a target organization or OU, or moved between target OUs.

For example, consider `StackSet1` that targets `OU1` in the `us-east-1` Region and `StackSet2` that targets `OU2` in the `us-east-1` Region. `OU1` contains `AccountA`. 

If you move `AccountA` from `OU1` to `OU2` with automatic deployments enabled, CloudFormation automatically runs a delete operation to remove the `StackSet1` stack from `AccountA` and queues a create operation that adds the `StackSet2` stack to `AccountA`.

## Considerations
<a name="stacksets-orgs-auto-deployment-considerations"></a>

The following are considerations when using automatic deployments:
+ The automatic deployments feature is enabled at the StackSet level. You can't adjust automatic deployments selectively for OUs, accounts, or Regions.
+ Overridden parameter values only apply to the accounts that are currently in the target OUs and their child OUs. Accounts added to the target OUs and their child OUs in the future will use the StackSet default values and not the overridden values.
+ Automatic deployments do not consider account level targeting filters. If you target specific accounts and enable automatic deployments, your StackSet will continue to deploy to any newly added accounts within the deployed organization. To prevent deployments to newly added accounts, disable automatic deployments. 
+ Dependency management: Define up to 10 dependencies per StackSet, with up to 100 dependencies per account. For example, if you have five StackSets with five dependencies each, you have 25 dependencies counting towards the 100 dependency limit. You can request a limit increase through [service quota console](https://console.aws.amazon.com/servicequotas/home). Dependencies are removed when StackSets are deleted or Organizations are deactivated.
+ It is recommended to enable managed execution when using auto-deployments. Managed execution will allow auto-deployment operations in multiple target accounts to execute concurrently within a StackSet, increasing processing velocity, especially for larger Organizations.

## Enable or disable automatic deployments (console)
<a name="stacksets-orgs-manage-auto-deployment-console"></a>

**To enable or disable automatic deployments**

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 navigation bar at the top of the screen, choose the AWS Region you created the StackSet in.

1. From the navigation pane, choose **StackSets**.

1. On the **StackSets** page, select the option next to the name of the StackSet to update.

1. Choose **Edit automatic deployment** from the **Actions** menu in the upper right corner. 

1. From the dialog box that opens, do the following:

   1. For **Automatic deployment**, choose **Activated** or **Deactivated**.

   1. For **Account removal behavior**, choose **Delete stacks** or **Retain stacks**. Retained resources stay in their current state, but will no longer be part of the StackSet.

   1. For StackSet **dependencies**, add dependent StackSet ARNs, staying within 10 dependencies maximum.

1. Choose **Save**.

## Enable or disable automatic deployments (AWS CLI)
<a name="stacksets-orgs-manage-auto-deployment-cli"></a>

**To enable or disable automatic deployments**

1. Use the [https://docs.aws.amazon.com/cli/latest/reference/cloudformation/update-stack-set.html](https://docs.aws.amazon.com/cli/latest/reference/cloudformation/update-stack-set.html) command with the `--auto-deployment` option.

   The following command enables automatic deployments.

   ```
   aws cloudformation update-stack-set --stack-set-name my-stackset \
     --use-previous-template --auto-deployment Enabled=true,RetainStacksOnAccountRemoval=true,DependsOn=ARN1,ARN2
   ```

   Alternatively, to disable automatic deployments, specify `Enabled=false` as the value for the `--auto-deployment` option, as in the following example. 

   ```
   aws cloudformation update-stack-set --stack-set-name my-stackset \
     --use-previous-template --auto-deployment Enabled=false
   ```

1. Using the operation ID that was returned as part of the **update-stack-set** output, run [https://docs.aws.amazon.com/cli/latest/reference/cloudformation/describe-stack-set-operation.html](https://docs.aws.amazon.com/cli/latest/reference/cloudformation/describe-stack-set-operation.html) to verify that your StackSet was updated successfully.

   ```
   aws cloudformation describe-stack-set-operation --operation-id operation_ID
   ```

# Update CloudFormation StackSets
<a name="stacksets-update"></a>

You can update your StackSet using either the CloudFormation console or the AWS CLI. 

To add and remove accounts and Regions from a StackSet, see [Add stacks to StackSets](stackinstances-create.md) and [Delete stacks from StackSets](stackinstances-delete.md). To override parameter values for a stack, see [Override parameters on stacks](stackinstances-override.md). 

**Topics**
+ [Update your StackSet (console)](#stacksets-update-console)
+ [Update your StackSet (AWS CLI)](#stacksets-update-cli)

## Update your StackSet (console)
<a name="stacksets-update-console"></a>

**To update a StackSet**

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 navigation bar at the top of the screen, choose the AWS Region you created the StackSet in.

1. From the navigation pane, choose **StackSets**.

1. On the **StackSets** page, select the StackSet you want to update.

1. With the StackSet selected, choose **Edit StackSet details** from the **Actions** menu.

1. On the **Choose a template** page, update the **Permissions** section as needed, or skip to the next step.

1. For **Prerequisite - Prepare template**, choose **Use current template** to use the current template, or **Replace current template** to specify an S3 URL to another template or upload a new template.

1. Choose **Next**.

1. On the **Specify StackSet details** page, for **StackSet description**, update the description for the StackSet as needed.

1. For **Parameters**, update the parameter values as needed.

1. Choose **Next**.

1. On the **Configure StackSet options** page, for **Tags**, modify the tags as needed. You can add, update, or delete tags. For more information about how tags are used in AWS, see [Organizing and tracking costs using AWS cost allocation tags](https://docs.aws.amazon.com/awsaccountbilling/latest/aboutv2/cost-alloc-tags.html) in the *AWS Billing and Cost Management User Guide*.

1. For **Execution configuration**, you can update the execution configuration as needed. 
**Note**  
Remember, you can't change execution settings when operations are running or queued.

1. If your template contains IAM resources, for **Capabilities**, choose **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).

1. Choose **Next**.

1. On the **Set deployment options** page, provide the accounts and Regions for the update.

   CloudFormation will deploy stack updates in the specified accounts within the first Region, then moves on to the next, and so on, as long as a Region's deployment failures don't exceed a specified failure tolerance.

   1. [Self-managed permissions] For **Accounts**, **Deployment locations**, choose **Deploy stacks in accounts**. Paste the target account IDs that you used to create your StackSet in the text box, separating multiple numbers with commas. 

      [Service-managed permissions] Do one of the following:
      + Choose **Deploy to organizational units (OUs)**. Enter the target OUs that you used to create your StackSet.
      + Choose **Deploy to accounts**. Paste the target OU IDs or account IDs that you used to create your StackSet.

   1. For **Specify regions**, specify the order in which you want CloudFormation to deploy your updates.

   1. For **Deployment options**, do the following:
      + For **Maximum concurrent accounts**, specify how many accounts are processed concurrently.
      + For **Failure tolerance**, specify the maximum number of account failures allowed per Region. The operation will stop and won't proceed to other Regions once this limit is reached.
      + For **Region concurrency**, choose how to process Regions: **Sequential** (one Region at a time) or **Parallel** (multiple Regions concurrently).
      + For **Concurrency mode**, choose how concurrency behaves during operation execution.
        + **Strict failure tolerance** – Reduces account concurrency level when failures occur, staying within **Failure tolerance** \$11.
        + **Soft failure tolerance** – Maintains your specified concurrency level (the value of **Maximum concurrent accounts**) regardless of failures. 
      + [Service-managed permissions] For StackSet **dependencies**, add dependent StackSet ARNs, staying within 10 dependencies maximum. For more information, see [Enable or disable automatic deployments for StackSets in AWS Organizations](stacksets-orgs-manage-auto-deployment.md).

   1. Choose **Next** to continue.

1. On the **Review** page, review your choices. To make changes, choose **Edit** on the related section.

1. When you're ready to proceed, choose **Submit**.

   CloudFormation starts applying your updates to your StackSet, and displays the **Operations** tab of the StackSet details page. You can view the progress and status of update operations on the **Operations** tab.

## Update your StackSet (AWS CLI)
<a name="stacksets-update-cli"></a>

**Note**  
When acting as a delegated administrator, you must include `--call-as DELEGATED_ADMIN` in the command. 

1. 

**To update a StackSet**

   Use the [https://docs.aws.amazon.com/cli/latest/reference/cloudformation/update-stack-set.html](https://docs.aws.amazon.com/cli/latest/reference/cloudformation/update-stack-set.html) command to make changes to your StackSet.

   In the following examples, we're updating the StackSet by using `--parameters` option. Specifically, we change the default snapshot delivery frequency for delivery channel configuration from `TwentyFour_Hours` to `Twelve_Hours`. Because we're still using the current template, we add the `--use-previous-template` option.

   Set concurrent account processing and other deployment preferences using the `--operation-preferences` option. These examples use count-based settings. Note that `MaxConcurrentCount` must not exceed `FailureToleranceCount` \$1 1. For percentage-based settings, use `FailureTolerancePercentage` or `MaxConcurrentPercentage` instead. 

   [Self-managed permissions] For the `--accounts` option, provide the account IDs you want your update to target.

   ```
   aws cloudformation update-stack-set --stack-set-name my-stackset \
     --use-previous-template \
     --parameters ParameterKey=MaximumExecutionFrequency,ParameterValue=Twelve_Hours \
     --accounts account_ID_1 account_ID_2 \
     --regions us-west-2 us-east-1 \
     --operation-preferences MaxConcurrentCount=1,FailureToleranceCount=0
   ```

   [Service-managed permissions] For the `--deployment-targets` option, provide the organization root ID or organizational unit (OU) IDs you want your update to target.

   ```
   aws cloudformation update-stack-set --stack-set-name my-stackset \
     --use-previous-template \
     --parameters ParameterKey=MaximumExecutionFrequency,ParameterValue=Twelve_Hours \
     --deployment-targets OrganizationalUnitIds=ou-rcuk-1x5j1lwo,ou-rcuk-slr5lh0a \
     --regions us-west-2 us-east-1 \
     --operation-preferences MaxConcurrentCount=1,FailureToleranceCount=0
   ```

   For more information, see [UpdateStackSet](https://docs.aws.amazon.com/AWSCloudFormation/latest/APIReference/API_UpdateStackSet.html) in the *AWS CloudFormation API Reference*.

1. Verify that your StackSet was updated successfully by running the **describe-stack-set-operation** command to show the status and results of your update operation. For `--operation-id`, use the operation ID that was returned by your **update-stack-set** command.

   ```
   aws cloudformation describe-stack-set-operation \
     --operation-id operation_ID
   ```

# Add stacks to CloudFormation StackSets
<a name="stackinstances-create"></a>

When you create a StackSet, you can create the stacks for that StackSet. CloudFormation also enables you to add more stacks, for additional accounts and Regions, at any point after the StackSet is created. You can add stacks using either the CloudFormation console or the AWS CLI.

**Topics**
+ [Add stacks to a StackSet (console)](#stackinstances-create-console)
+ [Add stacks to a StackSet (AWS CLI)](#stackinstances-create-cli)

## Add stacks to a StackSet (console)
<a name="stackinstances-create-console"></a>

**To add stacks to a StackSet**

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 navigation bar at the top of the screen, choose the AWS Region you created the StackSet in.

1. From the navigation pane, choose **StackSets**. On the StackSets page, select the StackSet that you created.

1. With the StackSet selected, choose **Add stacks to StackSet** from the **Actions** menu.

1. On the **Set deployment options** page, do the following:

   1. For **Add stacks to StackSet**, choose **Deploy new stacks**.

   1. Next, do the following depending on your StackSet's permissions configuration:
      + [Self-managed permissions] For **Accounts**, **Deployment locations**, choose **Deploy stacks in accounts**. Paste your target account numbers in the text box, separating multiple numbers with commas.
      + [Service-managed permissions] For **Deployment targets**, do one of the following:
        + Choose **Deploy to organization** to deploy to all accounts in your organization.
        + Choose **Deploy to organizational units (OUs)** to deploy to all accounts in specific OUs. Choose **Add another OU**, and then paste the target OU ID in the text box. Repeat for each new target OU. CloudFormation also targets any child OUs of your selected targets.
**Note**  
If you add an OU that your StackSet already targets, CloudFormation creates new stacks in any accounts in the OU that don't already have stacks from your StackSet (for example, accounts that were added to the OU after your StackSet was created and with automatic deployments disabled).

   1. For **Specify regions**, specify which AWS Regions to deploy to in the target accounts you specified in the previous step. By default, CloudFormation will deploy stacks in the specified accounts within the first Region, then moves on to the next, and so on, as long as a Region's deployment failures don't exceed a specified failure tolerance.

   1. For **Deployment options**, do the following:
      + For **Maximum concurrent accounts**, specify how many accounts are processed concurrently.
      + For **Failure tolerance**, specify the maximum number of account failures allowed per Region. The operation will stop and won't proceed to other Regions once this limit is reached.
      + For **Region concurrency**, choose how to process Regions: **Sequential** (one Region at a time) or **Parallel** (multiple Regions concurrently).
      + For **Concurrency mode**, choose how concurrency behaves during operation execution.
        + **Strict failure tolerance** – Reduces account concurrency level when failures occur, staying within **Failure tolerance** \$11.
        + **Soft failure tolerance** – Maintains your specified concurrency level (the value of **Maximum concurrent accounts**) regardless of failures. 

   1. Choose **Next**.

1. On the **Specify Overrides** page, leave the property values as specified. You won't be overriding any property values for the stacks you're going to create. Choose **Next**.

1. On the **Review** page, review your choices. To make changes, choose **Edit** on the related section.

1. When you're ready to proceed, choose **Submit**.

   CloudFormation starts creating your stacks. View the progress and status of the creation of the stacks in your StackSet in the StackSet details page that opens when you choose **Submit**. When complete, your new stacks should be listed on the **Stack instances** tab.

## Add stacks to a StackSet (AWS CLI)
<a name="stackinstances-create-cli"></a>

**Note**  
When acting as a delegated administrator, you must include `--call-as DELEGATED_ADMIN` in the command. 

**To add stacks to a StackSet with self-managed permissions**  
Use the **create-stack-instances** CLI command. For the `--accounts` option, provide the accounts IDs for which you want to create stacks.

```
aws cloudformation create-stack-instances --stack-set-name my-stackset \
  --accounts account_id --regions eu-west-1 us-west-2
```

**To add stacks to a StackSet with service-managed permissions**  
Use the **create-stack-instances** CLI command. For the `--deployment-targets` option, provide the organization (root) ID or OU IDs for which you want to create stacks. For example commands that target specific accounts, see [Create a StackSet with service-managed permissions (AWS CLI)](stacksets-orgs-associate-stackset-with-org.md#stacksets-orgs-associate-stackset-with-org-cli).

```
aws cloudformation create-stack-instances --stack-set-name my-stackset \
  --deployment-targets OrganizationalUnitIds=ou-rcuk-r1qi0wl7 --regions eu-west-1 us-west-2
```

**Note**  
If you add an OU that your StackSet already targets, CloudFormation creates new stacks in any accounts in the OU that don't already have stacks from your StackSet (for example, accounts that were added to the OU after your StackSet was created and with automatic deployments disabled).

# Override parameter values on stacks within your CloudFormation StackSet
<a name="stackinstances-override"></a>

In certain cases, you might want stacks in certain Regions or accounts to have different property values than those specified in the StackSet itself. For example, you might want to specify a different value for a given parameter based on whether an account is used for development or production. For these situations, CloudFormation allows you to override parameter values in stacks by account and Region. You can override template parameter values when you first create the stacks, and you can override parameter values for existing stacks. You can only set parameters you've previously overridden in stacks back to the values specified in the StackSet.

Parameter value overrides apply to stacks in the accounts and Regions you select. During StackSet updates, any parameter values overridden for a stack aren't updated, but retain their overridden value.

You can only override parameter *values* that are specified in the StackSet; to add or delete a parameter itself, you need to update the StackSet template. If you add a parameter to a StackSet template, then before you can override that parameter value in a stack you must first update all stacks with the new parameter and value specified in the StackSet. Once all stacks have been updated with the new parameter, you can then override the parameter value in individual stacks as desired.

To learn how to override StackSet parameter values when you create stacks, see [Add stacks to StackSets](stackinstances-create.md).

**Topics**
+ [Override parameters on stacks (console)](#stackinstances-override-console)
+ [Override parameters on stacks (AWS CLI)](#stackinstances-override-cli)

## Override parameters on stacks (console)
<a name="stackinstances-override-console"></a>

**To override parameters for specific stacks**

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 navigation bar at the top of the screen, choose the AWS Region you created the StackSet in.

1. From the navigation pane, choose **StackSets**. On the StackSets page, select your StackSet.

1. With the StackSet selected, choose **Override StackSet parameters** from the **Actions** menu.

1. On the **Set deployment options** page, provide the accounts and Regions for the stacks that you'll create overrides for.

   By default, CloudFormation will deploy stacks in the specified accounts within the first Region, then moves on to the next, and so on, provided that a Region's deployment failures don't exceed a specified failure tolerance.

   1. [Self-managed permissions] For **Deployment locations**, choose **Deploy stacks in accounts**. Paste some or all the target account IDs that you used to create your StackSet.

      [Service-managed permissions] Do one of the following:
      + Choose **Deploy to organizational units (OUs)**. Enter one or more of the target OUs that you used to create your StackSet. The overridden parameter values only apply to the accounts that are currently in the target OUs and their child OUs. Accounts added to the target OUs and their child OUs in the future will use the StackSet default values and not the overridden values.
      + Choose **Deploy to accounts**. Paste some or all the target OU IDs or account IDs that you used to create your StackSet.

   1. For **Specify regions**, add one or more of the Regions into which you have deployed stacks for this StackSet.

      If you add multiple Regions, the order of the Regions under **Specify regions** determines their deployment order.

   1. For **Deployment options**, do the following:
      + For **Maximum concurrent accounts**, specify how many accounts are processed concurrently.
      + For **Failure tolerance**, specify the maximum number of account failures allowed per Region. The operation will stop and won't proceed to other Regions once this limit is reached.
      + For **Region concurrency**, choose how to process Regions: **Sequential** (one Region at a time) or **Parallel** (multiple Regions concurrently).
      + For **Concurrency mode**, choose how concurrency behaves during operation execution.
        + **Strict failure tolerance** – Reduces account concurrency level when failures occur, staying within **Failure tolerance** \$11.
        + **Soft failure tolerance** – Maintains your specified concurrency level (the value of **Maximum concurrent accounts**) regardless of failures. 

   1. Choose **Next**.

1. On the **Specify Overrides** page, select the checkboxes for the parameters to override, and then choose **Override StackSet value** from the **Edit override value** menu.

1. On the **Override StackSet parameter values** page, make your changes and then choose **Save changes**.
**Note**  
To set any overridden parameters back to using the value specified in the StackSet, check all parameters and choose **Set to StackSet value** from the **Edit override value** menu. Doing so removes all overridden values once you update the stacks.

1. On the **Review** page, review your choices. To make changes, choose **Edit** on the related section.

1. When you're ready to proceed, choose **Submit**.

   CloudFormation starts updating your stacks. View the progress and status of the stacks in the StackSet details page that opens when you choose **Submit**.

## Override parameters on stacks (AWS CLI)
<a name="stackinstances-override-cli"></a>

**Note**  
When acting as a delegated administrator, you must include `--call-as DELEGATED_ADMIN` in the command. 

**To override parameters for specific stacks**

1. Use the [https://docs.aws.amazon.com/cli/latest/reference/cloudformation/update-stack-instances.html](https://docs.aws.amazon.com/cli/latest/reference/cloudformation/update-stack-instances.html) AWS CLI command and specify the `--parameter-overrides` option.

   [Self-managed permissions] For the `--accounts` option, provide the account IDs for which you want to override parameter values on stacks.

   ```
   aws cloudformation update-stack-instances --stack-set-name my-stackset \
     --parameter-overrides ParameterKey=Subnets,ParameterValue=subnet-1baa3351\\,subnet-27b86940 \
     --accounts account_id --regions us-east-1
   ```

   [Service-managed permissions] For the `--deployment-targets` option, provide the organization root ID, OU IDs, or AWS Organizations account IDs for which you want to override parameters on stacks. In this example, we override parameter values for stacks in all accounts in the OU with the `ou-rcuk-1x5j1lwo` ID.

   The overridden parameter values only apply to the accounts that are currently in the target OU and its child OUs. Accounts added to the target OU and its child OUs in the future will use the StackSet default values and not the overridden values.

   ```
   aws cloudformation update-stack-instances --stack-set-name my-stackset \
     --parameter-overrides ParameterKey=Subnets,ParameterValue=subnet-1baa3351\\,subnet-27b86940 \
     --deployment-targets OrganizationalUnitIds=ou-rcuk-1x5j1lwo \
     --regions us-east-1
   ```

1. Verify that your parameter values were successfully overridden on stacks by running the **describe-stack-set-operation** command to show the status and results of your update operation. For `--operation-id`, use the operation ID that was returned by your **update-stack-instances** command.

   ```
   aws cloudformation describe-stack-set-operation --operation-id operation_ID
   ```

# Delete stacks from CloudFormation StackSets
<a name="stackinstances-delete"></a>

You can delete stacks from StackSets using either the CloudFormation console or the AWS CLI. 

**Topics**
+ [Delete stacks from your StackSet (console)](#stackinstances-delete-console)
+ [Delete stacks from your StackSet (AWS CLI)](#stackinstances-delete-cli)

**Note**  
Deleting stacks from a top-level organizational unit (OU) removes that OU as a StackSet target.

## Delete stacks from your StackSet (console)
<a name="stackinstances-delete-console"></a>

**To delete stacks**

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 navigation bar at the top of the screen, choose the AWS Region you created the StackSet in.

1. From the navigation pane, choose **StackSets**. On the StackSets page, select the StackSet.

1. With your StackSet selected, choose **Delete stacks from StackSet** from the **Actions** menu.

1. On the **Set deployment options** page, first choose the accounts and Regions where you want to delete the stacks.

   1. [Self-managed permissions] For **Accounts**, choose **Deploy stacks in accounts** or **Deploy stacks in organizational units**.

      If you choose **Deploy stacks in accounts**, paste your target account numbers in the **Account numbers** text box, separating multiple numbers with commas.

      If you choose **Deploy stacks in organizational units**, paste a target OU ID in the **Organization numbers** text box to target all accounts that are part of the specified organization.

   1. [Service-managed permissions] For **Organizational units (OUs)**, specify the target OU IDs. 
**Important**  
CloudFormation will delete stacks from both the specified target OUs and their child OUs.

      For **Account filter type**, you can refine which accounts will have stacks deleted by choosing one of the following options and providing account numbers. 
      + **None** (default) – Delete stacks from all accounts in the specified OUs.
      + **Intersection** – Delete stacks only from specific individual accounts within the selected OUs.
      + **Difference** – Delete stacks from all accounts in the selected OUs except for specific accounts.
      + **Union** – Delete stacks from the specified OUs plus additional individual accounts.

   1. For **Specify regions**, choose the Regions from which you want to delete stacks within the target accounts.

1. For **Deployment options**, do the following:
   + For **Maximum concurrent accounts**, specify how many accounts are processed concurrently.
   + For **Failure tolerance**, specify the maximum number of account failures allowed per Region. The operation will stop and won't proceed to other Regions once this limit is reached.
   + For **Retain stacks**, enable this option to save the stacks and their associated resources when removing them from your StackSet. The resources stay in their current state but are no longer part of the StackSet.
   + For **Region concurrency**, choose how to process Regions: **Sequential** (one Region at a time) or **Parallel** (multiple Regions concurrently).
   + For **Concurrency mode**, choose how concurrency behaves during operation execution.
     + **Strict failure tolerance** – Reduces account concurrency level when failures occur, staying within **Failure tolerance** \$11.
     + **Soft failure tolerance** – Maintains your specified concurrency level (the value of **Maximum concurrent accounts**) regardless of failures. 

1. Choose **Next**.

1. On the **Review** page, review your choices. To make changes, choose **Edit** on the related section.

1. When you are ready to remove the stacks from your StackSet, choose **Submit**.

   After stack deletion is finished, you can verify that stacks were deleted from your StackSet in the StackSet detail page, on the **Stack instances** tab.

## Delete stacks from your StackSet (AWS CLI)
<a name="stackinstances-delete-cli"></a>

**Note**  
When acting as a delegated administrator, you must include `--call-as DELEGATED_ADMIN` in the command. 

Use the **delete-stack-instances** command with your StackSet name.

In these examples, we use the `--no-retain-stacks` option because we aren't retaining any stacks. Use `--retain-stacks` instead of `--no-retain-stacks` if you want to keep the stacks and their resources. 

For `--regions`, specify the AWS Regions you want to delete stacks from, for example, `us-west-2` and `us-east-1`.

Set concurrent account processing and other preferences using the `--operation-preferences` option. These examples use count-based settings. Note that `MaxConcurrentCount` must not exceed `FailureToleranceCount` \$1 1. For percentage-based settings, use `FailureTolerancePercentage` or `MaxConcurrentPercentage` instead. 

**To delete stacks (self-managed permissions)**  
For the `--accounts` option, specify the IDs of the account to delete stacks from.

```
aws cloudformation delete-stack-instances --stack-set-name my-stackset \
  --accounts account_ID_1 account_ID_2 \
  --regions us-west-2 us-east-1 \
  --no-retain-stacks \
  --operation-preferences MaxConcurrentCount=1,FailureToleranceCount=0
```

**To delete stacks (service-managed permissions)**  
For `--deployment-targets`, specify the organization root ID or organizational unit (OU) IDs to delete stacks from.

**Important**  
CloudFormation will delete stacks from both the specified target OUs and their child OUs.

```
aws cloudformation delete-stack-instances --stack-set-name my-stackset \
  --deployment-targets OrganizationalUnitIds=ou-rcuk-1x5jlwo,ou-rcuk-slr5lh0a \ 
  --regions us-west-2 us-east-1 \
  --no-retain-stacks \
  --operation-preferences MaxConcurrentCount=1,FailureToleranceCount=0
```

For more information, see [DeleteStackInstances](https://docs.aws.amazon.com/AWSCloudFormation/latest/APIReference/API_DeleteStackInstances.html) in the *AWS CloudFormation API Reference*.

Optionally, after stack deletion is finished, verify that stacks were deleted from your StackSet by running the **describe-stack-set-operation** command to show the status and results of the delete stacks operation. For `--operation-id`, use the operation ID that was returned by your **delete-stack-instances** command.

```
aws cloudformation describe-stack-set-operation --stack-set-name my-stackset \
  --operation-id ddf16f54-ad62-4d9b-b0ab-3ed8e9example
```

# Delete CloudFormation StackSets
<a name="stacksets-delete"></a>

To delete a StackSet, you must first delete all stacks in the StackSet. For information about how to delete all stacks, see [Delete stacks from StackSets](stackinstances-delete.md).

**Topics**
+ [Delete a StackSet (console)](#stacksets-delete-set)
+ [Delete a StackSet (AWS CLI)](#stacksets-delete-set-cli)
+ [Delete service roles (optional)](#stacksets-delete-roles)

## Delete a StackSet (console)
<a name="stacksets-delete-set"></a>

**To delete a StackSet**

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 navigation bar at the top of the screen, choose the AWS Region you created the StackSet in.

1. On the **StackSets** page, select the StackSet.

1. With the StackSet selected, choose **Delete StackSet** from the **Actions** menu.

1. When you are prompted to confirm that you want to delete the StackSet, choose **Delete StackSet**.

## Delete a StackSet (AWS CLI)
<a name="stacksets-delete-set-cli"></a>

**Note**  
When acting as a delegated administrator, you must include `--call-as DELEGATED_ADMIN` in the command. 

**To delete a StackSet**

1. Use the following **delete-stack-set** command. When you are prompted to confirm, type **y**, and then press **Enter**.

   ```
   aws cloudformation delete-stack-set --stack-set-name my-stackset
   ```

1. Verify that the StackSet was deleted by running the **list-stack-sets** command. The results of the list-stack-sets command should show your stack with a status of `DELETED`.

   ```
   aws cloudformation list-stack-sets
   ```

## Delete service roles (optional)
<a name="stacksets-delete-roles"></a>

If you no longer need the IAM service roles that CloudFormation requires to perform StackSet operations, we recommend that you delete the roles.

*For self-managed StackSets*, the roles you created. For more information about these roles, see [Grant self-managed permissions](stacksets-prereqs-self-managed.md).

*For service-managed StackSets*, the roles that were automatically created for StackSets have the suffix `CloudFormationStackSetsOrgAdmin` in the organization management account, and `CloudFormationStackSetsOrgMember` in each target account. For more information, see [Service-linked roles](stacksets-orgs-activate-trusted-access.md#stacksets-orgs-service-linked-roles).

**To delete a service role (console)**

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

1. From the navigation pane, choose **Roles**, and then fill the check box next to the role that you want to delete.

1. In the **Role actions** menu at the top of the page, choose **Delete role**.

1. In the confirmation dialog box, choose **Yes, Delete**. If you are sure, you can proceed with the deletion even if the service last accessed data is still loading.

**To delete a service role (AWS CLI)**
+ Use the following **delete-role** command. When you are prompted to confirm, type **y**, and then press Enter.

  ```
  aws iam delete-role --role-name role name
  ```

For more information about deleting roles, see [Delete roles or instance profiles](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_manage_delete.html) in the *IAM User Guide*.

# Prevent failed StackSets deployments using target account gates
<a name="stacksets-account-gating"></a>

An account gate is an optional feature that helps you verify that a target account meets certain requirements before CloudFormation begins StackSets operations in that account. This verification is performed through an AWS Lambda function that acts as a prerequisite check.

A common example of an account gate is verifying that there are no CloudWatch alarms active or unresolved on the target account. CloudFormation invokes the Lambda function each time you start stack operations in the target account, and only continues if the function returns a `SUCCEEDED` code. If the Lambda function returns a status of `FAILED`, CloudFormation doesn't continue with your requested operation. If you don't have an account gating Lambda function configured, CloudFormation skips the check, and continues with your operation.

If your target account fails an account gate check, the failed operation counts toward your specified failure tolerance number or percentage of stacks. For more information about failure tolerance, see [StackSet operation options](stacksets-concepts.md#stackset-ops-options).

Account gating is only available for StackSets operations. This feature isn't available for other CloudFormation operations outside of StackSets.

## Requirements
<a name="stacksets-accountgating_reqs"></a>

The following requirements must be met for account gating:
+ Your Lambda function must be named `AWSCloudFormationStackSetAccountGate` to use this feature.
+ The **AWSCloudFormationStackSetExecutionRole** must have permissions to invoke your Lambda function. Without these permissions, CloudFormation will skip the account gating check and proceed with stack operations.
+ The Lambda `InvokeFunction` permission must be added to target accounts for account gating to work. The target account trust policy must have a trust relationship with the administrator account. The following is an example of a policy statement that grants Lambda `InvokeFunction` permissions.

------
#### [ JSON ]

****  

  ```
  {
      "Version":"2012-10-17",		 	 	 
      "Statement": [
          {
              "Effect": "Allow",
              "Action": [
                  "lambda:InvokeFunction"
              ],
              "Resource": "*"
          }
      ]
  }
  ```

------

## CloudFormation templates for creating Lambda functions
<a name="stacksets-sample-accountgate"></a>

Use the following sample templates to create Lambda `AWSCloudFormationStackSetAccountGate` functions. To create a new stack using either of these templates, see [Create a stack from the CloudFormation console](cfn-console-create-stack.md).


|  Template location  |  Description  | 
| --- | --- | 
|  [https://s3.amazonaws.com/cloudformation-stackset-sample-templates-us-east-1/AccountGateSucceeded.yml](https://s3.amazonaws.com/cloudformation-stackset-sample-templates-us-east-1/AccountGateSucceeded.yml)  |  Creates a stack that implements a Lambda account gate function that will return a status of `SUCCEEDED`.  | 
|  [https://s3.amazonaws.com/cloudformation-stackset-sample-templates-us-east-1/AccountGateFailed.yml](https://s3.amazonaws.com/cloudformation-stackset-sample-templates-us-east-1/AccountGateFailed.yml)  |  Creates a stack that implements a Lambda account gate function that will return a status of `FAILED`.  | 

# Choose the Concurrency Mode for CloudFormation StackSets
<a name="concurrency-mode"></a>

**Concurrency Mode** is a parameter for [https://docs.aws.amazon.com/AWSCloudFormation/latest/APIReference/API_StackSetOperationPreferences.html](https://docs.aws.amazon.com/AWSCloudFormation/latest/APIReference/API_StackSetOperationPreferences.html) that allows you to choose how the concurrency level behaves during StackSet operations. You can choose between the following modes:
+ **Strict Failure Tolerance**: This option dynamically lowers the concurrency level to ensure the number of failed accounts never exceeds the value of **Failure tolerance** \$11. The initial actual concurrency is set to the lower of either the value of the **Maximum concurrent accounts**, or the value of **Failure tolerance** \$11. The actual concurrency is then reduced proportionally by the number of failures. This is the default behavior.
+ **Soft Failure Tolerance**: This option decouples **Failure tolerance** from the actual concurrency. This allows StackSet operations to run at the concurrency level set by the **Maximum concurrent accounts** value, regardless of the number of failures.

**Strict Failure Tolerance** lowers the deployment speed as StackSet operation failures occur because concurrency decreases for each failure. **Soft Failure Tolerance** prioritizes deployment speed while still leveraging CloudFormation safety capabilities. This allows you to review and address StackSet operation failures for common issues such as those related to existing resources, service quotas, and permissions.

For more information on StackSets stack operation failures, see [Common reasons for stack operation failure](stacksets-troubleshooting.md#common-reasons-for-stack-operation-failure).

For more information on **Maximum concurrent accounts** and **Failure tolerance**, see [StackSet operation options](stacksets-concepts.md#stackset-ops-options).

## How each Concurrency Mode works
<a name="concurrency-mode-example"></a>

The images below provide a visual representation of how each **Concurrency Mode** works during a StackSet operation. The string of nodes represents a deployment to single AWS Region and each node is a target AWS account.

**Strict Failure Tolerance**  
When a StackSet operation using **Strict Failure Tolerance** has the **Failure tolerance** value set to 5 and the **Maximum concurrent accounts** value set to 10, the actual concurrency is 6. The actual concurrency is 6 because this the **Failure tolerance** value of 5 \$11 is lower than the value of **Maximum concurrent accounts**.  
The following image shows the impact that the **Failure tolerance** value has on the **Maximum concurrent accounts** value, and the impact they both have on the actual concurrency of the StackSet operation:  

![\[A StackSet operation using strict failure tolerance. Fail tolerance is 5, max concurrent account is 10, and concurrency is 6.\]](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/images/concurrency-strict-failure-tolerance-1.png)

When deployment begins and there are failed stack instances, then the actual concurrency reduces to provide a safe deployment experience. The actual concurrency reduces from 6 to 5 when StackSets fails to deploy 1 stack instance.  

![\[The StackSet operation using Strict Failure Tolerance has 2 successful deployments and 1 failure.\]](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/images/concurrency-strict-failure-tolerance-2.png)


![\[The StackSet operation using Strict Failure Tolerance has reduced the actual concurrency to 5 now that there is one failure.\]](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/images/concurrency-strict-failure-tolerance-3.png)

The **Strict Failure Tolerance** mode reduces the actual concurrency proportionally to the number of failed stack instances. In the following example, the actual concurrency reduces from 5 to 3 when StackSets fails to deploy 2 more stack instances, bringing the total of failed stack instances to 3.  

![\[The StackSet operation using Strict Failure Tolerance now has 3 failed deployments. Concurrency has reduced to 3.\]](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/images/concurrency-strict-failure-tolerance-4.png)

StackSets fails the StackSet operation when the number of failed stack instances equals the defined value of **Failure tolerance** \$11. In the following example, StackSets fails the operation when there are 6 failed stack instances and the **Failure tolerance** value is 5.  

![\[The StackSet operation using Strict Failure Tolerance now has 6 failed deployments. The StackSet operation fails.\]](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/images/concurrency-strict-failure-tolerance-5.png)

In this example, CloudFormation deployed 9 stack instances (3 successful and 6 failed) before stopping the StackSet operation.

**Soft Failure Tolerance**  
When a StackSet operation using **Soft Failure Tolerance** has the **Failure tolerance** value set to 5 and the **Maximum concurrent accounts** value set to 10, the actual concurrency is 10.  

![\[A StackSet operation with Soft Failure Tolerance. Fail tolerance is 5 max concurrent accounts and actual concurrency are 10.\]](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/images/concurrency-soft-failure-tolerance-1.png)

When deployment begins and there are failed stack instances, the actual concurrency doesn't change. In the following example, 1 stack operation failed, but the actual concurrency remains at 10.  

![\[The StackSet operation with Soft Failure Tolerance encounters the first failure. Actual concurrency remains at 10.\]](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/images/concurrency-soft-failure-tolerance-2.png)

The actual concurrency remains at 10 even after 2 more stack instance failures.  

![\[The StackSet operation with Soft Failure Tolerance now has 2 successes and 3 failures, but actual concurrency is still 10.\]](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/images/concurrency-soft-failure-tolerance-3.png)

StackSets fails the StackSet operation when failed stack instances exceeds the **Failure tolerance** value. In the following example, StackSets fails the operation when there are 6 failed stack instances and the **Failure tolerance** count is 5. However, the operation won't end until the remaining operations in the concurrency queue finish.  

![\[The StackSet operation with Soft Failure Tolerance reaches 6 fails, but it must finish what's left in the concurrency queue.\]](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/images/concurrency-soft-failure-tolerance-4.png)

StackSets continues to deploy stack instances that are already in the concurrency queue. This means that the number of failed stack instances can be higher than **Failure tolerance**. In the following example, there are 8 failed stack instances because the concurrency queue still had 7 operations left to perform, even though the StackSet operation had reached the **Failure tolerance** of 5.  

![\[The StackSet operation has 8 total fails because it had 7 deployments left in the queue after it reached the fail threshold.\]](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/images/concurrency-soft-failure-tolerance-5.png)

In this example, StackSets deployed 15 stack instances (7 successful and 8 failed) before stopping the stack operation.

## Choosing between Strict failure tolerance and Soft failure tolerance based on deployment speed
<a name="concurrency-mode-comparison"></a>

Choosing between **Strict failure tolerance** and **Soft failure tolerance** modes depends on the preferred speed of your StackSet deployment and the permissible number of deployment failures.

The following tables show how each concurrency mode handles a StackSet operation that fails while trying to deploy 1000 total stack instances. In each scenario, the **Failure tolerance** value is set to 100 stack instances and the **Maximum concurrent accounts** value is set to 250 stack instances.

While StackSets actually queues accounts as a sliding window (see [How each Concurrency Mode works](#concurrency-mode-example)), this example shows the operation in batches to demonstrate the speed of each mode.

### Strict failure tolerance
<a name="concurrency-mode-comparison-strict"></a>

This example using **Strict failure tolerance** mode lowers the actual concurrency relative to the number of failures that occur in each preceding batch. Each batch has 20 failed instances, which then lowers the actual concurrency of the following batch by 20 until the StackSet operation reaches the **Failure tolerance** value of 100.

In following table, the initial actual concurrency of the first batch is 101 stack instances. The actual concurrency is 101 because it's the lower value of either the **Maximum concurrent accounts** (250) and the **Failure tolerance** (100) \$11. Each batch contains 20 failed stack instance deployments, which then lowers the actual concurrency of each following batch by 20 stack instances.


| **Strict failure tolerance** | **Batch 1** | **Batch 2** | **Batch 3** | **Batch 4** | **Batch 5** | **Batch 6** | 
| --- | --- | --- | --- | --- | --- | --- | 
| Actual concurrency count | 101 | 81 | 61 | 41 | 21 | - | 
| Failed instance count | 20 | 20 | 20 | 20 | 20 | - | 
| Successful stack instance count  | 81 | 61 | 41 | 21 | 1 | - | 

The operation using **Strict failure tolerance** completed 305 stack instance deployments in 5 batches by the time the StackSet operation reached the **Failure tolerance** of 100 stack instances. The StackSet operation successfully deploys 205 stack instances before it fails.

### Soft failure tolerance
<a name="concurrency-mode-comparison-soft"></a>

This example using **Soft failure tolerance** mode maintains the same actual concurrency count defined by the **Maximum concurrent accounts** value of 250 stack instances, regardless of the number of failed instances. The StackSet operations keeps the same actual concurrency until it reaches the **Failure tolerance** value of 100 instances.

In following table, the initial actual concurrency of the first batch is 250 stack instances. The actual concurrency is 250 because the **Maximum concurrent accounts** value is set to 250 and **Soft failure tolerance** mode allows StackSets to use this value as the actual concurrency, regardless of the number of failures. Even though there are 50 failures in each of the batches for this example, the actual concurrency remains unaffected.


| **Soft failure tolerance** | **Batch 1** | **Batch 2** | **Batch 3** | **Batch 4** | **Batch 5** | **Batch 6** | 
| --- | --- | --- | --- | --- | --- | --- | 
| Actual concurrency count | 250 | 250 | - | - | - | - | 
| Failed instance count | 50 | 50 | - | - | - | - | 
| Successful stack instance count  | 200 | 200 | - | - | - | - | 

Using the same **Maximum concurrent accounts** value and **Failure tolerance** value, the operation using **Soft failure tolerance** mode completed 500 stack instance deployments in 2 batches. The StackSet operation successfully deploys 400 stack instances before it fails.

## Choosing your Concurrency Mode (console)
<a name="concurrency-mode-console"></a>

When creating or updating a StackSet, on the **Set deployment options** page, for **Concurrency mode**, choose **Strict failure tolerance** or **Soft failure tolerance**.

## Choosing your Concurrency Mode (AWS CLI)
<a name="concurrency-mode-cli"></a>

You can use the `ConcurrencyMode` parameter with the following StackSets commands:
+ [https://docs.aws.amazon.com/cli/latest/reference/cloudformation/create-stack-instances.html](https://docs.aws.amazon.com/cli/latest/reference/cloudformation/create-stack-instances.html)
+ [https://docs.aws.amazon.com/cli/latest/reference/cloudformation/delete-stack-instances.html](https://docs.aws.amazon.com/cli/latest/reference/cloudformation/delete-stack-instances.html)
+ [https://docs.aws.amazon.com/cli/latest/reference/cloudformation/detect-stack-set-drift.html](https://docs.aws.amazon.com/cli/latest/reference/cloudformation/detect-stack-set-drift.html)
+ [https://docs.aws.amazon.com/cli/latest/reference/cloudformation/import-stacks-to-stack-set.html](https://docs.aws.amazon.com/cli/latest/reference/cloudformation/import-stacks-to-stack-set.html)
+ [https://docs.aws.amazon.com/cli/latest/reference/cloudformation/update-stack-instances.html](https://docs.aws.amazon.com/cli/latest/reference/cloudformation/update-stack-instances.html)
+ [https://docs.aws.amazon.com/cli/latest/reference/cloudformation/update-stack-set.html](https://docs.aws.amazon.com/cli/latest/reference/cloudformation/update-stack-set.html)

These commands have an existing parameter called `--operation-preferences` that can use the `ConcurrencyMode` setting. `ConcurrencyMode` can be set to one of the following values:
+ `STRICT_FAILURE_TOLERANCE`
+ `SOFT_FAILURE_TOLERANCE`

The following example creates a stack instance using the `STRICT_FAILURE_TOLERANCE` `ConcurrencyMode`, with a `FailureToleranceCount` set to 10 and a `MaxConcurrentCount` set to 5.

```
aws cloudformation create-stack-instances \
  --stack-set-name example-stackset \
  --accounts 123456789012 \
  --regions eu-west-1  \
  --operation-preferences ConcurrencyMode=STRICT_FAILURE_TOLERANCE,FailureToleranceCount=10,MaxConcurrentCount=5
```

**Note**  
For detailed procedures for creating and updating a StackSet, see the following topics:  
[Create StackSets (self-managed permissions)](stacksets-getting-started-create-self-managed.md)
[Create StackSets (service-managed permissions)](stacksets-orgs-associate-stackset-with-org.md)
[Update StackSets](stacksets-update.md)

# Performing drift detection on CloudFormation StackSets
<a name="stacksets-drift"></a>

Even as you manage your stacks and the resources they contain through CloudFormation, users can change those resources outside of CloudFormation. Users can edit resources directly by using the underlying service that created the resource. By performing drift detection on a StackSet, you can determine if any of the stack instances belonging to that StackSet differ, or have *drifted*, from their expected configuration.

**Topics**
+ [How CloudFormation performs drift detection on a StackSet](#stacksets-drift-how)
+ [Detect drift on a StackSet (console)](#stacksets-drift-console-procedure)
+ [Detect drift on a StackSet (AWS CLI)](#stacksets-drift-cli-procedure)
+ [Stopping drift detection on a StackSet](#stacksets-drift-stop)

## How CloudFormation performs drift detection on a StackSet
<a name="stacksets-drift-how"></a>

When CloudFormation performs drift detection on a StackSet, it performs drift detection on the stack associated with each stack instance in the StackSet. To do this, CloudFormation compares the current state of each resource in the stack with the expected state of that resource, as defined in the stack's template and any specified input parameters. If the current state of a resource varies from its expected state, that resource is considered to have drifted. If one or more resources in a stack have drifted, then the stack itself is considered to have drifted, and the stack instances that the stack is associated with is considered to have drifted as well. If one or more stack instances in a StackSet have drifted, the StackSet itself is considered to have drifted.

Drift detection identifies unmanaged changes; that is, changes made to stacks outside of CloudFormation. Changes made through CloudFormation to a stack directly, rather than at the StackSet level, aren't considered drift. For example, suppose you have a stack that is associated with a stack instance of a StackSet. If you use CloudFormation to update that stack to use a different template, that is not considered drift, even though that stack now has a different template than any other stacks belonging to the StackSet. This is because the stack still matches its expected template and parameter configuration in CloudFormation.

For detailed information on how CloudFormation performs drift detection on a stack, see [Detect unmanaged configuration changes to stacks and resources with drift detection](using-cfn-stack-drift.md).

Because CloudFormation performs drift detection on each stack individually, it takes any overridden parameter values into account when determining whether a stack has drifted. For more information on overriding template parameters in stack instances, see [Override parameter values on stacks within your CloudFormation StackSet](stackinstances-override.md).

If you perform drift detection [directly on a stack](using-cfn-stack-drift.md) that is associated with a stack instance, those drift results aren't available from the **StackSets** console page.

## Detect drift on a StackSet (console)
<a name="stacksets-drift-console-procedure"></a>

**To detect drift on a StackSet**

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

1. On the **StackSets** page, select the StackSet on which you want to perform drift detection.

1. From the **Actions** menu, select **Detect drifts**.

   CloudFormation displays an information bar stating that drift detection has been initiated for the selected StackSet.

1. Optional: To monitor the progress of the drift detection operation:

   1. Select the StackSet name to display the **Stackset details** page.

   1. Select the **Operations** tab, select the drift detection operation, and then select **View drift details**.

   CloudFormation displays the **Operation details** dialog box.

1. Wait until CloudFormation completes the drift detection operation. When the drift detection operation completes, CloudFormation updates **Drift status** and **Last drift check time** for your StackSet. These fields are listed on the **Overview** tab of the **StackSet details** page for the selected StackSet.

   The drift detection operation may take some time, depending on the number of stack instances included in the StackSet, and the number of resources included in the StackSet. You can only run a single drift detection operation on a given StackSet at one time. CloudFormation continues the drift detection operation even after you dismiss the information bar.

1. To review the drift detection results for the stack instances in a StackSet, select the **Stack instances** tab.

   The **Stack name** column lists the name of the stack associated with each stack instance, and the **Drift status** column lists the drift status of that stack. A stack is considered to have drifted if one or more of its resources have drifted.

1. To review the drift detection results for the stack associated with a specific stack instance:

   1. Choose the **Operations** tab.

   1. Select the drift operation you want to view drift detection results for. A split panel will display the stack instance status and reason for the selected operation. For a drift operation, the status reason column shows the drift status of a stack instance.

   1. Choose the stack instance you want to view drift details for, and choose **View resource drifts**. In the **Resource drift status** table on the **Resource Drifts** page, each stack resource is listed with its drift status and the last time drift detection was initiated on the resource. The logical ID and physical ID of each resource is displayed to help you identify them.

1. You can sort the resources based on their drift status using the **Drift status** column.

   To view the details on a modified resource:

   1. With the resource selected, choose **View drift details**.

     CloudFormation displays the drift detail page for that particular resource. This page lists the resource's differences. It also lists the resource's expected and current property values.
**Note**  
If the stack belongs to a different Region and account than the one you're currently signed into, the **Detect drift** button will be disabled and you will be unable to view the details.

## Detect drift on a StackSet (AWS CLI)
<a name="stacksets-drift-cli-procedure"></a>

To detect drift on an entire stack using the AWS CLI, use the following procedure:

**To detect drift on a StackSet**

1. Use the [https://docs.aws.amazon.com/cli/latest/reference/cloudformation/detect-stack-set-drift.html](https://docs.aws.amazon.com/cli/latest/reference/cloudformation/detect-stack-set-drift.html) command to detect drift on an entire StackSet and its associated stack instances.

   The following example initiates drift detection on the StackSet `stack-set-drift-example`.

   ```
   aws cloudformation detect-stack-set-drift \
       --stack-set-name stack-set-drift-example
   ```

   Output:

   ```
   {
       "OperationId": "c36e44aa-3a83-411a-b503-cb611example"
   }
   ```

1. Because StackSet drift detection operations can be a long-running operation, use the [https://docs.aws.amazon.com/cli/latest/reference/cloudformation/describe-stack-set-operation.html](https://docs.aws.amazon.com/cli/latest/reference/cloudformation/describe-stack-set-operation.html) command to monitor the status of drift operation. This command takes the StackSet operation ID returned by the **detect-stack-set-drift** command.

   The following examples uses the operation ID from the previous example to return information on the StackSet drift detection operation. In this example, the operation is still running. Of the seven stack instances associated with this StackSet, one stack instance has already been found to have drifted, two instances are in sync , and drift detection for the remaining four stack instances is still in progress. Because one instance has drifted, the drift status of the StackSet itself is now `DRIFTED`.

   ```
   aws cloudformation describe-stack-set-operation \
       --stack-set-name stack-set-drift-example \
       --operation-id c36e44aa-3a83-411a-b503-cb611example
   ```

   Output:

   ```
   {
       "StackSetOperation": {
           "Status": "RUNNING",
           "AdministrationRoleARN": "arn:aws:iam::123456789012:role/AWSCloudFormationStackSetAdministrationRole",
           "OperationPreferences": {
               "RegionOrder": []
           },
           "ExecutionRoleName": "AWSCloudFormationStackSetExecutionRole",
           "StackSetDriftDetectionDetails": {
               "DriftedStackInstancesCount": 1,
               "TotalStackInstancesCount": 7,
               "LastDriftCheckTimestamp": "2019-12-04T20:34:28.543Z",
               "InSyncStackInstancesCount": 2,
               "InProgressStackInstancesCount": 4,
               "DriftStatus": "DRIFTED",
               "FailedStackInstancesCount": 0
           },
           "Action": "DETECT_DRIFT",
           "CreationTimestamp": "2019-12-04T20:33:13.673Z",
           "StackSetId": "stack-set-drift-example:bd1f4017-d4f9-432e-a73f-8c22example",
           "OperationId": "c36e44aa-3a83-411a-b503-cb611example"
       }
   }
   ```

   Performing the same command later, this example shows the information returned once the drift detection operation has completed. Two of the seven total stack instances associated with this StackSet have drifted, rendering the drift status of the StackSet itself as `DRIFTED`.

   ```
   aws cloudformation describe-stack-set-operation \
       --stack-set-name stack-set-drift-example \
       --operation-id c36e44aa-3a83-411a-b503-cb611example
   ```

   Output:

   ```
   {
       "StackSetOperation": {
           "Status": "SUCCEEDED",
           "AdministrationRoleARN": "arn:aws:iam::123456789012:role/AWSCloudFormationStackSetAdministrationRole",
           "OperationPreferences": {
               "RegionOrder": []
           } 
           "ExecutionRoleName": "AWSCloudFormationStackSetExecutionRole",
           "EndTimestamp": "2019-12-04T20:37:32.829Z",
           "StackSetDriftDetectionDetails": {
               "DriftedStackInstancesCount": 2,
               "TotalStackInstancesCount": 7,
               "LastDriftCheckTimestamp": "2019-12-04T20:36:55.612Z",
               "InSyncStackInstancesCount": 5,
               "InProgressStackInstancesCount": 0,
               "DriftStatus": "DRIFTED",
               "FailedStackInstancesCount": 0
           },
           "Action": "DETECT_DRIFT",
           "CreationTimestamp": "2019-12-04T20:33:13.673Z",
           "StackSetId": "stack-set-drift-example:bd1f4017-d4f9-432e-a73f-8c22example",
           "OperationId": "c36e44aa-3a83-411a-b503-cb611example"
       }
   }
   ```

1. When the StackSet drift detection operation is complete, use the **describe-stack-set**, **list-stack-instances**, **describe-stack-instance**, and **list-stack-instance-resource-drifts** commands to review the results.

   The [https://docs.aws.amazon.com/cli/latest/reference/cloudformation/describe-stack-set.html](https://docs.aws.amazon.com/cli/latest/reference/cloudformation/describe-stack-set.html) command includes the same detailed drift information returned by the **describe-stack-set-operation** command.

   ```
   aws cloudformation describe-stack-set \
       --stack-set-name stack-set-drift-example
   ```

   Output:

   ```
   {
       "StackSet": {
           "Status": "ACTIVE",
           "Description": "Demonstration of drift detection on stack sets.",
           "Parameters": [],
           "Tags": [
               {
                   "Value": "Drift detection",
                   "Key": "Feature"
               }
           ], 
           "ExecutionRoleName": "AWSCloudFormationStackSetExecutionRole",
           "Capabilities": [],
           "AdministrationRoleARN": "arn:aws:iam::123456789012:role/AWSCloudFormationStackSetAdministrationRole",
           "StackSetDriftDetectionDetails": {
               "DriftedStackInstancesCount": 2,
               "TotalStackInstancesCount": 7,
               "LastDriftCheckTimestamp": "2019-12-04T20:36:55.612Z",
               "InProgressStackInstancesCount": 0,
               "DriftStatus": "DRIFTED",
               "DriftDetectionStatus": "COMPLETED",
               "InSyncStackInstancesCount": 5,
               "FailedStackInstancesCount": 0
           },
           "StackSetARN": "arn:aws:cloudformation:us-east-1:123456789012:stackset/stack-set-drift-example:bd1f4017-d4f9-432e-a73f-8c22example",
           "TemplateBody": [details omitted],
           "StackSetId": "stack-set-drift-example:bd1f4017-d4f9-432e-a73f-8c22ebexample",
           "StackSetName": "stack-set-drift-example"
       }
   }
   ```

   You can use the [https://docs.aws.amazon.com/cli/latest/reference/cloudformation/list-stack-instances.html](https://docs.aws.amazon.com/cli/latest/reference/cloudformation/list-stack-instances.html) command to return summary information about the stack instances associated with a StackSet, including the drift status of each stack instance.

   In this example, executing **list-stack-instances** on the example StackSet with the drift status filter set to `DRIFTED` enables you to identify which two stack instances have a drift status of `DRIFTED`.

   ```
   aws cloudformation list-stack-instances \
       --stack-set-name stack-set-drift-example \
       --filters Name=DRIFT_STATUS,Values=DRIFTED
   ```

   Output:

   ```
   {
   "Summaries": [
           {
   "StackId": "arn:aws:cloudformation:eu-west-1:123456789012:stack/StackSet-stack-set-drift-example-b0fb6083-60c0-4e39-af15-2f071e0db90c/0e4f0940-16d4-11ea-93d8-0641cexample",
               "Status": "CURRENT",
               "Account": "012345678910",
               "Region": "eu-west-1",
               "LastDriftCheckTimestamp": "2019-12-04T20:37:32.687Z",
               "DriftStatus": "DRIFTED",
               "StackSetId": "stack-set-drift-example:bd1f4017-d4f9-432e-a73f-8c22eexample",
               "LastOperationId": "c36e44aa-3a83-411a-b503-cb611example"
           },
           {
               "StackId": "arn:aws:cloudformation:us-east-1:123456789012:stack/StackSet-stack-set-drift-example-b7fde68e-e541-44c2-b33d-ef2e2988071a/008e6030-16d4-11ea-8090-12f89example",
               "Status": "CURRENT",
               "Account": "123456789012",
               "Region": "us-east-1",
               "LastDriftCheckTimestamp": "2019-12-04T20:34:28.275Z",
               "DriftStatus": "DRIFTED",
               "StackSetId": "stack-set-drift-example:bd1f4017-d4f9-432e-a73f-8c22eexample",
               "LastOperationId": "c36e44aa-3a83-411a-b503-cb611example"
           },
           
           [additional stack instances omitted]
    
       ]
   }
   ```

   The [https://docs.aws.amazon.com/cli/latest/reference/cloudformation/describe-stack-instance.html](https://docs.aws.amazon.com/cli/latest/reference/cloudformation/describe-stack-instance.html) command also returns this information, but for a single stack instance, as in the example below.

   ```
   aws cloudformation describe-stack-instance \
       --stack-set-name stack-set-drift-example \
       --stack-instance-account 012345678910 --stack-instance-region us-east-1
   ```

   Output:

   ```
   {
       "StackInstance": {
           "StackId": "arn:aws:cloudformation:us-east-1:123456789012:stack/StackSet-stack-set-drift-example-b7fde68e-e541-44c2-b33d-ef2e2988071a/008e6030-16d4-11ea-8090-12f89example",
           "Status": "CURRENT",
           "Account": "123456789012",
           "Region": "us-east-1",
           "ParameterOverrides": [],
           "DriftStatus": "DRIFTED",
           "LastDriftCheckTimestamp": "2019-12-04T20:34:28.275Z",
           "StackSetId": "stack-set-drift-example:bd1f4017-d4f9-432e-a73f-8c22eexample",
           "LastOperationId": "c36e44aa-3a83-411a-b503-cb611example"
       }
   }
   ```

1. Once you've identified which stack instances have drifted, you can use the information about the stack instances that is returned by the **list-stack-instances** or **describe-stack-instance** commands to run the [https://docs.aws.amazon.com/cli/latest/reference/cloudformation/list-stack-instance-resource-drifts.html](https://docs.aws.amazon.com/cli/latest/reference/cloudformation/list-stack-instance-resource-drifts.html) command. This command returns detailed information about which resources in the stack have drifted for a particular drift operation.

   The following example uses the `--stack-instance-resource-drift-statuses` parameter to request stack drift information for the resources that have been modified or deleted in the previous drift operation example. The request returns information on the one resource that has been modified, including details about two of its properties and their changed values. No resources have been deleted.

   ```
   aws cloudformation list-stack-instance-resource-drifts \
       --stack-set-name my-stack-set-with-resource-drift \
       --stack-instance-account 123456789012 \
       --stack-instance-region us-east-1 \
       --operation-id c36e44aa-3a83-411a-b503-cb611example \
       --stack-instance-resource-drift-statuses MODIFIED DELETED
   ```

   Output:

   ```
   {
       "Summaries": [
           {
               "StackId": "arn:aws:cloudformation:us-east-1:123456789012:stack/my-stack-set-with-resource-drift/489e5570-df85-11e7-a7d9-50example",
               "ResourceType": "AWS::SQS::Queue",
               "Timestamp": "2018-03-26T17:23:34.489Z",
               "PhysicalResourceId": "https://sqs.us-east-1.amazonaws.com/123456789012/my-stack-with-resource-drift-Queue-494PBHCO76H4",
               "StackResourceDriftStatus": "MODIFIED",
               "PropertyDifferences": [
                   {
                       "PropertyPath": "/DelaySeconds",
                       "ActualValue": "120",
                       "ExpectedValue": "20",
                       "DifferenceType": "NOT_EQUAL"
                   },
                   {
                       "PropertyPath": "/RedrivePolicy/maxReceiveCount",
                       "ActualValue": "12",
                       "ExpectedValue": "10",
                       "DifferenceType": "NOT_EQUAL"
                   }
               ],
               "LogicalResourceId": "Queue"
           }
       ]
   }
   ```

## Stopping drift detection on a StackSet
<a name="stacksets-drift-stop"></a>

Because drift detection on a StackSet can be a long-running operation, there may be instances when you want to stop a drift detection operation that is currently running on a StackSet.

**To stop drift detection on a StackSet (console)**

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

1. On the **StackSets** page, select the name of the StackSet.

   CloudFormation displays the **StackSets details** page for the selected StackSet.

1. On the **StackSets details** page, select the **Operations** tab, and then select the drift detection operation.

1. Select **Stop operation**.

**To stop drift detection on a StackSet (AWS CLI)**
+ Use the [https://docs.aws.amazon.com/cli/latest/reference/cloudformation/stop-stack-set-operation.html](https://docs.aws.amazon.com/cli/latest/reference/cloudformation/stop-stack-set-operation.html) command. You must supply both the StackSet name and the operation ID of the drift detection StackSet operation.

  ```
  aws cloudformation stop-stack-set-operation \
      --stack-set-name stack-set-drift-example \
      --operation-id 624af370-311a-11e8-b6b7-500cexample
  ```

# Import stacks into CloudFormation StackSets
<a name="stacksets-import"></a>

A stack import operation can import existing stacks into new or existing StackSets, so that you can migrate existing stacks to a StackSet in one operation.

For *self-managed* StackSets, the import operation can import stacks in the administrator account or in different target accounts and AWS Regions. For *service-managed* StackSets, the import operation can import any stack in the same AWS Organizations as the management account. 

The following are considerations and limitations when importing stacks into StackSets:
+ The import operation can import up to 10 stacks using inline stack IDs or up to 200 stacks using an Amazon S3 object.
+  The `NoEcho` property is not supported. Stacks that contain `NoEcho` won't be imported into new StackSets through StackSet import.
+ Stacks can only belong to one StackSet.
+ You can implement stack tags to the StackSet by specifying tags explicitly as parameters in the stack import operation.
+ A stack's custom parameter overrides aren't affected during the import operation.
+ Parameters of imported stack instances can't be updated using the **Edit StackSet details** option. You must use the **Override StackSet parameters**. For more information on overriding parameters, see [Override parameters on stacks](stackinstances-override.md).
+ The StackSets quotas and stack instances apply when importing stacks. For more information about quotas, see [Understand CloudFormation quotas](cloudformation-limits.md).

**Topics**
+ [Self-managed stack import for CloudFormation StackSets](self-managed-import.md)
+ [Service-managed stack import for CloudFormation StackSets](service-managed-import.md)
+ [Revert stack imports into CloudFormation StackSets](revert-stackset-import.md)

# Self-managed stack import for CloudFormation StackSets
<a name="self-managed-import"></a>

The CloudFormation stack import operation can import existing stacks into new or existing StackSets, so that you can migrate existing stacks to a StackSet in one operation. By using stack import, you avoid downtime and outages without deleting and recreating those resources. Once the stack is imported into a StackSet, the original stack will become a stack instance of the specified stack set.

**Considerations for self-managed stack imports**
+ The stack import operation requires an administrator account in which you create a StackSet and a target account that contains a stack.
+ The target account must have permission to use the `GetTemplate` operation with the input of stack ID or ARN. Because of that, your administrator account must be granted **AWSCloudFormationStackSetAdministrationRole** or **AWSCloudFormationStackSetsExectionRole** permissions.

**Topics**
+ [Import an existing stack into a new StackSet (console)](#import-stacks-to-stack-set)
+ [Import an existing stack into an existing StackSet (console)](#import-stack-to-existing-stackset)
+ [Import a stack into a StackSet (AWS CLI)](#importing-stack-to-stackset.cli)

## Import an existing stack into a new StackSet (console)
<a name="import-stacks-to-stack-set"></a>

Before you begin, identify the stack that you want to import.

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. From the navigation pane, choose **StackSets**.

1. At the top of the **StackSets** page, choose **Create StackSet**.

1. On the **Choose a template** page, specify a template by one of the following options and choose **Next**.
   + Choose **Amazon S3 URL** and specify the URL for your template in the text box.
   + Choose **Upload a template file** and browse for your template.
   + Choose **From stack ID** and enter your stack ID.

1. On the **Specify StackSet details** page, enter the name of a StackSet you want to create and choose **Next**.

   (Optional) Enter a description of the StackSet.

1. On the **Configure StackSet options** page, review your choices and choose **Next**.

1. On the **Set deployment options** page, choose **Import stacks to stack set**.

1. Enter the stack ID of the stack you want to import in the **Stacks to import** field. For example, `arn:aws:cloudformation:us-east-1:123456789012:stack/StackToImport/f449b250-b969-11e0-a185-5081d0136786`.

   (Optional) Choose **Add another stack ID** and enter the stack ID of another stack you want to import. You may add up to 10 stacks per stack import operation.

1. Review your deployment options and choose **Next**.

1. On the **Review** page, review your choices and your StackSet's properties. When you are ready to import your stack into your StackSet, choose **Submit**.

**Results**: The imported stack is now a stack instance of the specified StackSet. To learn more about the stack import status, see [StackSets status codes](stacksets-concepts.md#stackset-status-codes).

## Import an existing stack into an existing StackSet (console)
<a name="import-stack-to-existing-stackset"></a>

Before you begin, identify the stack that you want to import.

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. From the navigation pane, choose **StackSets**.

1. On the **StackSets** page, choose the StackSet that you want to import a stack into.

1. With the StackSet selected, choose **Add stacks to StackSet** from the **Actions** menu.

1. On the **Set deployment options** page, choose **Import stacks to stack set** and enter the stack ID of the stack you want to import in the **Stacks to import** field. For example, `arn:aws:cloudformation:us-east-1:123456789012:stack/StackToImport/f449b250-b969-11e0-a185-5081d0136786`.

   (Optional) Choose **Add another stack ID** and enter the stack ID of another stack you want to import. You may add up to 10 stacks per stack import operation.

1. Choose **Next**.

1. On the **Specify overrides** page, review your choices and choose **Next**.

1. On the **Review** page, review your choices and your StackSet's properties. When you are ready to create your StackSet, choose **Submit**.

**Results**: The imported stack is now a stack instance of the specified StackSet. To learn more about the stack import status, see [StackSets status codes](stacksets-concepts.md#stackset-status-codes).

## Import a stack into a StackSet (AWS CLI)
<a name="importing-stack-to-stackset.cli"></a>

**To import an existing stack into a new StackSet**  
The following `create-stack-set` command creates a StackSet and imports the specified stack. The stack to import is identified by its ARN. Replace the placeholder text with your own information.

```
aws cloudformation create-stack-set \
  --stack-set-name MyStackSet \
  --stack-id arn:aws:cloudformation:us-east-1:123456789012:stack/StackToImport/466df9e0-0dff-08e3-8e2f-5088487c4896 \
  --administration-role-arn arn:aws:iam::123456789012:role/AWSCloudFormationStackSetAdministrationRole \
  --execution-role-name AWSCloudFormationStackSetExecutionRole
```

**To import an existing stack into an existing StackSet**  
The following `import-stacks-to-stack-sets` command imports the specified stack into the *MyStackSet* StackSet. The stack to import is identified by its ARN. Replace the placeholder text with your own information.

```
aws cloudformation import-stacks-to-stack-set \
  --stack-set MyStackSet \
  --stack-ids arn:aws:cloudformation:us-east-1:123456789012:stack/StackToImport/f449b250-b969-11e0-a185-5081d0136786
```

To specify more than one stack, use the following format for the value of the `--stack-ids` option.

```
--stack-ids "arn_1" "arn_2"
```

**To clone the imported stack into other Regions and accounts**  
The following `create-stack-instances` command adds stack instances to your StackSet. Replace the placeholder text with your own information.

```
aws cloudformation create-stack-instances \
  --stack-set-name MyStackSet \
  --accounts '["account_ID_1","account_ID_2"]' \
  --regions '["region_1","region_2"]'
```

# Service-managed stack import for CloudFormation StackSets
<a name="service-managed-import"></a>

The CloudFormation stack import operation can import existing stacks into new or existing StackSets, so that you can migrate existing stacks to a StackSet in one operation. StackSets extends the functionality of stacks, so you can create, update, or delete stacks across multiple accounts and Regions with a single operation.

**Considerations for service-managed stack imports**
+ The stack import operation requires a management account or delegated admin account in which you can manage the associated AWS Organizations such as enabling trust access with StackSets.
+ The target accounts must be members of the AWS Organizations managed by the management account or delegated admin account.
+ Target stack exists in one of the target OUs.
+ The target account should be a member of AWS Organizations.
+ AWS Organizations access should be in the `ACTIVATED` state for the Organizations.
+ Stacks being imported should be present in any of the member accounts, and not the management account.

**Topics**
+ [Import a service-managed stack into a new StackSet (console)](#import-service-managed-stack-to-new-stackset)
+ [Create and import a service-managed stack into an existing StackSet (console)](#import-service-managed-stack-to-existing-stackset)
+ [Import a service-managed stack into an existing StackSet (console)](#import-service-managed-stack-to-existing-stackset-console)
+ [Importing a service-managed stack into a StackSet (AWS CLI)](#import-service-managed-stack-to-stackset.cli)

## Import a service-managed stack into a new StackSet (console)
<a name="import-service-managed-stack-to-new-stackset"></a>

Import a stack into a new StackSet using the AWS Management Console

To import a new stack into a StackSet, identify a stack that contains the resource you want to import.

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. From the navigation pane, choose **StackSets**.

1. At the top of the **StackSets** page, choose **Create StackSet**.

1. On the **Choose a template** page, do the following:

   1. For **StackSet permission model** choose **Service-managed permissions**.

   1. For **Prerequisite - Prepare template**, choose **Template is ready**, and choose your template by using one of the following options:
      + For **Amazon S3 URL**, enter your Amazon S3 URL in the **Amazon S3 URL** field.
      + For **Upload a template file**, choose a CloudFormation template on your local computer.

   Accept your settings and choose **Next**.

1. On the **Specify StackSet details** page, do the following:

   1. Enter a StackSet name in the **StackSet name** box.

   1. (Optional) Enter a description in the **StackSet description** section.

   On the **Configure StackSet options** page, review your choices and choose **Next**.

1. On the **Set deployment options** page, do the following:

   1. For **Add stacks to stack set**, choose **Import stacks to stack set**.

   1. For **Stacks to import**, choose your stack import method.

      1. For **Stack ID** enter your stack ID.

      1. For **Stack URL** enter the Amazon S3 URL.

1. Under **Associate organizational units**, do the following:

   1. Choose **Associate with organization** to use root OU.

   1. Choose **Associate with organizational units (OUs)** to enter parent OU IDs for the stacks to import. For example, if `Stack 1` and `Stack 2` are under `OU1`, and `Stack 3` is under `OU2`, enter `OU1` and `OU2`.

   Accept your settings and choose **Next**.

1. Review your settings on the **Review** page and choose **Submit**.

## Create and import a service-managed stack into an existing StackSet (console)
<a name="import-service-managed-stack-to-existing-stackset"></a>

To import an existing stack into a new StackSet, identify a stack that contains the resource you want to import.

**To create a StackSet and import a stack**

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. From the navigation pane, choose **StackSets**.

1. At the top of the **StackSets** page, choose **Create StackSet**.

1. On the **Choose a template** page, do the following:

   1. For **StackSet permission model** choose **Service-managed permissions**.

   1. For **Prerequisite - Prepare template**, choose **Template is ready**, and choose your template by using one of the following options:
      + For **Amazon S3 URL**, enter your Amazon S3 URL in the **Amazon S3 URL** field.
      + For **Upload a template file**, choose a CloudFormation template on your local computer.

   Accept your settings and choose **Next**.

1. On the **Specify StackSet details** page, do the following:

   1. Enter a StackSet name in the **StackSet name** box.

   1. (Optional) Enter a description in the **StackSet description** section.

   On the **Configure StackSet options** page, review your choices and choose **Next**.

1. On the **Set deployment options** page, do the following:

   1. For **Add stacks to stack set**, choose **Deploy new stacks**.

1. For the **Associate organizational units** section, do the following:

   1. Choose **Associate with organization** to use root OU.

   1. Choose **Associate with organizational units (OUs)** to enter parent OU IDs for the stacks to import. For example, if `Stack 1` and `Stack 2` are under `OU1`, and `Stack 3` is under `OU2`, enter `OU1` and `OU2`.

1. For **Specify regions** and **Deployment options**, review your choices.

   Accept your settings and choose **Next**.

1. Review your settings on the **Review** page and choose **Submit**.

## Import a service-managed stack into an existing StackSet (console)
<a name="import-service-managed-stack-to-existing-stackset-console"></a>

Choose your StackSet and identify the stack you want to import.

**To import a stack to an existing StackSet**

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. From the navigation pane, choose **StackSets**.

1. Choose the StackSet you want to import a stack to, and then choose **Add stacks to StackSet** from the **Actions** drop-down.

1. On the **Set deployment options** page, do the following:

   1. For **Add stacks to stack set**, choose **Import stacks to stack set**.

   1. Under **Stacks to import**, do the following

      1. For **Stack ID**, enter your stack ID.

      1. For **Stack URL**, enter the Amazon S3 URL.

   1. Under **Associate organizational units**, do the following:

      1. Choose **Associate with organization** to use root OU.

      1. Choose **Associate with organizational units (OUs)** to enter parent OU IDs for the stacks to import. For example, if `Stack 1` and `Stack 2` are under `OU1`, and `Stack 3` is under `OU2`, enter `OU1` and `OU2`.

      Accept your settings and choose **Next**.

1. Review the **Specify overrides** page and choose **Next**.

1. Confirm and review the **Review** page and choose **Submit**.

## Importing a service-managed stack into a StackSet (AWS CLI)
<a name="import-service-managed-stack-to-stackset.cli"></a>

Once a StackSet is created, you can import your stacks by passing the stack ID's of the stacks being imported. You may also pass the OU ID list to which you want to map it to.

CloudFormation will import user provided stacks within those OUs and use those OUs as deployment targets for the StackSet. Stack IDs presented in the input will map to the nearest OU in OU ID list input internally. If a stack doesn't belong to an existing OU ID in the input list, then the AWS CLI will return the `StackNotFoundException` error.

The `import-stacks-to-stack-set` operation creates stack instances for the stacks in the OU ID input. The following AWS CLI examples use the `import-stacks-to-stack-set` operation to import a stack into a StackSet.
+ To use the `import-stacks-to-stack-sets` operation, specify `stack-ids` or `stack-ids-url` you want to import to your stack set.

  ```
  aws cloudformation import-stacks-to-stack-set \
    --stack-set-name ServiceMangedStackSet \
    --stack-ids "arn:123456789012:us-east-1:Stack1" \
    --organizational-unit-ids ou-examplerootid111-exampleouid111
  ```

  ```
  aws cloudformation import-stacks-to-stack-set \
    --stack-set-name ServiceMangedStackSet \
    --stack-ids-url https://amzn-s3-demo-bucket.s3.us-west-2.amazonaws.com/file-name.json \
    --organizational-unit-ids ou-examplerootid111-exampleouid111
  ```

**Note**  
The `import-stacks-to-stack-sets` operation, requires you to specify at least one organizational unit ID (OU ID) so that it can associate the stack being imported to that particular OU. This operation doesn't create stack instances for other member accounts in the associated OUs. To update member accounts for the associated OUs, use `create-stack-instances` or `update-stack-instances`.

`create-stack-set` creates stack instances for all the accounts under the OUs with a user provided template, either from direct upload or Amazon S3. The following AWS CLI examples use the `create-stack-set` operation to import a stack into a new StackSet.
+ To use the `create-stack-set` operation, specify your StackSet name and import a stack to a newly created StackSet.

  ```
  aws cloudformation create-stack-set \
    --template-url https://amzn-s3-demo-bucket.s3.us-west-2.amazonaws.com/file-name.json \
    --permission-model SERVICE_MANAGED \
    --auto-deployment Enabled=true
  ```

# Revert stack imports into CloudFormation StackSets
<a name="revert-stackset-import"></a>

If you have unwanted changes in your stack instance, you can revert the stack instance import.

When you revert a stack instance import, CloudFormation deletes the stack instance from the StackSet but retains the stack's resources.

To revert a stack import operation, complete the following procedure.

1. Specify a `DeletionPolicy` attribute of `Retain` for each resource that you want to keep after the stack instance is deleted. For more information, see [Reverting an import operation](resource-import-revert.md).

1. Delete stack instances from your StackSet. For more information, see [Delete stacks from CloudFormation StackSets](stackinstances-delete.md).

1. Delete your StackSet. For more information, see [Delete CloudFormation StackSets](stacksets-delete.md).

# Best practices for using CloudFormation StackSets
<a name="stacksets-bestpractices"></a>

This section describes the best practices for defining a StackSet template, creating or adding stacks to a StackSet, or updating a StackSet.

If you are new to CloudFormation, review the [CloudFormation best practices](best-practices.md) topic for more recommendations that can help you use CloudFormation more effectively and securely.

**Topics**
+ [Defining the template](#w2aac15c41b9)
+ [Creating or adding stacks to the StackSet](#w2aac15c41c11)
+ [Updating stacks in a StackSet](#w2aac15c41c13)

## Defining the template
<a name="w2aac15c41b9"></a>
+ Define the template that you want to standardize in multiple accounts, within multiple regions.
+ As you create the template, be sure that global resources (such as IAM roles and Amazon S3 buckets) do not have naming conflicts when they are created in more than one region in the same account.
+ A StackSet has a single template and parameter set. The same stack is created in all accounts that are associated with a StackSet. As you author your templates, make them granular enough to allow you a good balance of control and standardization. 
+ We recommend that you store your template in an Amazon S3 bucket.

## Creating or adding stacks to the StackSet
<a name="w2aac15c41c11"></a>
+ Verify that adding stack instances to your initial StackSet works before you add larger numbers of stack instances to your StackSet.
+ Choose the deployment (rollout) options that work for your use case.
  + For a more conservative deployment, set **Maximum Concurrent Accounts** to 1, and **Failure Tolerance** to 0. Set your lowest-impact region to be first in the **Region Order** list. Start with one region.
  + For a faster deployment, increase the values of **Maximum Concurrent Accounts** and **Failure Tolerance** as needed.
+ Operations on StackSets depend on how many stack instances are involved, and can take significant time.

## Updating stacks in a StackSet
<a name="w2aac15c41c13"></a>
+ By default, updating a StackSet updates all stack instances. If you have 20 accounts each in two regions, you will have 40 stack instances, and all will be updated when you update the StackSet.

  For StackSets with a large number of stack instances, we recommend that to test the updated version of a template, you selectively update the stack instances in a few test accounts before updating all stack instances.
+ To get more granular control over updating individual stacks within your StackSet, plan to create multiple StackSets.
+ Updating a StackSet that contains a large number of stacks can take significant time. In this release, only one operation is permitted at a time on a StackSet. Plan your updates so you are not blocked from performing other operations on the StackSet.

# CloudFormation StackSets sample templates
<a name="stacksets-sampletemplates"></a>

This section includes links to some sample CloudFormation templates that can help you use CloudFormation StackSets in your enterprise. Templates listed in this section enable [AWS CloudTrail](https://docs.aws.amazon.com/awscloudtrail/latest/userguide/cloudtrail-user-guide.html) or [AWS Config](https://docs.aws.amazon.com/config/latest/developerguide/WhatIsConfig.html) and rules within it.

**Important**  
As a security best practice when allowing AWS Config access to an Amazon S3 bucket, we strongly recommend that you restrict access in the bucket policy with the `AWS:SourceAccount` condition. New templates are updated to have `AWS:SourceAccount`. If your existing bucket policy does not follow this security best practice, we strongly recommend you edit that bucket policy to include this protection. This makes sure that AWS Config is granted access on behalf of expected users only. 


| Description | S3 link | 
| --- | --- | 
| Enable AWS CloudTrail | [https://s3.amazonaws.com/cloudformation-stackset-sample-templates-us-east-1/EnableAWSCloudtrail.yml](https://s3.amazonaws.com/cloudformation-stackset-sample-templates-us-east-1/EnableAWSCloudtrail.yml) | 
| Enable AWS Config | [https://s3.amazonaws.com/cloudformation-stackset-sample-templates-us-east-1/EnableAWSConfig.yml](https://s3.amazonaws.com/cloudformation-stackset-sample-templates-us-east-1/EnableAWSConfig.yml) | 
| Enable AWS Config with central logging | [https://s3.amazonaws.com/cloudformation-stackset-sample-templates-us-east-1/EnableAWSConfigForOrganizations.yml](https://s3.amazonaws.com/cloudformation-stackset-sample-templates-us-east-1/EnableAWSConfigForOrganizations.yml) | 
| Enable Amazon Data Lifecycle Manager default policies across an AWS organization or across specific AWS accounts |  [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/stacksets-sampletemplates.html) [https://s3.amazonaws.com/cloudformation-stackset-sample-templates-us-east-1/ConfigRuleEncryptedVolumes.yml](https://s3.amazonaws.com/cloudformation-stackset-sample-templates-us-east-1/ConfigRuleEncryptedVolumes.yml) | 
| Configure an AWS Config rule to determine if CloudTrail is enabled | [https://s3.amazonaws.com/cloudformation-stackset-sample-templates-us-east-1/ConfigRuleCloudtrailEnabled.yml](https://s3.amazonaws.com/cloudformation-stackset-sample-templates-us-east-1/ConfigRuleCloudtrailEnabled.yml) | 
| Configure an AWS Config rule to determine if root MFA is enabled | [https://s3.amazonaws.com/cloudformation-stackset-sample-templates-us-east-1/ConfigRuleRootAccountMFAEnabled.yml](https://s3.amazonaws.com/cloudformation-stackset-sample-templates-us-east-1/ConfigRuleRootAccountMFAEnabled.yml) | 
| Configure an AWS Config rule to determine if EIPs are attached | [https://s3.amazonaws.com/cloudformation-stackset-sample-templates-us-east-1/ConfigRuleEipAttached.yml](https://s3.amazonaws.com/cloudformation-stackset-sample-templates-us-east-1/ConfigRuleEipAttached.yml) | 
| Configure an AWS Config rule to determine if EBS volumes are encrypted | [https://s3.amazonaws.com/cloudformation-stackset-sample-templates-us-east-1/ConfigRuleEncryptedVolumes.yml](https://s3.amazonaws.com/cloudformation-stackset-sample-templates-us-east-1/ConfigRuleEncryptedVolumes.yml) | 

# Troubleshooting CloudFormation StackSets
<a name="stacksets-troubleshooting"></a>

This topic contains some common StackSets issues, and suggested solutions for those issues.

**Topics**
+ [Common reasons for stack operation failure](#common-reasons-for-stack-operation-failure)
+ [Retrying failed stack creation or update operations](#retrying-failed-stack-creation-or-update-operations)
+ [Stack instance deletion fails](#stack-instance-delete-fails)
+ [Stack import operation fails](#stack-import-fails)
+ [Stack instance failure count for StackSets operations](#stack-instance-failure-count-for-stackset-operations)

## Common reasons for stack operation failure
<a name="common-reasons-for-stack-operation-failure"></a>

**Problem:** A stack operation failed, and the stack instance status is `OUTDATED`.

**Cause:** There can be several common causes for stack operation failure.
+ Insufficient permissions in a target account for creating resources that are specified in your template.
+ The CloudFormation template might have errors. Validate the template in CloudFormation and fix errors before trying to create your StackSet.
+ The template could be trying to create global resources that must be unique but aren't, such as S3 buckets.
+ A specified target account number doesn't exist. Check the target account numbers that you specified on the **Set deployment options** page of the wizard.
+ The administrator account does not have a trust relationship with the target account.
+ The maximum number of a resource that is specified in your template already exists in your target account. For example, you might have reached the limit of allowed IAM roles in a target account, but the template creates more IAM roles.
+ You have reached the maximum number of stacks that are allowed in a StackSet. For the maximum number of stacks per StackSet, see [Understand CloudFormation quotas](cloudformation-limits.md).

**Solution:** For more information about the permissions required of target and administrator accounts before you can create StackSets, see [Give all users of the administrator account permissions to manage stacks in all target accounts](stacksets-prereqs-self-managed.md#stacksets-prereqs-accountsetup).

## Retrying failed stack creation or update operations
<a name="retrying-failed-stack-creation-or-update-operations"></a>

**Problem:** A stack creation or update failed, and the stack instance status is `OUTDATED`. To troubleshoot why a stack creation or update failed, open the CloudFormation console, and view the events for the stack, which will have a status of `DELETED` (for failed create operations) or `FAILED` (for failed update operations). Browse the stack events, and find the **Status reason** column. The value of **Status reason** explains why the stack operation failed.

After you have fixed the underlying cause of the stack creation failure, and you are ready to retry stack creation, perform the following steps.

**Solution:** Perform the following steps to retry your stack operation.

1. In the console, select the StackSet that contains the stack on which the operation failed.

1. In the **Actions** menu, choose **Edit StackSet details** to retry creating or updating stacks.

1. On the **Specify template** page, to use the same CloudFormation template, keep the default option, **Use current template**. If your stack operation failed because the template required changes, and you want to upload a revised template, choose **Upload a template to Amazon S3** instead, and then choose **Browse** to select your updated template. When you are finished uploading your revised template, choose **Next**.

1. On the **Specify stack details** page, if you are not changing any parameters that are specific to your template, choose **Next**.

1. On the **Set deployment options** page, change defaults for **Maximum concurrent accounts** and **Failure tolerance**, if desired. For more information about these settings, see [StackSet operation options](stacksets-concepts.md#stackset-ops-options).

1. On the **Review** page, review your selections, and fill the checkbox to acknowledge required IAM capabilities. Choose **Submit**.

1. If your stack is not successfully updated, repeat this procedure, after you've resolved any underlying issues that are preventing stack creation.

## Stack instance deletion fails
<a name="stack-instance-delete-fails"></a>

**Problem:** A stack deletion has failed.

**Cause:** Stack deletion will fail for any stacks on which termination protection has been enabled.

**Solution:** Determine if termination protection has been enabled for the stack. If it has, disable termination protection and then perform the stack instance deletion again.

## Stack import operation fails
<a name="stack-import-fails"></a>

**Problem:** A stack import operation fails to import existing stacks into new or existing StackSets. The stack instance is in an `INOPERABLE` status.

**Solution:** Revert the stack import operation, by completing the following tasks.

1. Use **Delete Stacks from StackSets** option and enable **RetainStacks** during configuration, then proceed to delete stack instances from your StackSet. For more information, For more information, see [Delete stacks from CloudFormation StackSets](stackinstances-delete.md).

1. You will see the stack instances of the StackSet are updated to remove the `INOPERABLE` stack instance.

1. Fix the stack instances according to the import failure error and retry the stack import operation.

## Stack instance failure count for StackSets operations
<a name="stack-instance-failure-count-for-stackset-operations"></a>

The stack instance failure count alerts you if stack instances fail to provision or update. These stack instances didn't deploy because of one or more of the following reasons:
+ Existing resource(s) with a similar configuration
+ Missing dependencies, such as AWS Identity and Access Management (IAM) roles
+ Other conflicting factors

If you want to deploy with maximum concurrency, max concurrency count is one more than the failure tolerance count, at most. For example, if the failure tolerance count is 9, then max concurrency count can’t be more than 10. This will cause the operation to return `SUCCEEDED` even if some stack instances fail to update. The new stack instance failure count enables you to determine if the operation only conditionally succeeded because the failure tolerance count is set to allow all failures.

You can use the AWS Management Console, AWS SDK, or AWS CLI to get the failure count and filter stack instances to determine which instances need to be redeployed.

### Using the console
<a name="stack-instance-failure-count-for-stackset-operations-console-examples"></a>

**To view the number of failed stack instances:**

1. Open the [CloudFormation console](https://console.aws.amazon.com/cloudformation) and choose **StackSets**.

1. Choose your StackSet, and then choose the **Operations** tab.

1. Choose a status in the **Status** column to view the status details. You will find the number of failed stack instances for a particular operation in the status details.

**To view the account, region, and status of stack instances for the operation:**

1. In the status details, choose the failed stack instances count. *Example:* **Stack instances: `<number of failed stack instances>`**.

1. Expand the side panel by choosing the panel header. The results in the side panel are the statuses of the stack instances after the completion of the selected operation.

**To view the current stack instance details for an operation:**

1. Choose the **Stack Instances** tab.

1. Filter by **Last operation ID**. The results are the current statuses and status reasons from the last operation to modify the instance. You can use this filter in combination with **AWS account**, **AWS region**, **Detailed Status**, and **Drift status** to further refine your search results.

### Using the AWS CLI
<a name="stack-instance-failure-count-for-stackset-operations-cli-examples"></a>

To get the number of failed stack instances, call `describe-stack-set-operation` or `list-stack-set-operations` and see `StatusDetails`.

```
aws cloudformation describe-stack-set-operation --stack-set-name ss1 \
    --operation-id 5550e62f-c822-4331-88fa-21c1d7bafc60
```

```
{
    "StackSetOperation": {
        "OperationId": "5550e62f-c822-4331-88fa-21c1d7bafc60",
        "StackSetId": "ss1:9101ca57-49fc-4a61-a5a6-4c97b8adb08f",
        "Action": "CREATE",
        "Status": "SUCCEEDED",
        "OperationPreferences": {
            "RegionOrder": [],
            "FailureToleranceCount": 10,
            "MaxConcurrentCount": 10
        },
        "AdministrationRoleARN": "arn:aws:iam::123456789012:role/AWSCloudFormationStackSetAdministrationRole",
        "ExecutionRoleName": "AWSCloudFormationStackSetExecutionRole",
        "CreationTimestamp": "2022-10-26T17:18:53.947000+00:00",
        "EndTimestamp": "2022-10-26T17:19:35.304000+00:00",
        "StatusDetails": {
            "FailedStackInstancesCount": 3
        }
    }
}
```

```
aws cloudformation list-stack-set-operations --stack-set-name ss1
```

```
{
    "Summaries": [
        {
            "OperationId": "5550e62f-c822-4331-88fa-21c1d7bafc60",
            "Action": "CREATE",
            "Status": "SUCCEEDED",
            "CreationTimestamp": "2022-10-26T17:18:53.947000+00:00",
            "EndTimestamp": "2022-10-26T17:19:35.304000+00:00",
            "StatusDetails": {
                "FailedStackInstancesCount": 3
            },
            "OperationPreferences": {
                "RegionOrder": [],
                "FailureToleranceCount": 10,
                "MaxConcurrentCount": 10
            }
        }
    ]
}
```

To get a historical overview for a particular operation, use `list-stack-set-operation-results` to view the status and status reason for each stack instance after the operation completed. See the following example to find the `Status` and `StatusReason`:

```
aws cloudformation list-stack-set-operation-results --stack-set-name ss1 \
  --operation-id 5550e62f-c822-4331-88fa-21c1d7bafc60 --filters Name=OPERATION_RESULT_STATUS,Values=FAILED
```

```
{
    "Summaries": [
        {
            "Account": "123456789012",
            "Region": "us-west-2",
            "Status": "FAILED",
            "StatusReason": "Account 123456789012 should have 'AWSCloudFormationStackSetExecutionRole' role with trust relationship to Role 'AWSCloudFormationStackSetAdministrationRole'.",
            "AccountGateResult": {
                "Status": "SKIPPED",
                "StatusReason": "Account 123456789012 should have 'AWSCloudFormationStackSetExecutionRole' role with trust relationship to Role 'AWSCloudFormationStackSetAdministrationRole'."
            },
            "OrganizationalUnitId": ""
        },
        {
            "Account": "123456789012",
            "Region": "us-west-1",
            "Status": "FAILED",
            "StatusReason": "Account 123456789012 should have 'AWSCloudFormationStackSetExecutionRole' role with trust relationship to Role 'AWSCloudFormationStackSetAdministrationRole'.",
            "AccountGateResult": {
                "Status": "SKIPPED",
                "StatusReason": "Account 123456789012 should have 'AWSCloudFormationStackSetExecutionRole' role with trust relationship to Role 'AWSCloudFormationStackSetAdministrationRole'."
            },
            "OrganizationalUnitId": ""
        },
        {
            "Account": "123456789012",
            "Region": "us-east-1",
            "Status": "FAILED",
            "StatusReason": "Account 123456789012 should have 'AWSCloudFormationStackSetExecutionRole' role with trust relationship to Role 'AWSCloudFormationStackSetAdministrationRole'.",
            "AccountGateResult": {
                "Status": "SKIPPED",
                "StatusReason": "Account 123456789012 should have 'AWSCloudFormationStackSetExecutionRole' role with trust relationship to Role 'AWSCloudFormationStackSetAdministrationRole'."
            },
            "OrganizationalUnitId": ""
        }
    ]
}
```

Use `list-stack-instances` with the `DETAILED_STATUS` and `LAST_OPERATION_ID` filters to get a list of stack instances that failed in the last operation that tried to deploy the stack instance. See the `--filters` flag in the example with `DETAILED_STATUS` and `LAST_OPERATION_ID`:

```
aws cloudformation list-stack-instances --stack-set-name ss1 \
  --filters Name=DETAILED_STATUS,Values=FAILED Name=LAST_OPERATION_ID,Values=5550e62f-c822-4331-88fa-21c1d7bafc60
```

```
{
    "Summaries": [
        {
            "StackSetId": "ss1:9101ca57-49fc-4a61-a5a6-4c97b8adb08f",
            "Region": "us-east-1",
            "Account": "123456789012",
            "Status": "OUTDATED",
            "StatusReason": "Account 123456789012 should have 'AWSCloudFormationStackSetExecutionRole' role with trust relationship to Role 'AWSCloudFormationStackSetAdministrationRole'.",
            "StackInstanceStatus": {
                "DetailedStatus": "FAILED"
            },
            "OrganizationalUnitId": "",
            "DriftStatus": "NOT_CHECKED",
            "LastOperationId": "5550e62f-c822-4331-88fa-21c1d7bafc60"
        },
        {
            "StackSetId": "ss1:9101ca57-49fc-4a61-a5a6-4c97b8adb08f",
            "Region": "us-west-1",
            "Account": "123456789012",
            "Status": "OUTDATED",
            "StatusReason": "Account 123456789012 should have 'AWSCloudFormationStackSetExecutionRole' role with trust relationship to Role 'AWSCloudFormationStackSetAdministrationRole'.",
            "StackInstanceStatus": {
                "DetailedStatus": "FAILED"
            },
            "OrganizationalUnitId": "",
            "DriftStatus": "NOT_CHECKED",
            "LastOperationId": "5550e62f-c822-4331-88fa-21c1d7bafc60"
        },
        {
            "StackSetId": "ss1:9101ca57-49fc-4a61-a5a6-4c97b8adb08f",
            "Region": "us-west-2",
            "Account": "123456789012",
            "Status": "OUTDATED",
            "StatusReason": "Account 123456789012 should have 'AWSCloudFormationStackSetExecutionRole' role with trust relationship to Role 'AWSCloudFormationStackSetAdministrationRole'.",
            "StackInstanceStatus": {
                "DetailedStatus": "FAILED"
            },
            "OrganizationalUnitId": "",
            "DriftStatus": "NOT_CHECKED",
            "LastOperationId": "5550e62f-c822-4331-88fa-21c1d7bafc60"
        }
    ]
}
```

To find the last operation ID to modify a stack instance, use `list-stack-instances` or `describe-stack-instance` to get the `LastOperationId`:

```
aws cloudformation describe-stack-instance --stack-set-name ss1 \
  --stack-instance-account 123456789012 --stack-instance-region us-east-2
```

```
{
    "StackInstance": {
        "StackSetId": "ss1:9101ca57-49fc-4a61-a5a6-4c97b8adb08f",
        "Region": "us-west-2",
        "Account": "123456789012",
        "ParameterOverrides": [],
        "Status": "OUTDATED",
        "StackInstanceStatus": {
            "DetailedStatus": "FAILED"
        },
        "StatusReason": "Account 123456789012 should have 'AWSCloudFormationStackSetExecutionRole' role with trust relationship to Role 'AWSCloudFormationStackSetAdministrationRole'.",
        "OrganizationalUnitId": "",
        "DriftStatus": "NOT_CHECKED",
        "LastOperationId": "5550e62f-c822-4331-88fa-21c1d7bafc60"
    }
}
```