

This is the new *CloudFormation Template Reference Guide*. Please update your bookmarks and links. For help getting started with CloudFormation, see the [AWS CloudFormation User Guide](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/Welcome.html).

# Resource attribute reference
<a name="aws-product-attribute-reference"></a>

This section details the attributes that you can add to a resource to control additional behaviors and relationships.

**Topics**
+ [

# `CreationPolicy` attribute
](aws-attribute-creationpolicy.md)
+ [

# `Condition` attribute
](aws-attribute-condition.md)
+ [

# `DeletionPolicy` attribute
](aws-attribute-deletionpolicy.md)
+ [

# `DependsOn` attribute
](aws-attribute-dependson.md)
+ [

# `Metadata` attribute
](aws-attribute-metadata.md)
+ [

# `UpdatePolicy` attribute
](aws-attribute-updatepolicy.md)
+ [

# `UpdateReplacePolicy` attribute
](aws-attribute-updatereplacepolicy.md)

# `CreationPolicy` attribute
<a name="aws-attribute-creationpolicy"></a>

Associate the `CreationPolicy` attribute with a resource to prevent its status from reaching create complete until CloudFormation receives a specified number of success signals or the timeout period is exceeded. To signal a resource, you can use the [cfn-signal](cfn-signal.md) helper script or [https://docs.aws.amazon.com/AWSCloudFormation/latest/APIReference/API_SignalResource.html](https://docs.aws.amazon.com/AWSCloudFormation/latest/APIReference/API_SignalResource.html) API. CloudFormation publishes valid signals to the stack events so that you track the number of signals sent.

The creation policy is invoked only when CloudFormation creates the associated resource. Currently, the only CloudFormation resources that support creation policies are:
+ [https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/aws-resource-appstream-fleet.html](https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/aws-resource-appstream-fleet.html)
+ [https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/aws-resource-autoscaling-autoscalinggroup.html](https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/aws-resource-autoscaling-autoscalinggroup.html)
+ [https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/aws-resource-ec2-instance.html](https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/aws-resource-ec2-instance.html)
+ [https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/aws-resource-cloudformation-waitcondition.html](https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/aws-resource-cloudformation-waitcondition.html)

Use the `CreationPolicy` attribute when you want to wait on resource configuration actions before stack creation proceeds. For example, if you install and configure software applications on an EC2 instance, you might want those applications to be running before proceeding. In such cases, you can add a `CreationPolicy` attribute to the instance, and then send a success signal to the instance after the applications are installed and configured. For a detailed example, see [Deploying applications on Amazon EC2 with CloudFormation](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/deploying.applications.html) in the *AWS CloudFormation User Guide*.

## WorkSpaces Applications creation policy
<a name="aws-attribute-creation-policy-app-stream-fleet"></a>

Amazon AppStream configuration for a creation policy.

### Syntax
<a name="aws-attribute-creation-policy-app-stream-fleet-syntax"></a>

#### JSON
<a name="aws-attribute-creation-policy-app-stream-fleet-syntax-json"></a>

```
{
    "CreationPolicy": {
        "StartFleet": "Boolean"
    }
}
```

#### YAML
<a name="aws-attribute-creation-policy-app-stream-fleet-syntax-yaml"></a>

```
CreationPolicy:
  StartFleet: Boolean
```

`StartFleet`  <a name="cfn-attributes-updatepolicy-replacingupdate-StartFleet"></a>
Starts the specified fleet.  
*Required*: No

## Amazon EC2 Auto Scaling creation properties
<a name="w2aac19b7c13"></a>

Amazon EC2 Auto Scaling configuration for a creation policy.

### Syntax
<a name="aws-attribute-creation-policy-app-auto-scaling-syntax"></a>

#### JSON
<a name="aws-attribute-creation-policy-app-auto-scaling-syntax.json"></a>

```
"CreationPolicy" : {
  "AutoScalingCreationPolicy" : {
    "MinSuccessfulInstancesPercent" : Integer
  },
  "ResourceSignal" : {    
    "Count" : Integer,
    "Timeout" : String
  }
}
```

#### YAML
<a name="aws-attribute-creation-policy-app-auto-scaling-syntax.yaml"></a>

```
CreationPolicy:
  AutoScalingCreationPolicy:
    MinSuccessfulInstancesPercent: Integer
  ResourceSignal:    
    Count: Integer
    Timeout: String
```

### Amazon EC2 Auto Scaling creation properties
<a name="cfn-attributes-creationpolicy-properties"></a>

Amazon EC2 Auto Scaling configuration for a creation policy.

`AutoScalingCreationPolicy`  <a name="cfn-attributes-creationpolicy-autoscalingcreationpolicy"></a>
For a new Amazon EC2 Auto Scaling group, specifies the number of instances that must signal success before setting the group's status to `CREATE_COMPLETE`.    
`MinSuccessfulInstancesPercent`  <a name="cfn-attributes-creationpolicy-autoscalingcreationpolicy-minsuccessfulinstancespercent"></a>
Specifies the percentage of instances in an Amazon EC2 Auto Scaling that must signal success before setting the group's status to `CREATE_COMPLETE`. You can specify a value from `0` to `100`. CloudFormation rounds to the nearest tenth of a percent. For example, if you create five instances with a minimum successful percentage of `50`, three instances must signal success. If an instance doesn't send a signal within the time specified by the `Timeout` property, CloudFormation assumes that the instance wasn't created.  
*Default*: `100`  
*Type*: Integer  
*Required*: No

`ResourceSignal`  <a name="cfn-attributes-creationpolicy-resourcesignal"></a>
When CloudFormation creates the associated resource, configures the number of required success signals and the length of time that CloudFormation waits for those signals.    
`Count`  <a name="cfn-attributes-creationpolicy-resourcesignal-count"></a>
The number of success signals CloudFormation must receive before it sets the resource status as `CREATE_COMPLETE`. If the resource receives a failure signal or doesn't receive the specified number of signals before the timeout period expires, the resource creation fails and CloudFormation rolls the stack back.  
*Default*: `1`  
*Type*: Integer  
*Required*: No  
`Timeout`  <a name="cfn-attributes-creationpolicy-resourcesignal-timeout"></a>
The length of time that CloudFormation waits for the number of signals that was specified in the `Count` property. The timeout period starts after CloudFormation stabilizes the resource, and the timeout expires no sooner than the time you specify but can occur shortly thereafter. The maximum time that you can specify is 12 hours.  
The value must be in [ISO8601 duration format](https://en.wikipedia.org/wiki/ISO_8601#Durations), in the form: `PT#H#M#S`, where each *\$1* is the number of hours, minutes, and seconds, respectively. For best results, specify a period of time that gives your instances plenty of time to get up and running. A shorter timeout can cause a rollback.  
*Default*: `PT5M` (5 minutes)  
*Type*: String  
*Required*: No

## Examples
<a name="aws-attribute-creation-policy-examples"></a>

### Auto Scaling group
<a name="aws-attribute-creation-policy-as-group"></a>

The following example shows how to add a creation policy to an Amazon EC2 Auto Scaling group. The creation policy requires three success signals and times out after 15 minutes. Use the [cfn-signal](cfn-signal.md) helper script to signal when an instance creation process has completed successfully.

To have instances wait for an Elastic Load Balancing health check before they signal success, add a health-check verification by using the [cfn-init](cfn-init.md) helper script. For an example, see the `verify_instance_health` command in the sample templates for Amazon EC2 Auto Scaling rolling updates in our [GitHub repository](https://github.com/aws-cloudformation/aws-cloudformation-templates/tree/main/AutoScaling).

#### JSON
<a name="aws-attribute-creationpolicy-example-1.json"></a>

```
"AutoScalingGroup": {
  "Type": "AWS::AutoScaling::AutoScalingGroup",
  "Properties": {
    "VPCZoneIdentifier":[ "subnetIdAz1", "subnetIdAz2", "subnetIdAz3" ],
    "LaunchTemplate":{
      "LaunchTemplateId":{
        "Ref":"logicalName"
      },
      "Version":{
        "Fn::GetAtt":[
          "logicalName",
          "LatestVersionNumber"
        ]
      }
    },
    "MinSize": "1",
    "MaxSize": "4"
  },
  "CreationPolicy": {
    "ResourceSignal": {
      "Count": "3",
      "Timeout": "PT15M"
    }
  }
}
```

#### YAML
<a name="aws-attribute-creationpolicy-example-1.yaml"></a>

```
AutoScalingGroup:
  Type: AWS::AutoScaling::AutoScalingGroup
  Properties:
    VPCZoneIdentifier:
      - subnetIdAz1
      - subnetIdAz2
      - subnetIdAz3
    LaunchTemplate:
      LaunchTemplateId: !Ref logicalName
      Version: !GetAtt logicalName.LatestVersionNumber
    MinSize: '1'
    MaxSize: '4'
  CreationPolicy:
    ResourceSignal:
      Count: '3'
      Timeout: PT15M
```

### WaitCondition
<a name="w2aac19b7c15b5"></a>

The following example shows how to add a creation policy to a wait condition for CloudFormation resources beyond Amazon EC2.

To signal the `WaitCondition` resource, use the [https://docs.aws.amazon.com/AWSCloudFormation/latest/APIReference/API_SignalResource.html](https://docs.aws.amazon.com/AWSCloudFormation/latest/APIReference/API_SignalResource.html) API. This API is designed to work with `WaitCondition` resources that you configure using a `CreationPolicy`.

#### JSON
<a name="aws-attribute-creationpolicy-example-2.json"></a>

```
"WaitCondition" : {
    "Type" : "AWS::CloudFormation::WaitCondition",
    "CreationPolicy" : {
        "ResourceSignal" : {
            "Timeout" : "PT15M",
            "Count" : "5"
        }
    }
}
```

#### YAML
<a name="aws-attribute-creationpolicy-example-2.yaml"></a>

```
WaitCondition:
  Type: AWS::CloudFormation::WaitCondition
  CreationPolicy:
    ResourceSignal:
      Timeout: PT15M
      Count: 5
```

# `Condition` attribute
<a name="aws-attribute-condition"></a>

To create resources in CloudFormation based on conditions, first declare your condition in the template's `Conditions` section. Then, use the `Condition` key along with the condition's logical ID as an attribute on the resource. CloudFormation creates the resource only when the condition evaluates to true. This lets you control resource creation based on specific criteria or parameters you define in your template.

If you're new to using conditions in your templates, we recommend you first review the [CloudFormation template Conditions syntax](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/conditions-section-structure.html) topic in the *AWS CloudFormation User Guide*.

**Note**  
If a resource with a condition isn't created, any resources that depend on that resource aren't created either, regardless of their own conditions.

## Example
<a name="aws-attribute-condition-example"></a>

The following template contains an Amazon S3 bucket resource with a `Condition` attribute. The bucket is only created if the `CreateBucket` condition evaluates to `true`.

### JSON
<a name="aws-attribute-condition-example.json"></a>

```
{
   "AWSTemplateFormatVersion" : "2010-09-09",
   "Parameters" : {
      "EnvType" : {
         "Type" : "String",
         "AllowedValues" : ["prod", "dev"],
         "Default" : "dev",
         "Description" : "Environment type"
      }
   },
   "Conditions" : {
      "CreateBucket" : {"Fn::Equals" : [{"Ref" : "EnvType"}, "prod"]}
   },
   "Resources" : {
      "MyBucket" : {
         "Type" : "AWS::S3::Bucket",
         "Condition" : "CreateBucket",
         "Properties" : {
            "BucketName" : {"Fn::Join" : ["-", ["mybucket", {"Ref" : "EnvType"}]]}
         }
      }
   }
}
```

### YAML
<a name="aws-attribute-condition-example.yaml"></a>

```
 1. AWSTemplateFormatVersion: 2010-09-09
 2. Parameters:
 3.   EnvType:
 4.     Type: String
 5.     AllowedValues:
 6.       - prod
 7.       - dev
 8.     Default: dev
 9.     Description: Environment type
10. Conditions:
11.   CreateBucket: !Equals [!Ref EnvType, prod]
12. Resources:
13.   MyBucket:
14.     Type: AWS::S3::Bucket
15.     Condition: CreateBucket
16.     Properties:
17.       BucketName: !Sub mybucket-${EnvType}
```

## Using multiple conditions
<a name="aws-attribute-condition-multiple"></a>

You can combine multiple conditions using intrinsic functions like [`Fn::And`](intrinsic-function-reference-conditions.md#intrinsic-function-reference-conditions-and), [`Fn::Or`](intrinsic-function-reference-conditions.md#intrinsic-function-reference-conditions-or), and [`Fn::Not`](intrinsic-function-reference-conditions.md#intrinsic-function-reference-conditions-not) to create more complex conditional logic.

### JSON
<a name="aws-attribute-condition-multiple.json"></a>

```
{
   "AWSTemplateFormatVersion" : "2010-09-09",
   "Parameters" : {
      "EnvType" : {
         "Type" : "String",
         "AllowedValues" : ["prod", "test", "dev"],
         "Default" : "dev",
         "Description" : "Environment type"
      },
      "CreateResources" : {
         "Type" : "String",
         "AllowedValues" : ["true", "false"],
         "Default" : "true",
         "Description" : "Create resources flag"
      }
   },
   "Conditions" : {
      "IsProd" : {"Fn::Equals" : [{"Ref" : "EnvType"}, "prod"]},
      "IsTest" : {"Fn::Equals" : [{"Ref" : "EnvType"}, "test"]},
      "CreateResourcesFlag" : {"Fn::Equals" : [{"Ref" : "CreateResources"}, "true"]},
      "CreateProdResources" : {"Fn::And" : [{"Condition" : "IsProd"}, {"Condition" : "CreateResourcesFlag"}]},
      "CreateTestOrDevResources" : {"Fn::And" : [{"Fn::Or" : [{"Condition" : "IsTest"}, {"Fn::Not" : [{"Condition" : "IsProd"}]}]}, {"Condition" : "CreateResourcesFlag"}]}
   },
   "Resources" : {
      "ProdBucket" : {
         "Type" : "AWS::S3::Bucket",
         "Condition" : "CreateProdResources",
         "Properties" : {
            "BucketName" : {"Fn::Join" : ["-", ["prod-bucket", {"Ref" : "AWS::StackName"}]]}
         }
      },
      "TestDevBucket" : {
         "Type" : "AWS::S3::Bucket",
         "Condition" : "CreateTestOrDevResources",
         "Properties" : {
            "BucketName" : {"Fn::Join" : ["-", [{"Ref" : "EnvType"}, "bucket", {"Ref" : "AWS::StackName"}]]}
         }
      }
   }
}
```

### YAML
<a name="aws-attribute-condition-multiple.yaml"></a>

```
 1. AWSTemplateFormatVersion: 2010-09-09
 2. Parameters:
 3.   EnvType:
 4.     Type: String
 5.     AllowedValues:
 6.       - prod
 7.       - test
 8.       - dev
 9.     Default: dev
10.     Description: Environment type
11.   CreateResources:
12.     Type: String
13.     AllowedValues:
14.       - 'true'
15.       - 'false'
16.     Default: 'true'
17.     Description: Create resources flag
18. Conditions:
19.   IsProd: !Equals [!Ref EnvType, prod]
20.   IsTest: !Equals [!Ref EnvType, test]
21.   CreateResourcesFlag: !Equals [!Ref CreateResources, 'true']
22.   CreateProdResources: !And
23.     - !Condition IsProd
24.     - !Condition CreateResourcesFlag
25.   CreateTestOrDevResources: !And
26.     - !Or
27.       - !Condition IsTest
28.       - !Not [!Condition IsProd]
29.     - !Condition CreateResourcesFlag
30. Resources:
31.   ProdBucket:
32.     Type: AWS::S3::Bucket
33.     Condition: CreateProdResources
34.     Properties:
35.       BucketName: !Sub prod-bucket-${AWS::StackName}
36.   TestDevBucket:
37.     Type: AWS::S3::Bucket
38.     Condition: CreateTestOrDevResources
39.     Properties:
40.       BucketName: !Sub ${EnvType}-bucket-${AWS::StackName}
```

## Using `AWS::AccountId` in conditions
<a name="aws-attribute-condition-account"></a>

You can use pseudo parameters like `AWS::AccountId` in your conditions to create resources based on the AWS account where the stack is being deployed. This is useful for multi-account deployments or when you need to exclude specific accounts from receiving certain resources. For more information about pseudo parameters, see [Get AWS values using pseudo parameters](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/pseudo-parameter-reference.html) in the *AWS CloudFormation User Guide*.

### JSON
<a name="aws-attribute-condition-account.json"></a>

```
{
   "AWSTemplateFormatVersion" : "2010-09-09",
   "Conditions" : {
      "ExcludeAccount1" : {"Fn::Not" : [{"Fn::Equals" : [{"Ref" : "AWS::AccountId"}, "111111111111"]}]},
      "ExcludeAccount2" : {"Fn::Not" : [{"Fn::Equals" : [{"Ref" : "AWS::AccountId"}, "222222222222"]}]},
      "ExcludeBothAccounts" : {"Fn::And" : [{"Condition" : "ExcludeAccount1"}, {"Condition" : "ExcludeAccount2"}]}
   },
   "Resources" : {
      "StandardBucket" : {
         "Type" : "AWS::S3::Bucket",
         "Properties" : {
            "BucketName" : {"Fn::Join" : ["-", ["standard-bucket", {"Ref" : "AWS::StackName"}]]}
         }
      },
      "RestrictedResource" : {
         "Type" : "AWS::SNS::Topic",
         "Condition" : "ExcludeBothAccounts",
         "Properties" : {
            "TopicName" : {"Fn::Join" : ["-", ["restricted-topic", {"Ref" : "AWS::StackName"}]]}
         }
      }
   }
}
```

### YAML
<a name="aws-attribute-condition-account.yaml"></a>

```
 1. AWSTemplateFormatVersion: 2010-09-09
 2. Conditions:
 3.   ExcludeAccount1: !Not [!Equals [!Ref 'AWS::AccountId', '111111111111']]
 4.   ExcludeAccount2: !Not [!Equals [!Ref 'AWS::AccountId', '222222222222']]
 5.   ExcludeBothAccounts: !And
 6.     - !Condition ExcludeAccount1
 7.     - !Condition ExcludeAccount2
 8. Resources:
 9.   StandardBucket:
10.     Type: AWS::S3::Bucket
11.     Properties:
12.       BucketName: !Sub standard-bucket-${AWS::StackName}
13.   RestrictedResource:
14.     Type: AWS::SNS::Topic
15.     Condition: ExcludeBothAccounts
16.     Properties:
17.       TopicName: !Sub restricted-topic-${AWS::StackName}
```

# `DeletionPolicy` attribute
<a name="aws-attribute-deletionpolicy"></a>

With the `DeletionPolicy` attribute you can preserve, and in some cases, backup a resource when its stack is deleted. You specify a `DeletionPolicy` attribute for each resource that you want to control. If a resource has no `DeletionPolicy` attribute, CloudFormation deletes the resource by default.

This capability also applies to stack update operations that lead to resources being deleted from stacks. For example, if you remove the resource from the stack template, and then update the stack with the template. This capability doesn't apply to resources whose physical instance is replaced during stack update operations. For example, if you edit a resource's properties such that CloudFormation replaces that resource during a stack update.

**Note**  
**Exception**: The default policy is `Snapshot` for `AWS::RDS::DBCluster` resources and for `AWS::RDS::DBInstance` resources that don't specify the `DBClusterIdentifier` property.

To keep a resource when its stack is deleted, specify `Retain` for that resource. You can use `Retain` for any resource. For example, you can retain a nested stack, Amazon S3 bucket, or EC2 instance so that you can continue to use or modify those resources after you delete their stacks.

**Note**  
If you want to modify resources outside of CloudFormation, use a `Retain` deletion policy and then delete the stack. Otherwise, your resources might get out of sync with your CloudFormation template and cause stack errors.

For resources that support snapshots, such as `AWS::EC2::Volume`, specify `Snapshot` to have CloudFormation create a snapshot before deleting the resource.

The following snippet contains an Amazon S3 bucket resource with a `Retain` deletion policy. When this stack is deleted, CloudFormation leaves the bucket without deleting it.

## JSON
<a name="aws-attribute-deletionpolicy-example.json"></a>

```
{
  "AWSTemplateFormatVersion" : "2010-09-09",
  "Resources" : {
    "MyBucket" : {
      "Type" : "AWS::S3::Bucket",
      "DeletionPolicy" : "Retain"
    }
  }
}
```

## YAML
<a name="aws-attribute-deletionpolicy-example.yaml"></a>

```
AWSTemplateFormatVersion: '2010-09-09'
Resources:
  MyBucket:
    Type: AWS::S3::Bucket
    DeletionPolicy: Retain
```

## `DeletionPolicy` options
<a name="aws-attribute-deletionpolicy-options"></a>

`Delete`  
CloudFormation deletes the resource and all its content if applicable during stack deletion. You can add this deletion policy to any resource type. By default, if you don't specify a `DeletionPolicy`, CloudFormation deletes your resources. However, be aware of the following considerations:  
+ For `AWS::RDS::DBCluster` resources, the default policy is `Snapshot`.
+ For `AWS::RDS::DBInstance` resources that don't specify the `DBClusterIdentifier` property, the default policy is `Snapshot`.
+ For Amazon S3 buckets, you must delete all objects in the bucket for deletion to succeed.
The default behavior of CloudFormation is to delete the secret with the ForceDeleteWithoutRecovery flag.

`Retain`  
CloudFormation keeps the resource without deleting the resource or its contents when its stack is deleted. You can add this deletion policy to any resource type. When CloudFormation completes the stack deletion, the stack will be in `Delete_Complete` state; however, resources that are retained continue to exist and continue to incur applicable charges until you delete those resources.  
For update operations, the following considerations apply:  
+ If a resource is deleted, the `DeletionPolicy` retains the physical resource but ensures that it's deleted from CloudFormation's scope.
+ If a resource is updated such that a new physical resource is created to replace the old resource, then the old resource is completely deleted, including from CloudFormation's scope.

`RetainExceptOnCreate`  
`RetainExceptOnCreate` behaves like `Retain` for stack operations, except for the stack operation that initially created the resource. If the stack operation that created the resource is rolled back, CloudFormation deletes the resource. For all other stack operations, such as stack deletion, CloudFormation retains the resource and its contents. The result is that new, empty, and unused resources are deleted, while in-use resources and their data are retained. Refer to the [UpdateStack](https://docs.aws.amazon.com/AWSCloudFormation/latest/APIReference/API_UpdateStack.html) API documentation to use this deletion policy as an API parameter without updating your template.

`Snapshot`  
For resources that support snapshots, CloudFormation creates a snapshot for the resource before deleting it. When CloudFormation completes the stack deletion, the stack will be in the `Delete_Complete` state; however, the snapshots that are created with this policy continue to exist and continue to incur applicable charges until you delete those snapshots.  
Resources that support snapshots include:  
+ [AWS::DocDB::DBCluster](https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/aws-resource-docdb-dbcluster.html)
+ [AWS::EC2::Volume](https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/aws-resource-ec2-volume.html)
+ [AWS::ElastiCache::CacheCluster](https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/aws-resource-elasticache-cachecluster.html)
+ [AWS::ElastiCache::ReplicationGroup](https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/aws-resource-elasticache-replicationgroup.html)
+ [AWS::Neptune::DBCluster](https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/aws-resource-neptune-dbcluster.html)
+ [AWS::RDS::DBCluster](https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/aws-resource-rds-dbcluster.html)
+ [AWS::RDS::DBInstance](https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/aws-resource-rds-dbinstance.html)
+ [AWS::Redshift::Cluster](https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/aws-resource-redshift-cluster.html)

# `DependsOn` attribute
<a name="aws-attribute-dependson"></a>

With the `DependsOn` attribute you can specify that the creation of a specific resource follows another. When you add a `DependsOn` attribute to a resource, that resource is created only after the creation of the resource specified in the `DependsOn` attribute.

**Important**  
Dependent stacks also have implicit dependencies in the form of target properties `!Ref`, `!GetAtt`, and `!Sub`. For example, if the properties of resource A use a `!Ref` to resource B, the following rules apply:  
Resource B is created before resource A.
Resource A is deleted before resource B.
Resource B is updated before resource A.

You can use the `DependsOn` attribute with any resource. Here are some typical uses:
+ Determine when a wait condition goes into effect. For more information, see [Creating wait conditions in a template](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/using-cfn-waitcondition.html) in the *AWS CloudFormation User Guide*.
+ Declare dependencies for resources that must be created or deleted in a specific order. For example, you must explicitly declare dependencies on gateway attachments for some resources in a VPC. For more information, see [When a `DependsOn` attribute is required](#gatewayattachment).
+ Override default parallelism when creating, updating, or deleting resources. CloudFormation creates, updates, and deletes resources in parallel to the extent possible. It automatically determines which resources in a template can be parallelized and which have dependencies that require other operations to finish first. You can use `DependsOn` to explicitly specify dependencies, which overrides the default parallelism and directs CloudFormation to operate on those resources in a specified order.

**Note**  
During a stack update, resources that depend on updated resources are updated automatically. CloudFormation makes no changes to the automatically updated resources, but, if a stack policy is associated with these resources, your account must have the permissions to update them.

## Syntax
<a name="aws-attribute-dependson-syntax"></a>

The `DependsOn` attribute can take a single string or list of strings.

```
"DependsOn" : [ String, ... ]
```

## Example
<a name="aws-attribute-dependson-example"></a>

The following template contains an [AWS::EC2::Instance](https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/aws-resource-ec2-instance.html) resource with a `DependsOn` attribute that specifies `myDB`, an [AWS::RDS::DBInstance](https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/aws-resource-rds-dbinstance.html). When CloudFormation creates this stack, it first creates `myDB`, then creates `Ec2Instance`.

### JSON
<a name="aws-attribute-dependson-example-1.json"></a>

```
 1. {
 2.     "Resources" : {
 3.         "Ec2Instance" : {
 4.             "Type" : "AWS::EC2::Instance",
 5.             "Properties" : {
 6.                 "ImageId": "{{resolve:ssm:/aws/service/ami-amazon-linux-latest/al2023-ami-kernel-6.1-x86_64}}",
 7.                 "InstanceType": "t2.micro"
 8.             },
 9.             "DependsOn" : "myDB"
10.         },
11.         "myDB" : {
12.             "Type" : "AWS::RDS::DBInstance",
13.             "Properties" : {
14.                "AllocatedStorage" : "5",
15.                "DBInstanceClass" : "db.t2.small",
16.                "Engine" : "MySQL",
17.                "EngineVersion" : "5.5",
18.                "MasterUsername" : "{{resolve:secretsmanager:MySecret:SecretString:username}}",
19.                "MasterUserPassword" : "{{resolve:secretsmanager:MySecret:SecretString:password}}"
20.             }
21.         }
22.     }
23. }
```

### YAML
<a name="aws-attribute-dependson-example-1.yaml"></a>

```
 1. Resources:
 2.   Ec2Instance:
 3.     Type: AWS::EC2::Instance
 4.     Properties:
 5.       ImageId: '{{resolve:ssm:/aws/service/ami-amazon-linux-latest/al2023-ami-kernel-6.1-x86_64}}'
 6.       InstanceType: t2.micro
 7.     DependsOn: myDB
 8.   myDB:
 9.     Type: AWS::RDS::DBInstance
10.     Properties:
11.       AllocatedStorage: '5'
12.       DBInstanceClass: db.t2.small
13.       Engine: MySQL
14.       EngineVersion: '5.5'
15.       MasterUsername: '{{resolve:secretsmanager:MySecret:SecretString:username}}'
16.       MasterUserPassword: '{{resolve:secretsmanager:MySecret:SecretString:password}}'
```

## When a `DependsOn` attribute is required
<a name="gatewayattachment"></a>

VPC-gateway attachment

Some resources in a VPC require a gateway (either an Internet or VPN gateway). If your CloudFormation template defines a VPC, a gateway, and a gateway attachment, any resources that require the gateway are dependent on the gateway attachment. For example, an Amazon EC2 instance with a public IP address is dependent on the VPC-gateway attachment if the `VPC` and `InternetGateway` resources are also declared in the same template.

Currently, the following resources depend on a VPC-gateway attachment when they have an associated public IP address and are in a VPC.
+ Auto Scaling groups
+ Amazon EC2 instances
+ Elastic Load Balancing load balancers
+ Elastic IP addresses
+ Amazon RDS database instances
+ Amazon VPC routes that include the Internet gateway

A VPN gateway route propagation depends on a VPC-gateway attachment when you have a VPN gateway.

The following snippet shows a sample gateway attachment and an Amazon EC2 instance that depends on a gateway attachment:

### JSON
<a name="aws-attribute-dependson-example-2.json"></a>

```
"GatewayToInternet" : {
  "Type" : "AWS::EC2::VPCGatewayAttachment",
  "Properties" : {
    "VpcId" : { 
      "Ref" : "VPC" 
    },
    "InternetGatewayId" : { 
      "Ref" : "InternetGateway" 
    }
  }
},

"EC2Host" : {
  "Type" : "AWS::EC2::Instance",
  "DependsOn" : "GatewayToInternet",
  "Properties" : {
    "InstanceType" : "t2.micro",
    "ImageId": "{{resolve:ssm:/aws/service/ami-amazon-linux-latest/al2023-ami-kernel-6.1-x86_64}}",
    "KeyName"  : { 
      "Ref" : "KeyName" 
    },
    "NetworkInterfaces" : [
      {
        "GroupSet" : [
          { 
            "Ref" : "EC2SecurityGroup" 
          }
        ],
        "AssociatePublicIpAddress" : "true",
        "DeviceIndex" : "0",
        "DeleteOnTermination" : "true",
        "SubnetId" : { 
          "Ref" : "PublicSubnet" 
        }
      }
    ]
  }
}
```

### YAML
<a name="aws-attribute-dependson-example-2.yaml"></a>

```
GatewayToInternet:
  Type: AWS::EC2::VPCGatewayAttachment
  Properties:
    VpcId:
      Ref: VPC
    InternetGatewayId:
      Ref: InternetGateway
EC2Host:
  Type: AWS::EC2::Instance
  DependsOn: GatewayToInternet
  Properties:
    InstanceType: t2.micro
    ImageId: '{{resolve:ssm:/aws/service/ami-amazon-linux-latest/al2023-ami-kernel-6.1-x86_64}}'
    KeyName:
      Ref: KeyName
    NetworkInterfaces:
    - GroupSet:
      - Ref: EC2SecurityGroup
      AssociatePublicIpAddress: 'true'
      DeviceIndex: '0'
      DeleteOnTermination: 'true'
      SubnetId:
        Ref: PublicSubnet
```

### Amazon ECS service and Auto Scaling group
<a name="w2aac19c19c17c19"></a>

When you use Auto Scaling or Amazon Elastic Compute Cloud (Amazon EC2) to create container instances for an Amazon ECS cluster, the Amazon ECS service resource must have a dependency on the Auto Scaling group or Amazon EC2 instances, as shown in the following snippet. That way the container instances are available and associated with the Amazon ECS cluster before CloudFormation creates the Amazon ECS service.

#### JSON
<a name="aws-attribute-dependson-example-3.json"></a>

```
"service": {
  "Type": "AWS::ECS::Service",
  "DependsOn": [
    "ECSAutoScalingGroup"
  ],
  "Properties" : {
    "Cluster": {
      "Ref": "ECSCluster"
    },
    "DesiredCount": "1",
    "LoadBalancers": [
      {
        "ContainerName": "simple-app",
        "ContainerPort": "80",
        "LoadBalancerName" : { 
          "Ref" : "EcsElasticLoadBalancer" 
        }
      }
    ],
    "Role" : {
      "Ref":"ECSServiceRole"
    },
    "TaskDefinition" : {
      "Ref":"taskdefinition"
    }
  }
}
```

#### YAML
<a name="aws-attribute-dependson-example-3.yaml"></a>

```
service:
  Type: AWS::ECS::Service
  DependsOn:
  - ECSAutoScalingGroup
  Properties:
    Cluster:
      Ref: ECSCluster
    DesiredCount: 1
    LoadBalancers:
    - ContainerName: simple-app
      ContainerPort: 80
      LoadBalancerName:
        Ref: EcsElasticLoadBalancer
    Role:
      Ref: ECSServiceRole
    TaskDefinition:
      Ref: taskdefinition
```

### IAM role policy
<a name="w2aac19c19c17c21"></a>

Resources that make additional calls to AWS require a service role, which permits a service to make calls to AWS on your behalf. For example, the `AWS::CodeDeploy::DeploymentGroup` resource requires a service role so that CodeDeploy has permissions to deploy applications to your instances. When you have a single template that defines a service role, the role's policy (by using the `AWS::IAM::Policy` or `AWS::IAM::ManagedPolicy` resource), and a resource that uses the role, add a dependency so that the resource depends on the role's policy. This dependency ensures that the policy is available throughout the resource's lifecycle.

For example, imagine that you have a template with a deployment group resource, a service role, and the role's policy. When you create a stack, CloudFormation won't create the deployment group until it creates the role's policy. Without the dependency, CloudFormation can create the deployment group resource before it creates the role's policy. If that happens, the deployment group will fail to create because of insufficient permissions.

If the role has an embedded policy, don't specify a dependency. CloudFormation creates the role and its policy at the same time.

# `Metadata` attribute
<a name="aws-attribute-metadata"></a>

The `Metadata` attribute enables you to associate structured data with a resource. By adding a `Metadata` attribute to a resource, you can add data in JSON or YAML to the resource declaration. In addition, you can use intrinsic functions (such as [`Fn::GetAtt`](intrinsic-function-reference-getatt.md) and [`Ref`](intrinsic-function-reference-ref.md)), parameters, and pseudo parameters within the `Metadata` attribute to add those interpreted values.

**Note**  
CloudFormation doesn't validate the syntax within the metadata attribute.

**Important**  
CloudFormation doesn't redact or obfuscate any information you include in the metadata attribute. We strongly recommend you don't use this section to store sensitive information, such as passwords or secrets.

You can retrieve this data using the [describe-stack-resource](https://docs.aws.amazon.com/cli/latest/reference/cloudformation/describe-stack-resource.html) CLI command or the [DescribeStackResource](https://docs.aws.amazon.com/AWSCloudFormation/latest/APIReference/API_DescribeStackResource.html) API operation.

## Example
<a name="aws-attribute-metadata-example"></a>

The following template contains an Amazon S3 bucket resource with a `Metadata` attribute.

### JSON
<a name="aws-attribute-metadata-example.json"></a>

```
{
   "AWSTemplateFormatVersion" : "2010-09-09",
   "Resources" : {
      "MyBucket" : {
         "Type" : "AWS::S3::Bucket",
         "Metadata" : { 
            "Object1" : "Location1",
            "Object2" : "Location2" 
         }
      }
   }
}
```

### YAML
<a name="aws-attribute-metadata-example.yaml"></a>

```
1. AWSTemplateFormatVersion: '2010-09-09'
2. Resources:
3.   MyBucket:
4.     Type: AWS::S3::Bucket
5.     Metadata:
6.       Object1: Location1
7.       Object2: Location2
```

# `AWS::CloudFormation::Authentication`
<a name="aws-resource-authentication"></a>

Use the `AWS::CloudFormation::Authentication` metadata type to specify authentication credentials for files or sources that you specify with the [`AWS::CloudFormation::Init`](aws-resource-init.md) metadata type.

To include authentication information for a file or source that you specify with `AWS::CloudFormation::Init`, use the `uris` property if the source is a URI or the `buckets` property if the source is an Amazon S3 bucket. For more information about files, see [Files](aws-resource-init.md#aws-resource-init-files). For more information about sources, see [Sources](aws-resource-init.md#aws-resource-init-sources).

You can also specify authentication information for files directly in the `AWS::CloudFormation::Init` metadata type. The files key of the resource contains a property named `authentication`. You can use the `authentication` property to associate authentication information defined in the `AWS::CloudFormation::Authentication` metadata type directly with a file.

For files, CloudFormation looks for authentication information in the following order:

1. The `authentication` property of the `AWS::CloudFormation::Init` `files` key.

1. The `uris` or `buckets` property of the `AWS::CloudFormation::Authentication` metadata.

For sources, CloudFormation looks for authentication information in the `uris` or `buckets` property of the `AWS::CloudFormation::Authentication` metadata.

**Topics**
+ [

## Syntax
](#aws-resource-cloudformation-authentication-syntax)
+ [

## Properties
](#w2aac19c23c15c19)
+ [

## Examples
](#aws-resource-authentication-examples)

## Syntax
<a name="aws-resource-cloudformation-authentication-syntax"></a>

To declare this entity in your CloudFormation template, use the following syntax:

Be aware of the following considerations when using the `AWS::CloudFormation::Authentication` metadata type:
+ Unlike most CloudFormation resources, the `AWS::CloudFormation::Authentication` metadata type doesn't contain a block called *Properties*, but instead contains a list of user-named blocks, each containing its own authentication properties.

  Not all properties pertain to each authentication type. For more information, see the [type](#cfn-cloudformation-authentication-type) property.
+ Unlike most CloudFormation resources, `AWS::CloudFormation::Authentication` property names use lower camel case.

### JSON
<a name="aws-resource-cloudformation-authentication-syntax.json"></a>

```
{
  "AWS::CloudFormation::Authentication" {
    "String" : {
      "accessKeyId" : String,
      "buckets" : [ String, ... ],
      "password" : String,
      "secretKey" : String,
      "type" : String,
      "uris" : [ String, ... ],
      "username" : String,
      "roleName" : String
    }
  }
}
```

### YAML
<a name="aws-resource-cloudformation-authentication-syntax.yaml"></a>

```
AWS::CloudFormation::Authentication
String:
  accessKeyId: String
  buckets:
    - String
  password: String
  secretKey: String
  type: String
  uris:
    - String
  username: String
  roleName: String
```

## Properties
<a name="w2aac19c23c15c19"></a>

`accessKeyId`  <a name="cfn-cloudformation-authentication-accesskeyid"></a>
Specifies the access key ID for S3 authentication.  
*Required*: Conditional. Can be specified only if the `type` property is set to `S3`.  
*Type*: String

`buckets`  <a name="cfn-cloudformation-authentication-buckets"></a>
A comma-delimited list of Amazon S3 buckets to be associated with the S3 authentication credentials.  
*Required*: Conditional. Can be specified only if the `type` property is set to `S3`.  
*Type*: List of String values

`password`  <a name="cfn-cloudformation-authentication-password"></a>
Specifies the password for basic authentication.  
*Required*: Conditional. Can be specified only if the type property is set to `basic`.  
*Type*: String

`secretKey`  <a name="cfn-cloudformation-authentication-secretkey"></a>
Specifies the secret key for S3 authentication.  
*Required*: Conditional. Can be specified only if the `type` property is set to `S3`.  
*Type*: String

`type`  <a name="cfn-cloudformation-authentication-type"></a>
Specifies whether the authentication scheme uses a user name and password (basic) or an access key ID and secret key (S3).  
If you specify `basic`, specify the `username`, `password`, and `uris` properties.  
If you specify `S3`, specify the `accessKeyId`, `secretKey`, and `buckets` (optional) properties.  
*Required*: Yes  
*Valid values*: `basic` \$1 `S3`

`uris`  <a name="cfn-cloudformation-authentication-uris"></a>
A comma-delimited list of URIs to be associated with the basic authentication credentials. The authorization applies to the specified URIs and any more specific URI. For example, if you specify `http://www.example.com`, the authorization will also apply to `http://www.example.com/test`.  
*Required*: Conditional. Can be specified only if the `type` property is set to `basic`.  
*Type*: List of String values

`username`  <a name="cfn-cloudformation-authentication-username"></a>
Specifies the user name for basic authentication.  
*Required*: Conditional. Can be specified only if the type property is set to `basic`.  
*Type*: String

`roleName`  <a name="cfn-cloudformation-authentication-rolename"></a>
Describes the role for role-based authentication.  
This role must be contained within the instance profile that's attached to the EC2 instance. An instance profile can only contain one IAM role.
*Required*: Conditional. Can be specified only if the `type` property is set to `S3`.  
*Type*: String.

## Examples
<a name="aws-resource-authentication-examples"></a>

**Topics**
+ [

### EC2 web server authentication
](#aws-resource-cloudformation-authentication-example1)
+ [

### Specifying both basic and S3 authentication
](#aws-resource-cloudformation-authentication-example2)
+ [

### IAM roles
](#aws-resource-cloudformation-authentication-example3)

### EC2 web server authentication
<a name="aws-resource-cloudformation-authentication-example1"></a>

This template snippet shows how to get a file from a private S3 bucket within an EC2 instance. The credentials used for authentication are defined in the `AWS::CloudFormation::Authentication` metadata, and referenced by the `AWS::CloudFormation::Init` metadata in the *files* section.

#### JSON
<a name="aws-resource-cloudformation-authentication-example1.json"></a>

```
"WebServer": {
   "Type": "AWS::EC2::Instance",
   "DependsOn" : "BucketPolicy",
   "Metadata" : {
      "AWS::CloudFormation::Init" : {
         "config" : {
            "packages" : { "yum" : { "httpd" : [] } },
            "files" : {
               "/var/www/html/index.html" : {
                  "source" : {
                     "Fn::Join" : [
                        "", [ "http://s3.amazonaws.com/", { "Ref" : "BucketName" }, "/index.html" ]
                     ]
                  },
                  "mode"   : "000400",
                  "owner"  : "apache",
                  "group"  : "apache",
                  "authentication" : "S3AccessCreds"
               }
            },
            "services" : {
               "sysvinit" : {
                  "httpd" : { "enabled" : "true", "ensureRunning" : "true" }
               }
            }
         }
      },
      "AWS::CloudFormation::Authentication" : {
         "S3AccessCreds" : {
            "type" : "S3",
            "accessKeyId" : { "Ref" : "AccessKeyID" },
            "secretKey" : { "Ref" : "SecretAccessKey" }
         }
      }
   },
   "Properties": {
   EC2 Resource Properties ...
   }
}
```

#### YAML
<a name="aws-resource-cloudformation-authentication-example1.yaml"></a>

```
WebServer: 
  Type: AWS::EC2::Instance
  DependsOn: BucketPolicy
  Metadata: 
    AWS::CloudFormation::Init: 
      config: 
        packages: 
          yum: 
            httpd: []
        files: 
          /var/www/html/index.html: 
            source: !Join
              - ''
              - - 'http://s3.amazonaws.com/'
                - !Ref BucketName
                - '/index.html'
            mode: '000400'
            owner: apache
            group: apache
            authentication: S3AccessCreds
        services: 
          sysvinit: 
            httpd: 
              enabled: 'true'
              ensureRunning: 'true'
    AWS::CloudFormation::Authentication: 
      S3AccessCreds: 
        type: S3
        accessKeyId: !Ref AccessKeyID
        secretKey: !Ref SecretAccessKey
  Properties: 
  EC2 Resource Properties ...
```

### Specifying both basic and S3 authentication
<a name="aws-resource-cloudformation-authentication-example2"></a>

The following example template snippet includes both *basic* and *S3* authentication types.

#### JSON
<a name="aws-resource-cloudformation-authentication-example2.json"></a>

```
"AWS::CloudFormation::Authentication" : {
   "testBasic" : {
      "type" : "basic",
      "username" : { "Ref" : "UserName" },
      "password" : { "Ref" : "Password" },
      "uris" : [ "example.com/test" ]
   },
   "testS3" : {
      "type" : "S3",
      "accessKeyId" : { "Ref" : "AccessKeyID" },
      "secretKey" : { "Ref" : "SecretAccessKey" },
      "buckets" : [{ "Fn::Sub": "${BucketName}" }]
   }
}
```

#### YAML
<a name="aws-resource-cloudformation-authentication-example2.yaml"></a>

```
AWS::CloudFormation::Authentication: 
  testBasic: 
    type: basic
    username: !Ref UserName
    password: !Ref Password
    uris: 
      - 'example.com/test'
  testS3: 
    type: S3
    accessKeyId: !Ref AccessKeyID
    secretKey: !Ref SecretAccessKey
    buckets: 
      - !Sub ${BucketName}
```

### IAM roles
<a name="aws-resource-cloudformation-authentication-example3"></a>

The following example shows how to use IAM roles:
+ `myRole` is an [AWS::IAM::Role](https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/aws-resource-iam-role.html) resource.
+ The Amazon EC2 instance that runs `cfn-init` is associated with `myRole` through an instance profile.
+ The example specifies the authentication by using the `buckets` property, like in Amazon S3 authentication. You can also specify authentication by name.

#### JSON
<a name="aws-resource-cloudformation-authentication-example3.json"></a>

```
"AWS::CloudFormation::Authentication": {
    "rolebased" : {
        "type": "S3",
        "buckets": [{ "Fn::Sub": "${BucketName}" }],
        "roleName": { "Ref": "myRole" }
    }
}
```

#### YAML
<a name="aws-resource-cloudformation-authentication-example3.yaml"></a>

```
AWS::CloudFormation::Authentication:
  rolebased:
    type: S3
    buckets:
      - !Sub ${BucketName}
    roleName: !Ref myRole
```

# `AWS::CloudFormation::Init`
<a name="aws-resource-init"></a>

Use the `AWS::CloudFormation::Init` type to include metadata on an Amazon EC2 instance for the `cfn-init` helper script. If your template calls the `cfn-init` script, the script looks for resource metadata rooted in the `AWS::CloudFormation::Init` metadata key. For more information, see [cfn-init](cfn-init.md).

`cfn-init` supports all metadata types for Linux systems. It supports metadata types for Windows with conditions that are described in the sections that follow.

## Syntax
<a name="aws-resource-cloudformation-init-syntax"></a>

The configuration is separated into sections. The following template snippet shows how you can attach metadata for `cfn-init` to an EC2 instance resource within the template.

The metadata is organized into config keys, which you can group into configsets. You can specify a configset when you call `cfn-init` in your template. If you don't specify a configset, `cfn-init` looks for a single config key named `config`.

**Note**  
The `cfn-init` helper script processes these configuration sections in the following order: packages, groups, users, sources, files, commands, and then services. If you require a different order, separate your sections into different config keys, and then use a configset that specifies the order in which the config keys should be processed.

### JSON
<a name="aws-resource-cloudformation-init-syntax.json"></a>

```
"Resources": {
  "MyInstance": {
    "Type": "AWS::EC2::Instance",
    "Metadata" : {
      "AWS::CloudFormation::Init" : {
        "config" : {
          "packages" : {
            :
          },
          "groups" : {
            :
          },
          "users" : {
            :
          },
          "sources" : {
            :
          },
          "files" : {
            :
          },
          "commands" : {
            :
          },
          "services" : {
            :
          }
        }
      }
    },
    "Properties": {
      :
    }
  }
}
```

### YAML
<a name="aws-resource-cloudformation-init-syntax.yaml"></a>

```
Resources: 
  MyInstance: 
    Type: AWS::EC2::Instance
    Metadata: 
      AWS::CloudFormation::Init: 
        config: 
          packages: 
            :
          groups: 
            :
          users: 
            :
          sources: 
            :
          files: 
            :
          commands: 
            :
          services: 
            :
    Properties: 
      :
```

**Note**  
The following sections contain examples for scripts written in Unix-like shell scripting languages, such as Bash. To create scripts for PowerShell instead, make sure you're familiar with the PowerShell language. PowerShell syntax is different from Unix-like shells, so you'll need to have familiarity with the PowerShell way of doing things.

## Configsets
<a name="aws-resource-init-configsets"></a>

If you want to create more than one config key and to have `cfn-init` process them in a specific order, create a configset that contains the config keys in the desired order.

### Single configset
<a name="w2aac19c23c19c11b5"></a>

The following template snippet creates configsets named `ascending` and `descending` that each contain two config keys.

#### JSON
<a name="aws-resource-cloudformation-init-configset-example1.json"></a>

```
"AWS::CloudFormation::Init" : {
    "configSets" : {
        "ascending" : [ "config1" , "config2" ],
        "descending" : [ "config2" , "config1" ]
    },
    "config1" : {
        "commands" : {
            "test" : {
                "command" : "echo \"$CFNTEST\" > test.txt",
                "env" : { "CFNTEST" : "I come from config1." },
                "cwd" : "~"
            }
        }
    },
    "config2" : {
        "commands" : {
            "test" : {
                "command" : "echo \"$CFNTEST\" > test.txt",
                "env" : { "CFNTEST" : "I come from config2" },
                "cwd" : "~"
            }
        }
    }
}
```

#### YAML
<a name="aws-resource-cloudformation-init-configset-example1.yaml"></a>

```
AWS::CloudFormation::Init: 
  configSets: 
    ascending: 
      - "config1"
      - "config2"
    descending: 
      - "config2"
      - "config1"
  config1: 
    commands: 
      test: 
        command: "echo \"$CFNTEST\" > test.txt"
        env: 
          CFNTEST: "I come from config1."
        cwd: "~"
  config2: 
    commands: 
      test: 
        command: "echo \"$CFNTEST\" > test.txt"
        env: 
          CFNTEST: "I come from config2"
        cwd: "~"
```

#### Related `cfn-init` calls
<a name="w2aac19c23c19c11b5b9"></a>

The following example calls to `cfn-init` refer to the preceding example configsets. The example calls are abbreviated for clarity. See [cfn-init](https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/cfn-init.html) for the complete syntax.
+ If a call to `cfn-init` specifies the `ascending` configset:

  ```
  cfn-init -c ascending
  ```

  The script processes `config1` and then processes `config2` and the `test.txt` file would contain the text `I come from config2`.
+ If a call to `cfn-init` specifies the `descending` configset:

  ```
  cfn-init -c descending
  ```

  The script processes `config2` and then processes `config1` and the `test.txt` file would contain the text `I come from config1`.

### Multiple configsets
<a name="w2aac19c23c19c11b7"></a>

You can create multiple configsets, and call a series of them using your `cfn-init` script. Each configset can contain a list of config keys or references to other configsets. For example, the following template snippet creates three configsets. The first configset, `test1`, contains one config key named `1`. The second configset, `test2`, contains a reference to the `test1` configset and one config key named `2`. The third configset, default, contains a reference to the configset `test2`.

#### JSON
<a name="aws-resource-cloudformation-init-configset-example2.json"></a>

```
"AWS::CloudFormation::Init" : {
    "configSets" : {
        "test1" : [ "1" ],
        "test2" : [ { "ConfigSet" : "test1" }, "2" ],
        "default" : [ { "ConfigSet" : "test2" } ]
    },
    "1" : {
        "commands" : {
            "test" : {
                "command" : "echo \"$MAGIC\" > test.txt",
                "env" : { "MAGIC" : "I come from the environment!" },
                "cwd" : "~"
            }
        }
    },
    "2" : {
        "commands" : {
            "test" : {
                "command" : "echo \"$MAGIC\" >> test.txt",
                "env" : { "MAGIC" : "I am test 2!" },
                "cwd" : "~"
            }
        }
    }
}
```

#### YAML
<a name="aws-resource-cloudformation-init-configset-example2.yaml"></a>

```
AWS::CloudFormation::Init:
  1:
    commands:
      test:
        command: "echo \"$MAGIC\" > test.txt"
        env:
          MAGIC: "I come from the environment!"
        cwd: "~"
  2:
    commands:
      test:
        command: "echo \"$MAGIC\" >> test.txt"
        env:
          MAGIC: "I am test 2!"
        cwd: "~"
  configSets: 
    test1:
      - "1"
    test2:
      - ConfigSet: "test1"
      - "2"
    default:
      - ConfigSet: "test2"
```

#### Related `cfn-init` calls
<a name="w2aac19c23c19c11b7b9"></a>

The following calls to `cfn-init` refer to the `configSets` declared in the preceding template snippet. The example calls are abbreviated for clarity. See [cfn-init](https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/cfn-init.html) for the complete syntax.
+ If you specify `test1` only:

  ```
  cfn-init -c test1
  ```

  `cfn-init` processes config key `1` only.
+ If you specify `test2` only:

  ```
  cfn-init -c test2
  ```

  `cfn-init` processes config key `1` and then processes config key `2`.
+ If you specify the `default` configset (or no configsets at all):

  ```
  cfn-init -c default
  ```

  You'll get the same behavior that you would if you specify configset `test2`.

## Commands
<a name="aws-resource-init-commands"></a>

You can use the commands key to run commands on the EC2 instance. The commands are processed in alphabetical order by name.


| Key | Required | Description | 
| --- | --- | --- | 
|  `command`  | Required |  Either an array or a string specifying the command to run. If you use an array, you don't need to escape space characters or enclose command parameters in quotes. Don't use the array to specify multiple commands.  | 
|  `env`  | Optional |  Sets environment variables for the command. This property overwrites, rather than appends, the existing environment.  | 
|  `cwd`  | Optional |  The working directory.  | 
|  `test`  | Optional |  A test command that determines whether `cfn-init` runs commands that are specified in the command key. If the test passes, `cfn-init` runs the commands. The `cfn-init` script runs the test in a command interpreter, such as Bash or `cmd.exe`. Whether a test passes depends on the exit code that the interpreter returns. For Linux, the test command must return an exit code of `0` for the test to pass. For Windows, the test command must return an %ERRORLEVEL% of `0`.  | 
|  `ignoreErrors`  | Optional |  A Boolean value that determines whether `cfn-init` continues to run if the command contained in the command key fails (returns a non-zero value). Set to `true` if you want `cfn-init` to continue running even if the command fails. Set to `false` if you want `cfn-init` to stop running if the command fails. The default value is `false`.  | 
|  `waitAfterCompletion`  | Optional |  For Windows systems only. Specifies how long to wait (in seconds) after a command has finished in case the command causes a reboot. The default value is 60 seconds and a value of "forever" directs `cfn-init` to exit and resume only after the reboot is complete. Set this value to `0` if you don't want to wait for every command.  | 

### Example
<a name="w2aac19c23c19c13b7"></a>

The following example snippet calls the echo command if the `~/test.txt` file doesn't exist.

#### JSON
<a name="aws-resource-init-commands-example.json"></a>

```
"commands" : {
    "test" : {
        "command" : "echo \"$MAGIC\" > test.txt",
        "env" : { "MAGIC" : "I come from the environment!" },
        "cwd" : "~",
        "test" : "test ! -e ~/test.txt",
        "ignoreErrors" : "false"
    },
    "test2" : {
        "command" : "echo \"$MAGIC2\" > test2.txt",
        "env" : { "MAGIC2" : "I come from the environment!" },
        "cwd" : "~",
        "test" : "test ! -e ~/test2.txt",
        "ignoreErrors" : "false"
    }
}
```

#### YAML
<a name="aws-resource-init-commands-example.yaml"></a>

```
commands:
  test:
    command: "echo \"$MAGIC\" > test.txt"
    env:
      MAGIC: "I come from the environment!"
    cwd: "~"
    test: "test ! -e ~/test.txt"
    ignoreErrors: "false"
  test2:
    command: "echo \"$MAGIC2\" > test2.txt"
    env:
      MAGIC2: "I come from the environment!"
    cwd: "~"
    test: "test ! -e ~/test2.txt"
    ignoreErrors: "false"
```

## Files
<a name="aws-resource-init-files"></a>

You can use the `files` key to create files on the EC2 instance. The content can be either inline in the template or the content can be pulled from a URL. The files are written to disk in lexicographic order. The following table lists the supported keys.


| Key | Description | 
| --- | --- | 
|  `content`  |  Either a string or a properly formatted JSON object. If you use a JSON object as your content, the JSON will be written to a file on disk. Any intrinsic functions such as `Fn::GetAtt` or `Ref` are evaluated before the JSON object is written to disk. When you create a symlink, specify the symlink target as the content.  If you create a symlink, the helper script modifies the permissions of the target file. Currently, you can't create a symlink without modifying the permissions of the target file.   | 
|  `source`  |  A URL to load the file from. This option can't be specified with the content key.  | 
|  `encoding`  |  The encoding format. Only used if the content is a string. Encoding isn't applied if you are using a source. Valid values: `plain` \$1 `base64`  | 
|  `group`  |  The name of the owning group for this file. Not supported for Windows systems.  | 
|  `owner`  |  The name of the owning user for this file. Not supported for Windows systems.  | 
|  `mode`  |  A six-digit octal value representing the mode for this file. Not supported for Windows systems. Use the first three digits for symlinks and the last three digits for setting permissions. To create a symlink, specify **120*xxx***, where `xxx` defines the permissions of the target file. To specify permissions for a file, use the last three digits, such as **000644**.  | 
|  `authentication`  |  The name of an authentication method to use. This overrides any default authentication. You can use this property to select an authentication method you define with the [`AWS::CloudFormation::Authentication`](aws-resource-authentication.md) resource.  | 
|  `context`  |  Specifies a context for files that are to be processed as [Mustache templates](https://mustache.github.io/mustache.5.html). To use this key, you must have installed `aws-cfn-bootstrap` 1.3 –11 or later in addition to [https://github.com/defunkt/pystache](https://github.com/defunkt/pystache).  | 

### Examples
<a name="w2aac19c23c19c15b7"></a>

The following example snippet creates a file named `setup.mysql` as part of a larger installation.

#### JSON
<a name="aws-resource-init-setup-mysql.json"></a>

```
"files" : {
  "/tmp/setup.mysql" : {
    "content" : { "Fn::Join" : ["", [
      "CREATE DATABASE ", { "Ref" : "DBName" }, ";\n",
      "CREATE USER '", { "Ref" : "DBUsername" }, "'@'localhost' IDENTIFIED BY '",
                       { "Ref" : "DBPassword" }, "';\n",
      "GRANT ALL ON ", { "Ref" : "DBName" }, ".* TO '", { "Ref" : "DBUsername" },
                       "'@'localhost';\n",
      "FLUSH PRIVILEGES;\n"
      ]]},
    "mode"  : "000644",
    "owner" : "root",
    "group" : "root"
  }
}
```

#### YAML
<a name="aws-resource-init-setup-mysql.yaml"></a>

```
files: 
  /tmp/setup.mysql: 
    content: !Sub |
      CREATE DATABASE ${DBName};
      CREATE USER '${DBUsername}'@'localhost' IDENTIFIED BY '${DBPassword}';
      GRANT ALL ON ${DBName}.* TO '${DBUsername}'@'localhost';
      FLUSH PRIVILEGES;
    mode: "000644"
    owner: "root"
    group: "root"
```

The full template is available at: [https://s3.amazonaws.com/cloudformation-templates-us-east-1/Drupal\$1Single\$1Instance.template](https://s3.amazonaws.com/cloudformation-templates-us-east-1/Drupal_Single_Instance.template).

The following example snippet creates a symlink `/tmp/myfile2.txt` that points at an existing file `/tmp/myfile1.txt`. The permissions of the target file `/tmp/myfile1.txt` is defined by the mode value `644`.

#### JSON
<a name="aws-resource-init-symlink.json"></a>

```
"files" : {
  "/tmp/myfile2.txt" : {
    "content" : "/tmp/myfile1.txt",
    "mode" : "120644"
  }
}
```

#### YAML
<a name="aws-resource-init-symlink.yaml"></a>

```
files:
  /tmp/myfile2.txt:
    content: "/tmp/myfile1.txt"
    mode: "120644"
```

Mustache templates are used primarily to create configuration files. For example, you can store a configuration file in an S3 bucket and interpolate Refs and GetAtts from the template, instead of using `Fn::Join`. The following example snippet outputs `Content for test9` to `/tmp/test9.txt`.

#### JSON
<a name="aws-resource-init-test9.json"></a>

```
"files" : {
    "/tmp/test9.txt" : {
        "content" : "Content for {{name}}",
        "context" : { "name" : "test9" }
    }
}
```

#### YAML
<a name="aws-resource-init-test9.yaml"></a>

```
files:
  /tmp/test9.txt:
    content: "Content for {{name}}"
    context:
      name: "test9"
```

When working with Mustache templates, note the following:
+ The context key must be present for the files to be processed.
+ The context key must be a key-value map, but it can be nested.
+ You can process files with inline content by using the content key and remote files by using the source key.
+ Mustache support depends on the pystache version. Version 0.5.2 supports the [Mustache 1.1.2 specification](https://github.com/mustache/spec/tree/v1.1.2).

## Groups
<a name="aws-resource-init-groups"></a>

You can use the groups key to create Linux/UNIX groups and to assign group IDs. The groups key isn't supported for Windows systems.

To create a group, add a new key-value pair that maps a new group name to an optional group ID. The groups key can contain one or more group names. The following table lists the available keys.


| Key | Description | 
| --- | --- | 
|   `gid`  |  A group ID number. If a group ID is specified, and the group already exists by name, the group creation will fail. If another group has the specified group ID, the OS may reject the group creation. Example: `{ "gid" : "23" }`  | 

### Example snippet
<a name="aws-resource-init-groups-snippet"></a>

The following snippet specifies a group named `groupOne` without assigning a group ID and a group named `groupTwo` that specified a group ID value of `45`.

#### JSON
<a name="aws-resource-init-groups-snippet.json"></a>

```
"groups" : {
    "groupOne" : {},
    "groupTwo" : { "gid" : "45" }
}
```

#### YAML
<a name="aws-resource-init-groups-snippet.yaml"></a>

```
groups:
  groupOne: {}
  groupTwo:
    gid: "45"
```

## Packages
<a name="aws-resource-init-packages"></a>

You can use the packages key to download and install pre-packaged applications and components. On Windows systems, the packages key supports only the MSI installer.

### Supported package formats
<a name="aws-resource-init-packages-formats"></a>

The `cfn-init` script currently supports the following package formats: apt, msi, python, rpm, rubygems, yum, and Zypper. Packages are processed in the following order: rpm, yum/apt/zypper, and then rubygems and python. There is no ordering between rubygems and python, and packages within each package manager aren't guaranteed to be installed in any order.

### Specifying versions
<a name="aws-resource-init-packages-versions"></a>

Within each package manager, each package is specified as a package name and a list of versions. The version can be a string, a list of versions, or an empty string or list. An empty string or list indicates that you want the latest version. For rpm manager, the version is specified as a path to a file on disk or a URL.

If you specify a version of a package, `cfn-init` will attempt to install that version even if a newer version of the package is already installed on the instance. Some package managers support multiple versions, but others may not. Verify the documentation for your package manager for more information. If you don't specify a version and a version of the package is already installed, the `cfn-init` script won't install a new version— it will assume that you want to keep and use the existing version.

### Example snippets
<a name="aws-resource-init-packages-snippet"></a>

#### RPM, yum, Rubygems, and Zypper
<a name="w2aac19c23c19c19b9b3"></a>

The following snippet specifies a version URL for rpm, requests the latest versions from yum and Zypper, and version 0.10.2 of chef from rubygems:

##### JSON
<a name="aws-resource-init-packages-example1.json"></a>

```
"rpm" : {
  "epel" : "http://download.fedoraproject.org/pub/epel/5/i386/epel-release-5-4.noarch.rpm"
},
"yum" : {
  "httpd" : [],
  "php" : [],
  "wordpress" : []
},
"rubygems" : {
  "chef" : [ "0.10.2" ]
},
"zypper" : {
  "git" : []
}
```

##### YAML
<a name="aws-resource-init-packages-example1.yaml"></a>

```
rpm:
  epel: "http://download.fedoraproject.org/pub/epel/5/i386/epel-release-5-4.noarch.rpm"
yum:
  httpd: []
  php: []
  wordpress: []
rubygems:
  chef:
    - "0.10.2"
zypper:
  git: []
```

#### MSI package
<a name="w2aac19c23c19c19b9b5"></a>

The following snippet specifies a URL for an MSI package:

##### JSON
<a name="aws-resource-init-packages-example2.json"></a>

```
"msi" : {
  "awscli" : "https://s3.amazonaws.com/aws-cli/AWSCLI64.msi"
}
```

##### YAML
<a name="aws-resource-init-packages-example2.yaml"></a>

```
msi:
  awscli: "https://s3.amazonaws.com/aws-cli/AWSCLI64.msi"
```

## Services
<a name="aws-resource-init-services"></a>

You can use the services key to define which services should be enabled or disabled when the instance is launched. Amazon Linux 2 systems and above running `aws-cfn-bootstrap` version 2.0-29\$1 support this key by using systemd. Other Linux systems support this key using sysvinit (by default) or systemd (by adding the necessary configurations below). Windows systems support this key through Windows Service Manager.

The services key also allows you to specify dependencies on sources, packages, and files so that if a restart is needed due to files being installed, `cfn-init` will take care of the service restart. For example, if you download the Apache HTTP Server package, the package installation will automatically start the Apache HTTP Server during the stack creation process. However, if the Apache HTTP Server configuration is updated later in the stack creation process, the update won't take effect unless the Apache server is restarted. You can use the services key to ensure that the Apache HTTP service is restarted.

The following table lists the supported keys.


| Key | Description | 
| --- | --- | 
|  `ensureRunning`  |  Set to true to ensure that the service is running after `cfn-init` finishes. Set to false to ensure that the service isn't running after `cfn-init` finishes. Omit this key to make no changes to the service state.  | 
|  `enabled`  |  Set to true to ensure that the service will be started automatically upon boot. Set to false to ensure that the service won't be started automatically upon boot. Omit this key to make no changes to this property.  | 
|  `files`  |  A list of files. If `cfn-init` changes one directly through the files block, this service will be restarted.  | 
|  sources  |  A list of directories. If `cfn-init` expands an archive into one of these directories, this service will be restarted.  | 
|  packages  |  A map of package manager to list of package names. If `cfn-init` installs or updates one of these packages, this service will be restarted.  | 
|  commands  |  A list of command names. If `cfn-init` runs the specified command, this service will be restarted.  | 

### Examples
<a name="w2aac19c23c19c21c11"></a>

#### Linux
<a name="w2aac19c23c19c21c11b3"></a>

The following Linux snippet configures the services as follows:
+ The nginx service will be restarted if either `/etc/nginx/nginx.conf` or `/var/www/html` are modified by `cfn-init`.
+ The php-fastcgi service will be restarted if `cfn-init` installs or updates php or spawn-fcgi using yum.
+ The sendmail service will be stopped and disabled using systemd.

##### JSON
<a name="aws-resource-init-services-example1.json"></a>

```
"services" : {
  "sysvinit" : {
    "nginx" : {
      "enabled" : "true",
      "ensureRunning" : "true",
      "files" : ["/etc/nginx/nginx.conf"],
      "sources" : ["/var/www/html"]
    },
    "php-fastcgi" : {
      "enabled" : "true",
      "ensureRunning" : "true",
      "packages" : { "yum" : ["php", "spawn-fcgi"] }
    }
  },
  "systemd": {
    "sendmail" : {
      "enabled" : "false",
      "ensureRunning" : "false"
    }
  }
}
```

##### YAML
<a name="aws-resource-init-services-example1.yaml"></a>

```
services:
  sysvinit:
    nginx:
      enabled: "true"
      ensureRunning: "true"
      files:
        - "/etc/nginx/nginx.conf"
      sources:
        - "/var/www/html"
    php-fastcgi:
      enabled: "true"
      ensureRunning: "true"
      packages:
        yum:
          - "php"
          - "spawn-fcgi"
  systemd:
    sendmail:
      enabled: "false"
      ensureRunning: "false"
```

To use systemd with a service, the service must have a systemd unit file configured. The following unit file allows systemd to start and stop the `cfn-hup` daemon in the multi-user service target:

```
[Unit]
Description=cfn-hup daemon
[Service]
ExecStart=/usr/bin/cfn-hup -v
PIDFile=/var/run/cfn-hup.pid
[Install]
WantedBy=multi-user.target
```

This configuration assumes that `cfn-hup` is installed under the `/usr/bin` directory. However, the actual location where `cfn-hup` is installed might vary on different platforms. You can override this configuration by creating an override file in `/etc/systemd/system/cfn-hup.service.d/override.conf` as follows:

```
# In this example, cfn-hup executable is available under /usr/local/bin
[Service]
ExecStart=
ExecStart=/usr/local/bin/cfn-hup -v
```

#### Windows
<a name="aws-resource-init-windows-example"></a>

The following Windows snippet starts the `cfn-hup` service, sets it to automatic, and restarts the service if `cfn-init` modifies the specified configuration files:

##### JSON
<a name="aws-resource-init-services-example2.json"></a>

```
"services" : {
  "windows" : {
    "cfn-hup" : {
      "enabled" : "true",
      "ensureRunning" : "true",
      "files" : ["c:\\cfn\\cfn-hup.conf", "c:\\cfn\\hooks.d\\cfn-auto-reloader.conf"]
    }
  }
}
```

##### YAML
<a name="aws-resource-init-services-example2.yaml"></a>

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

## Sources
<a name="aws-resource-init-sources"></a>

You can use the sources key to download an archive file and unpack it in a target directory on the EC2 instance. This key is fully supported for both Linux and Windows systems.

**Supported formats**  
Supported formats are:
+ `tar`
+ `tar+gzip`
+ `tar+bz2`
+ `zip`

### Examples
<a name="aws-resource-init-sources-examples"></a>

#### GitHub
<a name="aws-resource-init-sources-examples-github"></a>

If you use GitHub as a source control system, you can use `cfn-init` and the sources package mechanism to pull a specific version of your application. GitHub allows you to create a .zip or a .tar from a specific version through a URL as follows:

```
https://github.com/<your directory>/(zipball|tarball)/<version>
```

For example, the following snippet pulls down version `main` as a `.tar` file.

##### JSON
<a name="aws-resource-init-sources-example1.json"></a>

```
"sources" : {
  "/etc/puppet" : "https://github.com/user1/cfn-demo/tarball/main"
  }
```

##### YAML
<a name="aws-resource-init-sources-example1.yaml"></a>

```
sources:
  /etc/puppet: "https://github.com/user1/cfn-demo/tarball/main"
```

#### S3 Bucket
<a name="aws-resource-init-sources-examples-s3"></a>

The following example downloads a tarball from an S3 bucket and unpacks it into `/etc/myapp`:

**Note**  
You can use authentication credentials for a source. However, you can't put an authentication key in the sources block. Instead, include a buckets key in your `S3AccessCreds` block. For more information on Amazon S3 authentication credentials, see [`AWS::CloudFormation::Authentication`](aws-resource-authentication.md).  
For an example, see the [https://s3.amazonaws.com/cloudformation-templates-us-east-1/S3Bucket\$1SourceAuth.template](https://s3.amazonaws.com/cloudformation-templates-us-east-1/S3Bucket_SourceAuth.template).

##### JSON
<a name="aws-resource-init-sources-example2.json"></a>

```
"sources" : {
  "/etc/myapp" : "https://s3.amazonaws.com/amzn-s3-demo-bucket/myapp.tar.gz"
  }
```

##### YAML
<a name="aws-resource-init-sources-example2.yaml"></a>

```
sources:
  /etc/myapp: "https://s3.amazonaws.com/amzn-s3-demo-bucket/myapp.tar.gz"
```

## Users
<a name="aws-resource-init-users"></a>

You can use the users key to create Linux/UNIX users on the EC2 instance. The `users` key isn't supported for Windows systems.

The following table lists the supported keys.


| Key | Description | 
| --- | --- | 
|  `uid`  |  A user ID. The creation process fails if the user name exists with a different user ID. If the user ID is already assigned to an existing user the operating system may reject the creation request.  | 
|  `groups`  |  A list of group names. The user will be added to each group in the list.  | 
|  `homeDir`  |  The user's home directory.  | 

### Example
<a name="aws-resource-init-users-example"></a>

Users are created as non-interactive system users with a shell of `/sbin/nologin`. This is by design and can't be modified.

#### JSON
<a name="aws-resource-init-users-example.json"></a>

```
"users" : {
    "myUser" : {
        "groups" : ["groupOne", "groupTwo"],
        "uid" : "50",
        "homeDir" : "/tmp"
    }
}
```

#### YAML
<a name="aws-resource-init-users-example.yaml"></a>

```
users:
  myUser:
    groups:
      - "groupOne"
      - "groupTwo"
    uid: "50"
    homeDir: "/tmp"
```

# `UpdatePolicy` attribute
<a name="aws-attribute-updatepolicy"></a>

Use the `UpdatePolicy` attribute to specify how CloudFormation handles updates to certain resources during stack update operations. 

**Topics**
+ [

## Overview
](#aws-resource-update-policies)
+ [

## WorkSpaces Applications update policy
](#aws-attribute-update-policy-app-stream-fleet)
+ [

## AutoScalingReplacingUpdate policy
](#cfn-attributes-updatepolicy-replacingupdate)
+ [

## AutoScalingRollingUpdate policy
](#cfn-attributes-updatepolicy-rollingupdate)
+ [

## AutoScalingScheduledAction policy
](#cfn-attributes-updatepolicy-scheduledactions)
+ [

## UseOnlineResharding policy
](#cfn-attributes-updatepolicy-useonlineresharding)
+ [

## EnableVersionUpgrade policy
](#cfn-attributes-updatepolicy-upgradeopensearchdomain)
+ [

## CodeDeployLambdaAliasUpdate policy
](#cfn-attributes-updatepolicy-codedeploylambdaaliasupdate)
+ [

## Examples
](#aws-attribute-updatepolicy-examples)

## Overview
<a name="aws-resource-update-policies"></a>

By using the `UpdatePolicy` attribute, you can control how the following resources are updated, as described here:
+ **[AWS::AppStream::Fleet](https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/aws-resource-appstream-fleet.html)** – CloudFormation can stop and start a fleet, which causes the fleet's instances to be replaced. By doing so, all instances will have the latest changes applied immediately after a stack update.
+ **[https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/aws-resource-autoscaling-autoscalinggroup.html](https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/aws-resource-autoscaling-autoscalinggroup.html)** – With Auto Scaling groups, you can use one or more update policies to control how CloudFormation handles certain updates. These policies include:
  + **`AutoScalingReplacingUpdate` and `AutoScalingRollingUpdate` policies** – CloudFormation can either replace the Auto Scaling group and its instances with an `AutoScalingReplacingUpdate` policy, or replace only the instances with an `AutoScalingRollingUpdate` policy. These replacement operations occur when you make one or more of the following changes:
    + Change the Auto Scaling group's [https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/aws-resource-autoscaling-launchconfiguration.html](https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/aws-resource-autoscaling-launchconfiguration.html).
    + Change the Auto Scaling group's `VPCZoneIdentifier` property.
    + Change the Auto Scaling group's `LaunchTemplate` property.
    + Change the Auto Scaling group's `PlacementGroup` property.
    + Update an Auto Scaling group that contains instances that don't match the current `LaunchConfiguration`.

    If both the `AutoScalingReplacingUpdate` and `AutoScalingRollingUpdate` policies are specified, setting the `WillReplace` property to `true` gives `AutoScalingReplacingUpdate` precedence.
  + **`AutoScalingScheduledAction` policy** – This policy applies when you update a stack that includes an Auto Scaling group with scheduled actions that scale the group at specific times. CloudFormation can't modify the minimum size, maximum size, or desired capacity of the group unless they have been explicitly changed in the stack template. This policy helps to prevent any unexpected updates that could interfere with the scheduled scaling activities.
+ **[https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/aws-resource-elasticache-replicationgroup.html](https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/aws-resource-elasticache-replicationgroup.html)** – CloudFormation can modify a replication group's shards by adding or removing shards, rather than replacing the entire resource. 
+ **[https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/aws-resource-opensearchservice-domain.html](https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/aws-resource-opensearchservice-domain.html)** and **[https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/aws-resource-elasticsearch-domain.html](https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/aws-resource-elasticsearch-domain.html)** (legacy) – CloudFormation can upgrade an OpenSearch Service domain to a new version of OpenSearch or Elasticsearch without replacing the entire resource. 
+ **[https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/aws-resource-lambda-alias.html](https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/aws-resource-lambda-alias.html)** – CloudFormation can perform a CodeDeploy deployment when the version changes on the alias. 

The sections that follow describe the syntax and properties for the `UpdatePolicy` attribute supported by each resource type.

## WorkSpaces Applications update policy
<a name="aws-attribute-update-policy-app-stream-fleet"></a>

To stop an WorkSpaces Applications fleet before an update and restart it after an update, use the WorkSpaces Applications update policy. 

### Syntax
<a name="aws-attribute-update-policy-app-stream-fleet-syntax"></a>

#### JSON
<a name="aws-attribute-update-policy-app-stream-fleet-syntax-json"></a>

```
{
    "UpdatePolicy": {
        "StopBeforeUpdate": {
            "Type": "Boolean"
        },
        "StartAfterUpdate": {
            "Type": "Boolean"
        }
    }
}
```

#### YAML
<a name="aws-attribute-update-policy-app-stream-fleet-syntax-yaml"></a>

```
UpdatePolicy:
  StopBeforeUpdate:
    Type: Boolean
  StartAfterUpdate:
    Type: Boolean
```

`StopBeforeUpdate`  <a name="cfn-attributes-updatepolicy-replacingupdate-StopBeforeUpdate"></a>
Stops the specified fleet before the update.  
*Required*: No

`StartAfterUpdate`  <a name="cfn-attributes-updatepolicy-replacingupdate-StartAfterUpdate"></a>
Starts the specified fleet after the update.  
*Required*: No

## AutoScalingReplacingUpdate policy
<a name="cfn-attributes-updatepolicy-replacingupdate"></a>

To replace the Auto Scaling group and the instances it contains, use the `AutoScalingReplacingUpdate` policy.

Before attempting an update, ensure that you have sufficient Amazon EC2 capacity for both your old and new Auto Scaling groups.

### Syntax
<a name="cfn-attributes-updatepolicy-replacingupdate-syntax"></a>

#### JSON
<a name="aws-attribute-updatepolicy-replacingupdate-syntax.json"></a>

```
"UpdatePolicy" : {
  "AutoScalingReplacingUpdate" : {
    "WillReplace" : Boolean
  }
}
```

#### YAML
<a name="aws-attribute-updatepolicy-replacingupdate-syntax.yaml"></a>

```
UpdatePolicy:
  AutoScalingReplacingUpdate:
    WillReplace: Boolean
```

### Properties
<a name="cfn-attributes-updatepolicy-replacingupdate-properties"></a>

`WillReplace`  <a name="cfn-attributes-updatepolicy-replacingupdate-willreplace"></a>
Specifies whether an Auto Scaling group and the instances it contains are replaced during an update. During replacement, CloudFormation retains the old group until it finishes creating the new one. If the update fails, CloudFormation can roll back to the old Auto Scaling group and delete the new Auto Scaling group.  
While CloudFormation creates the new group, it doesn't detach or attach any instances. After successfully creating the new Auto Scaling group, CloudFormation deletes the old Auto Scaling group during the cleanup process.  
When you set the `WillReplace` parameter, remember to specify a matching [`CreationPolicy` attribute](aws-attribute-creationpolicy.md). If the minimum number of instances (specified by the `MinSuccessfulInstancesPercent` property) don't signal success within the `Timeout` period (specified in the `CreationPolicy` attribute), the replacement update fails and CloudFormation rolls back to the old Auto Scaling group.  
*Type*: Boolean  
*Required*: No

## AutoScalingRollingUpdate policy
<a name="cfn-attributes-updatepolicy-rollingupdate"></a>

To perform a rolling update of the instances in an Auto Scaling group rather than wait for scaling activities to gradually replace older instances with newer instances, use the `AutoScalingRollingUpdate` policy. This policy provides you the flexibility to specify whether CloudFormation replaces instances that are in an Auto Scaling group in batches or all at once without replacing the entire resource. 

Things to consider when using an `AutoScalingRollingUpdate` policy:
+ When CloudFormation rolls back an update, it uses the `UpdatePolicy` configuration specified in the template before the current stack update. For example, you change the `MaxBatchSize` from 1 to 10 in the `UpdatePolicy`, perform a stack update, and that update fails. CloudFormation will use 1 as the maximum batch size when it rolls back, not 10. To avoid this scenario, make changes to the `UpdatePolicy` in a separate update before any updates to the Auto Scaling group that are likely to initiate rolling updates.
+ CloudFormation recommends specifying the `SuspendProcesses` property to temporarily suspend Amazon EC2 Auto Scaling processes that might interfere with the rolling update and cause it to fail. For more information, see [How can I update my Auto Scaling group when I update my CloudFormation stack?](https://repost.aws/knowledge-center/auto-scaling-group-rolling-updates)
+ CloudFormation supports using Amazon EC2 Auto Scaling lifecycle hooks when launching or terminating instances. This gives you time to perform custom actions on an instance before it moves to the next state. To make sure that new instances reach the `InService` state, complete the lifecycle hook with a `CONTINUE` result when the custom action finishes. By default, if no response is received and the lifecycle hook times out, the instance launch will be considered unsuccessful and abandoned. If no instances reach the `InService` state, the rolling update will eventually fail.
+ Amazon EC2 Auto Scaling features such as instance maintenance policies, termination policies, and scale-in protection are not available for use with CloudFormation rolling updates. Plan your rolling updates accordingly.
+ If you use an `AutoScalingRollingUpdate` policy and remove the placement group setting, the placement group will be removed from the Auto Scaling group and the CloudFormation template. Also this triggers a rolling update, so new instances won't be launched into a placement group.

### Syntax
<a name="cfn-attributes-updatepolicy-rollingupdate-syntax"></a>

#### JSON
<a name="aws-attribute-updatepolicy-rollingupdate-syntax.json"></a>

```
"UpdatePolicy" : {
  "AutoScalingRollingUpdate" : {
    "MaxBatchSize" : Integer,
    "MinActiveInstancesPercent" : Integer,
    "MinInstancesInService" : Integer,
    "MinSuccessfulInstancesPercent" : Integer,
    "PauseTime" : String,
    "SuspendProcesses" : [ List of processes ],
    "WaitOnResourceSignals" : Boolean
  }
}
```

#### YAML
<a name="aws-attribute-updatepolicy-rollingupdate-syntax.yaml"></a>

```
UpdatePolicy:
  AutoScalingRollingUpdate:
    MaxBatchSize: Integer
    MinActiveInstancesPercent: Integer
    MinInstancesInService: Integer
    MinSuccessfulInstancesPercent: Integer
    PauseTime: String
    SuspendProcesses:
      - List of processes
    WaitOnResourceSignals: Boolean
```

### Properties
<a name="aws-attribute-updatepolicy-rollingupdate-properties"></a>

`MaxBatchSize`  <a name="cfn-attributes-updatepolicy-rollingupdate-maxbatchsize"></a>
Specifies the maximum number of instances that can be replaced simultaneously.  
*Default*: `1`  
*Maximum*: `100`  
*Type*: Integer  
*Required*: No

`MinActiveInstancesPercent`  <a name="cfn-attributes-updatepolicy-rollingupdate-minactiveinstancespercent"></a>
Specifies the percentage of instances in an Auto Scaling group that must be in the `InService` state relative to that group's desired capacity during a rolling update for an update to succeed. You can specify a value from 0 to 100. CloudFormation rounds to the nearest tenth of a percent. For example, if you update five instances with a minimum `InService` percentage of 50, at least three instances must be in the `InService` state. If an instance doesn't transition to the `InService` state within a fixed time of 1 hour, CloudFormation assumes that the instance wasn't updated.  
Setting `MinActiveInstancesPercent` in your `UpdatePolicy` will also affect instances launched when the `DesiredCapacity` property of the `AWS::AutoScaling::AutoScalingGroup` resource is set higher than the current desired capacity of that Auto Scaling group.  
*Default*: `100`  
*Type*: Integer  
*Required*: No

`MinInstancesInService`  <a name="cfn-attributes-updatepolicy-rollingupdate-mininstancesinservice"></a>
Specifies the minimum number of instances that must be in service within the Auto Scaling group while CloudFormation updates old instances. This value must be less than the [https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/aws-resource-autoscaling-autoscalinggroup.html#cfn-autoscaling-autoscalinggroup-maxsize](https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/aws-resource-autoscaling-autoscalinggroup.html#cfn-autoscaling-autoscalinggroup-maxsize) of the Auto Scaling group.  
We recommend that you set the value of the `MinInstancesInService` property to at least the [https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/aws-resource-autoscaling-autoscalinggroup.html#cfn-autoscaling-autoscalinggroup-minsize](https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/aws-resource-autoscaling-autoscalinggroup.html#cfn-autoscaling-autoscalinggroup-minsize) of the Auto Scaling group. This avoids potential availability issues during a rolling update due to 0 instances serving customer traffic. 
*Default*: `0`  
*Type*: Integer  
*Required*: No

`MinSuccessfulInstancesPercent`  <a name="cfn-attributes-updatepolicy-rollingupdate-minsuccessfulinstancespercent"></a>
Specifies the percentage of instances in an Auto Scaling rolling update that must signal success for an update to succeed. You can specify a value from 0 to 100. CloudFormation rounds to the nearest tenth of a percent. For example, if you update five instances with a minimum successful percentage of `50`, three instances must signal success. If an instance doesn't send a signal within the time specified in the `PauseTime` property, CloudFormation assumes that the instance wasn't updated.  
We recommend that you set the value of the `MinSuccessfulInstancesPercent` property to a value greater than 0. When the `MinSuccessfulInstancesPercent` property is set to 0, CloudFormation waits for 0% of the capacity instances to be in an `InService` state. `MinSuccessfulInstancesPercent` returns immediately and before considering the Auto Scaling group status as `UPDATE_COMPLETE` to move on to the subsequent resources defined in the stack template. If other Auto Scaling groups are defined in your CloudFormation template, they will update simultaneously. When all Auto Scaling groups are deployed at once with 0% of the capacity instances in an `InService` state, then you will experience availability issues, due to 0 instances serving customer traffic.  
*Default*: `100`  
*Type*: Integer  
*Required*: No

`PauseTime`  <a name="cfn-attributes-updatepolicy-rollingupdate-pausetime"></a>
The amount of time that CloudFormation pauses after making a change to a batch of instances to give those instances time to start software applications.   
Specify `PauseTime` in the [ISO8601 duration format](https://en.wikipedia.org/wiki/ISO_8601#Durations) (in the format `PT#H#M#S`, where each *\$1* is the number of hours, minutes, and seconds, respectively). The maximum `PauseTime` is one hour (`PT1H`).  
When `WaitOnResourceSignals` is set to `true`, `PauseTime` acts as a timeout value. It determines the maximum time that CloudFormation waits to receive the required number of valid signals from the instances being replaced during a rolling update and from new instances being added by increasing the [https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/aws-resource-autoscaling-autoscalinggroup.html#cfn-autoscaling-autoscalinggroup-desiredcapacity](https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/aws-resource-autoscaling-autoscalinggroup.html#cfn-autoscaling-autoscalinggroup-desiredcapacity) property of the `AWS::AutoScaling::AutoScalingGroup` resource. If the `PauseTime` is exceeded before CloudFormation receives the expected signals, the update fails. For best results, specify a time period that provides sufficient time for your applications to start up. If the update needs to be rolled back, a short `PauseTime` can cause the rollback to fail.
*Default*: `PT5M` (5 minutes) when the `WaitOnResourceSignals` property is set to `true`. Otherwise, no default value is set.   
*Type*: String  
*Required*: No

`SuspendProcesses`  <a name="cfn-attributes-updatepolicy-rollingupdate-suspendprocesses"></a>
Specifies the Auto Scaling processes to suspend during a stack update. Suspending processes prevents Auto Scaling from interfering with a stack update. For example, you can suspend alarming so that Amazon EC2 Auto Scaling doesn't initiate scaling policies associated with an alarm. For valid values, see [Types of processes](https://docs.aws.amazon.com/autoscaling/ec2/userguide/as-suspend-resume-processes.html#process-types) in the *Amazon EC2 Auto Scaling User Guide*.  
*Default*: Not specified  
*Type*: List of Auto Scaling processes  
*Required*: No

`WaitOnResourceSignals`  <a name="cfn-attributes-updatepolicy-rollingupdate-waitonresourcesignals"></a>
Specifies whether CloudFormation waits for success signals from new instances before continuing the update. CloudFormation waits for the specified `PauseTime` duration for success signals.  
To signal the Auto Scaling group, use the [cfn-signal](cfn-signal.md) helper script. For Auto Scaling groups associated with Elastic Load Balancing, consider adding a health check to ensure that instances are healthy before signaling success by using the [cfn-init](cfn-init.md) helper script. For an example, see the `verify_instance_health` command in the sample templates for Amazon EC2 Auto Scaling rolling updates in our [GitHub repository](https://github.com/aws-cloudformation/aws-cloudformation-templates/tree/main/AutoScaling).  
*Default*: `false`  
*Type*: Boolean  
*Required*: Conditional. If you specify the `MinSuccessfulInstancesPercent` property, the `WaitOnResourceSignals` property must be set to `true`.

## AutoScalingScheduledAction policy
<a name="cfn-attributes-updatepolicy-scheduledactions"></a>

To specify how CloudFormation handles updates for the `MinSize`, `MaxSize`, and `DesiredCapacity` properties when the `AWS::AutoScaling::AutoScalingGroup` resource has an associated scheduled action, use the `AutoScalingScheduledAction` policy.

With scheduled actions, the group size properties of an Auto Scaling group can change at any time. When you update a stack with an Auto Scaling group and scheduled action, CloudFormation always sets the group size property values of your Auto Scaling group to the values that are defined in the `AWS::AutoScaling::AutoScalingGroup` resource of your template, even if a scheduled action is in effect.

If you don't want CloudFormation to change any of the group size property values when you have a scheduled action in effect, use the `AutoScalingScheduledAction` update policy and set `IgnoreUnmodifiedGroupSizeProperties` to `true` to prevent CloudFormation from changing the `MinSize`, `MaxSize`, or `DesiredCapacity` properties unless you have modified these values in your template.



### Syntax
<a name="cfn-attributes-updatepolicy-scheduledactions-syntax"></a>

#### JSON
<a name="aws-attribute-updatepolicy-scheduledactions-syntax.json"></a>

```
"UpdatePolicy" : {
  "AutoScalingScheduledAction" : {
    "IgnoreUnmodifiedGroupSizeProperties" : Boolean
  }
}
```

#### YAML
<a name="aws-attribute-updatepolicy-scheduledactions-syntax.yaml"></a>

```
UpdatePolicy:
  AutoScalingScheduledAction:
    IgnoreUnmodifiedGroupSizeProperties: Boolean
```

### Properties
<a name="cfn-attributes-updatepolicy-scheduledactions-properties"></a>

`IgnoreUnmodifiedGroupSizeProperties`  <a name="cfn-attributes-updatepolicy-scheduledactions-ignoreunmodifiedgroupsizeproperties"></a>
If `true`, CloudFormation ignores differences in group size properties between your current Auto Scaling group and the Auto Scaling group described in the `AWS::AutoScaling::AutoScalingGroup` resource of your template during a stack update. If you modify any of the group size property values in your template, CloudFormation uses the modified values and updates your Auto Scaling group.  
This property is ignored during a stack rollback.
*Default*: `false`  
*Type*: Boolean  
*Required*: No

## UseOnlineResharding policy
<a name="cfn-attributes-updatepolicy-useonlineresharding"></a>

To modify a replication group's shards by adding or removing shards, rather than replacing the entire [AWS::ElastiCache::ReplicationGroup](https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/aws-resource-elasticache-replicationgroup.html) resource, use the `UseOnlineResharding` update policy.

If `UseOnlineResharding` is set to `true`, you can update the `NumNodeGroups` and `NodeGroupConfiguration` properties of the `AWS::ElastiCache::ReplicationGroup` resource, and CloudFormation will update those properties without interruption. When `UseOnlineResharding` is set to `false`, or not specified, updating the `NumNodeGroups` and `NodeGroupConfiguration` properties results in CloudFormation replacing the entire `AWS::ElastiCache::ReplicationGroup` resource.

The `UseOnlineResharding` update policy has no properties.

Things to consider when setting the `UseOnlineResharding` update policy to `true`:
+ We strongly recommend you perform updates to the `NumNodeGroups` and `NodeGroupConfiguration` properties as the only updates in a given stack update operation.

  Updating the node group configuration of a replication group is a resource-intensive operation. If a stack update fails, CloudFormation doesn't roll back changes to the node group configuration of a replication group. However, CloudFormation will roll back any other properties that were changed as part of the failed update operation.
+ Any node group updates require identifying all node groups.

  If you specify the `NodeGroupConfiguration` property, you must also specify the NodeGroupId for each node group configuration in order for CloudFormation to update the number of nodes without interruption.

  When creating a replication group, if you don't specify an ID for each node group, ElastiCache automatically generates an ID for each node group. To update the replication group without interruption, use the ElastiCache console ([https://console.aws.amazon.com/elasticache/](https://console.aws.amazon.com/elasticache/)) or [DescribeReplicationGroups](https://docs.aws.amazon.com/AmazonElastiCache/latest/APIReference/API_DescribeReplicationGroups.html) to retrieve the IDs for all node groups in the replication group. Then specify the ID for each node group in your stack template before attempting to add or remove shards.
**Note**  
As a best practice, when you create a replication group in a stack template, include an ID for each node group you specify.

  In addition, updating the number of nodes without interruption requires that you have accurately specified the `PrimaryAvailabilityZone`, `ReplicaAvailabilityZones`, and `ReplicaCount` properties for each `NodeGroupConfiguration` as well. Again, you can use the ElastiCache console ([https://console.aws.amazon.com/elasticache/](https://console.aws.amazon.com/elasticache/)) or [DescribeReplicationGroups](https://docs.aws.amazon.com/AmazonElastiCache/latest/APIReference/API_DescribeReplicationGroups.html) to retrieve the actual values for each node group and compare them to the values in your stack template. You can update the property values of the node groups as a separate stack update, or as part of the same stack update that changes the number of node groups.

  When you use an `UseOnlineResharding` update policy to update the number of node groups without interruption, ElastiCache evenly distributes the keyspaces between the specified number of slots. This can't be updated later. Therefore, after updating the number of node groups in this way, you should remove the value specified for the `Slots` property of each `NodeGroupConfiguration` from the stack template, as it no longer reflects the actual values in each node group.
+ Actual node group removal results may vary.

  When you specify a `NumNodeGroups` value that's less than the current number of node groups, CloudFormation instructs ElastiCache to remove as many node groups as necessary to reach the specified number of nodes. However, ElastiCache may not always be able to remove the desired number of node groups. In the event ElastiCache can't remove the desired number of node groups, CloudFormation generates a stack event alerting you to this. In cases where ElastiCache can't remove *any* node groups, the CloudFormation resource update fails.

For more information on modifying replication groups, see [ModifyReplicationGroupShardConfiguration](https://docs.aws.amazon.com/AmazonElastiCache/latest/APIReference/API_ModifyReplicationGroupShardConfiguration.html) in the *Amazon ElastiCache API Reference*.

### Syntax
<a name="cfn-attributes-updatepolicy-useonlineresharding-syntax"></a>

#### JSON
<a name="cfn-attributes-updatepolicy-useonlineresharding-syntax.json"></a>

```
"UpdatePolicy" : {
  "UseOnlineResharding" : Boolean
}
```

#### YAML
<a name="cfn-attributes-updatepolicy-useonlineresharding-syntax.yaml"></a>

```
UpdatePolicy:
  UseOnlineResharding: Boolean
```

## EnableVersionUpgrade policy
<a name="cfn-attributes-updatepolicy-upgradeopensearchdomain"></a>

To upgrade an OpenSearch Service domain to a new version of OpenSearch or Elasticsearch rather than replacing the entire [AWS::OpenSearchService::Domain](https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/aws-resource-opensearchservice-domain.html) or [AWS::Elasticsearch::Domain](https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/aws-resource-elasticsearch-domain.html) resource, use the `EnableVersionUpgrade` update policy.

If `EnableVersionUpgrade` is set to `true`, you can update the `EngineVersion` property of the `AWS::OpenSearchService::Domain` resource (or the `ElasticsearchVersion` property of the legacy `AWS::Elasticsearch::Domain` resource), and CloudFormation will update that property without interruption. When `EnableVersionUpgrade` is set to `false`, or not specified, updating the `EngineVersion` or `ElasticsearchVersion` property results in CloudFormation replacing the entire `AWS::OpenSearchService::Domain`/`AWS::Elasticsearch::Domain` resource.

The `EnableVersionUpgrade` update policy has no properties.

For more information, see [Upgrading OpenSearch Service domains](https://docs.aws.amazon.com/opensearch-service/latest/developerguide/version-migration.html) in the Amazon OpenSearch Service Developer Guide.

### Syntax
<a name="cfn-attributes-updatepolicy-upgradeopensearchdomain-syntax"></a>

#### JSON
<a name="cfn-attributes-updatepolicy-upgradeopensearchdomain-syntax.json"></a>

```
"UpdatePolicy" : {
  "EnableVersionUpgrade" : Boolean
}
```

#### YAML
<a name="cfn-attributes-updatepolicy-upgradeopensearchdomain-syntax.yaml"></a>

```
UpdatePolicy:
  EnableVersionUpgrade: Boolean
```

## CodeDeployLambdaAliasUpdate policy
<a name="cfn-attributes-updatepolicy-codedeploylambdaaliasupdate"></a>

To perform an CodeDeploy deployment when the version changes on an `AWS::Lambda::Alias` resource, use the `CodeDeployLambdaAliasUpdate` update policy.

### Syntax
<a name="cfn-attributes-updatepolicy-codedeploylambdaaliasupdate-syntax"></a>

#### JSON
<a name="aws-attribute-updatepolicy-codedeploylambdaaliasupdate-syntax.json"></a>

```
"UpdatePolicy" : {
  "CodeDeployLambdaAliasUpdate" : {
    "AfterAllowTrafficHook" : String,
    "ApplicationName" : String,
    "BeforeAllowTrafficHook" : String,
    "DeploymentGroupName" : String
  }
}
```

#### YAML
<a name="aws-attribute-updatepolicy-codedeploylambdaaliasupdate-syntax.yaml"></a>

```
UpdatePolicy:
  CodeDeployLambdaAliasUpdate:
    AfterAllowTrafficHook: String
    ApplicationName: String
    BeforeAllowTrafficHook: String
    DeploymentGroupName: String
```

### Properties
<a name="aws-attribute-updatepolicy-codedeploylambdaaliasupdate-properties"></a>

`AfterAllowTrafficHook`  <a name="cfn-attributes-updatepolicy-codedeploylambdaaliasupdate-afterallowtraffichook"></a>
The name of the Lambda function to run after traffic routing completes.  
*Required*: No  
*Type: *String

`ApplicationName`  <a name="cfn-attributes-updatepolicy-codedeploylambdaaliasupdate-applicationname"></a>
The name of the CodeDeploy application.  
*Required: *Yes  
*Type: *String

`BeforeAllowTrafficHook`  <a name="cfn-attributes-updatepolicy-codedeploylambdaaliasupdate-beforeallowtraffichook"></a>
The name of the Lambda function to run before traffic routing starts.  
*Required*: No  
*Type: *String

`DeploymentGroupName`  <a name="cfn-attributes-updatepolicy-codedeploylambdaaliasupdate-deploymentgroupname"></a>
The name of the CodeDeploy deployment group. This is where the traffic-shifting policy is set.  
*Required*: Yes  
*Type: *String

For an example that specifies the `UpdatePolicy` attribute for an `AWS::Lambda::Alias` resource, see [Lambda alias update policy](#aws-resource-lambda-alias-example).

## Examples
<a name="aws-attribute-updatepolicy-examples"></a>

The following examples show how to add an update policy to an Auto Scaling group and how to maintain availability when updating metadata.

### Add an `UpdatePolicy` to an Auto Scaling group
<a name="aws-attribute-updatepolicy-example-1"></a>

The following example shows how to add an update policy. During an update, the Auto Scaling group updates instances in batches of two and keeps a minimum of one instance in service. Because the `WaitOnResourceSignals` flag is set, the Auto Scaling group waits for new instances that are added to the group. The new instances must signal the Auto Scaling group before it updates the next batch of instances.

#### JSON
<a name="attribute-updatepolicy-example-1.json"></a>

```
"ASG" : {
  "Type":"AWS::AutoScaling::AutoScalingGroup",
  "Properties":{
    "VPCZoneIdentifier":[ "subnetIdAz1", "subnetIdAz2", "subnetIdAz3" ],
    "LaunchTemplate":{
      "LaunchTemplateId":{
        "Ref":"logicalName"
      },
      "Version":{
        "Fn::GetAtt":[
          "logicalName",
          "LatestVersionNumber"
        ]
      }
    },
    "MaxSize":"4",
    "MinSize":"1"
  },
  "UpdatePolicy":{
    "AutoScalingScheduledAction":{
      "IgnoreUnmodifiedGroupSizeProperties":"true"
    },
    "AutoScalingRollingUpdate":{
      "MinInstancesInService":"1",
      "MaxBatchSize":"2",
      "WaitOnResourceSignals":"true",
      "PauseTime":"PT10M",
      "SuspendProcesses":[
        "HealthCheck",
        "ReplaceUnhealthy",
        "AZRebalance",
        "AlarmNotification",
        "ScheduledActions",
        "InstanceRefresh"
      ]
    }
  }
}
```

#### YAML
<a name="attribute-updatepolicy-example-1.yaml"></a>

```
ASG:
  Type: AWS::AutoScaling::AutoScalingGroup
  Properties:
    VPCZoneIdentifier:
      - subnetIdAz1
      - subnetIdAz2
      - subnetIdAz3
    LaunchTemplate:
      LaunchTemplateId: !Ref logicalName
      Version: !GetAtt logicalName.LatestVersionNumber
    MaxSize: '4'
    MinSize: '1'
  UpdatePolicy:
    AutoScalingScheduledAction:
      IgnoreUnmodifiedGroupSizeProperties: 'true'
    AutoScalingRollingUpdate:
      MinInstancesInService: '1'
      MaxBatchSize: '2'
      WaitOnResourceSignals: 'true'
      PauseTime: PT10M
      SuspendProcesses:
        - HealthCheck
        - ReplaceUnhealthy
        - AZRebalance
        - AlarmNotification
        - ScheduledActions
        - InstanceRefresh
```

### AutoScalingReplacingUpdate policy
<a name="attribute-updatepolicy-AutoScalingReplacingUpdate"></a>

The following example declares a policy that forces an associated Auto Scaling group to be replaced during an update. For the update to succeed, a percentage of instances (specified by the `MinSuccessfulPercentParameter` parameter) must signal success within the `Timeout` period.

#### JSON
<a name="attribute-updatepolicy-example-2.json"></a>

```
"UpdatePolicy" : {
  "AutoScalingReplacingUpdate" : {
    "WillReplace" : true
  }
},
"CreationPolicy" : {
  "ResourceSignal" : {
    "Count" : { "Ref" : "ResourceSignalsOnCreate"},
    "Timeout" : "PT10M"
  },
  "AutoScalingCreationPolicy" : {
    "MinSuccessfulInstancesPercent" : { "Ref" : "MinSuccessfulPercentParameter" }
  }
}
```

#### YAML
<a name="attribute-updatepolicy-example-2.yaml"></a>

```
UpdatePolicy:
  AutoScalingReplacingUpdate:
    WillReplace: true
CreationPolicy:
  ResourceSignal:
    Count: !Ref 'ResourceSignalsOnCreate'
    Timeout: PT10M
  AutoScalingCreationPolicy:
    MinSuccessfulInstancesPercent: !Ref 'MinSuccessfulPercentParameter'
```

### Maintain availability when updating the metadata for the cfn-init helper script
<a name="aws-attribute-updatepolicy-cfn-init-metadata"></a>

When you install software applications on your instances, you might use the [`AWS::CloudFormation::Init`](aws-resource-init.md) metadata key and the [cfn-init](cfn-init.md) helper script to bootstrap the instances in your Auto Scaling group. CloudFormation installs the packages, runs the commands, and performs other bootstrapping actions described in the metadata.

When you update only the metadata (for example, when updating a package to another version), you can use the [cfn-hup](cfn-hup.md) helper daemon to detect and apply the updates. However, the `cfn-hup` daemon runs independently on each instance. If the daemon happens to runs at the same time on all instances, your application or service might be unavailable during the update. To guarantee availability, you can force a rolling update so that CloudFormation updates your instances one batch at a time.

**Important**  
Forcing a rolling update requires CloudFormation to create a new instance and then delete the old one. Any information stored on the old instance is lost.

To force a rolling update, change the logical ID of the launch configuration resource, and then update the stack and any references pointing to the original logic ID (such as the associated Auto Scaling group). CloudFormation triggers a rolling update on the Auto Scaling group, replacing all instances.

### Original template
<a name="aws-attribute-updatepolicy-cfn-init-metadata-original"></a>

```
"LaunchConfig": {
  "Type" : "AWS::AutoScaling::LaunchConfiguration",
  "Metadata" : {
    "Comment" : "Install a simple PHP application",
    "AWS::CloudFormation::Init" : {
    ...
    }
  }
}
```

### Updated logical ID
<a name="aws-attribute-updatepolicy-cfn-init-metadata-updated"></a>

```
"LaunchConfigUpdateRubygemsPkg": {
  "Type" : "AWS::AutoScaling::LaunchConfiguration",
  "Metadata" : {
    "Comment" : "Install a simple PHP application",
    "AWS::CloudFormation::Init" : {
    ...
    }
  }
}
```

### Lambda alias update policy
<a name="aws-resource-lambda-alias-example"></a>

The following example specifies the `UpdatePolicy` attribute for an `AWS::Lambda::Alias` resource. All the details for the deployment are defined by the application and deployment group that are passed into the policy.

#### JSON
<a name="aws-attribute-updatepolicy-codedeploylambda.json"></a>

```
"Alias": {
  "Type": "AWS::Lambda::Alias",
  "Properties": {
    "FunctionName": {
      "Ref": "LambdaFunction"
    },
    "FunctionVersion": {
      "Fn::GetAtt": [
        "FunctionVersionTwo",
        "Version"
      ]
    },
    "Name": "MyAlias"
  },
  "UpdatePolicy": {
    "CodeDeployLambdaAliasUpdate": {
      "ApplicationName": {
        "Ref": "CodeDeployApplication"
      },
      "DeploymentGroupName": {
        "Ref": "CodeDeployDeploymentGroup"
      },
      "BeforeAllowTrafficHook": {
        "Ref": "PreHookLambdaFunction"
      },
      "AfterAllowTrafficHook": {
        "Ref": "PreHookLambdaFunction"
      }
    }
  }
}
```

#### YAML
<a name="aws-attribute-updatepolicy-codedeploylambda-example.yaml"></a>

```
Alias:
  Type: AWS::Lambda::Alias
  Properties:
    FunctionName: !Ref LambdaFunction
    FunctionVersion: !GetAtt FunctionVersionTwo.Version
    Name: MyAlias
  UpdatePolicy:
    CodeDeployLambdaAliasUpdate:
      ApplicationName: !Ref CodeDeployApplication
      DeploymentGroupName: !Ref CodeDeployDeploymentGroup
      BeforeAllowTrafficHook: !Ref PreHookLambdaFunction
      AfterAllowTrafficHook: !Ref PreHookLambdaFunction
```

# `UpdateReplacePolicy` attribute
<a name="aws-attribute-updatereplacepolicy"></a>

Use the `UpdateReplacePolicy` attribute to retain or, in some cases, backup the existing physical instance of a resource when it's replaced during a stack update operation.

When you initiate a stack update, CloudFormation updates resources based on differences between what you submit and the stack's current template and parameters. If you update a resource property that requires that the resource be replaced, CloudFormation recreates the resource during the update. For more information, see [Update behaviors of stack resources](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/using-cfn-updating-stacks-update-behaviors.html) in the *AWS CloudFormation User Guide*.

Recreating the resource generates a new physical ID. CloudFormation creates the replacement resource first, and then changes references from other dependent resources to point to the replacement resource. By default, CloudFormation then deletes the old resource. Using the `UpdateReplacePolicy`, you can specify that CloudFormation retain or, in some cases, create a snapshot of the old resource.

For resources that support snapshots, such as `AWS::EC2::Volume`, specify `Snapshot` to have CloudFormation create a snapshot before deleting the old resource instance.

You can apply the `UpdateReplacePolicy` attribute to any resource. `UpdateReplacePolicy` is only executed if you update a resource property whose update behavior is specified as **Replacement**, thereby causing CloudFormation to replace the old resource with a new one with a new physical ID. For example, if you update the `Engine` property of an [AWS::RDS::DBInstance](https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/aws-properties-rds-database-instance.html) resource type, CloudFormation creates a new resource and replaces the current DB instance resource with the new one. The `UpdateReplacePolicy` attribute would then dictate whether CloudFormation deleted, retained, or created a snapshot of the old DB instance. The update behavior for each property of a resource is specified in the reference topic for that resource in the [AWS resource and property types reference](aws-template-resource-type-ref.md).

The `UpdateReplacePolicy` attribute applies to [stack updates you perform directly](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/using-cfn-updating-stacks-direct.html), in addition to stack updates performed using [change sets](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/using-cfn-updating-stacks-changesets.html).

**Note**  
Resources that are retained continue to exist and continue to incur applicable charges until you delete those resources. Snapshots that are created with this policy continue to exist and continue to incur applicable charges until you delete those snapshots. `UpdateReplacePolicy` retains the old physical resource or snapshot, but removes it from CloudFormation's scope.

`UpdateReplacePolicy` differs from the [`DeletionPolicy`](aws-attribute-deletionpolicy.md) attribute in that it only applies to resources replaced during stack updates. Use `DeletionPolicy` for resources deleted when a stack is deleted, or when the resource definition itself is deleted from the template as part of a stack update.

The following snippet contains an Amazon RDS database instance resource with a `Retain` policy for replacement. When this resource is replaced with a new resource with a new physical ID, CloudFormation leaves the old database instance without deleting it.

## JSON
<a name="aws-attribute-updatereplacepolicy-example.json"></a>

```
{
  "AWSTemplateFormatVersion" : "2010-09-09",
  "Resources" : {
    "myDB" : {
      "Type" : "AWS::RDS::DBInstance",
      "DeletionPolicy" : "Retain",
      "UpdateReplacePolicy" : "Retain",
      "Properties" : {}
    }
  }
}
```

## YAML
<a name="aws-attribute-updatereplacepolicy-example.yaml"></a>

```
AWSTemplateFormatVersion: 2010-09-09
Resources:
  myDB:
    Type: AWS::RDS::DBInstance
    DeletionPolicy: Retain
    UpdateReplacePolicy: Retain
    Properties: {}
```

## `UpdateReplacePolicy` options
<a name="aws-attribute-updatereplacepolicy-options"></a>

`Delete`  
CloudFormation deletes the resource and all its content if applicable during resource replacement. You can add this policy to any resource type. By default, if you don't specify an `UpdateReplacePolicy`, CloudFormation deletes your resources. However, be aware of the following consideration:  
For Amazon S3 buckets, you must delete all objects in the bucket for deletion to succeed.

`Retain`  
CloudFormation keeps the resource without deleting the resource or its contents when the resource is replaced. You can add this policy to any resource type. Resources that are retained continue to exist and continue to incur applicable charges until you delete those resources.  
If a resource is replaced, the `UpdateReplacePolicy` retains the old physical resource but removes it from CloudFormation's scope.

`Snapshot`  
For resources that support snapshots, CloudFormation creates a snapshot for the resource before deleting it. Snapshots that are created with this policy continue to exist and continue to incur applicable charges until you delete those snapshots.  
If you specify the `Snapshot` option in the `UpdateReplacePolicy` for a resource that doesn't support snapshots, CloudFormation reverts to the default option, which is `Delete`.
Resources that support snapshots include:  
+ `[AWS::EC2::Volume](https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/aws-resource-ec2-volume.html)`
+ `[AWS::ElastiCache::CacheCluster](https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/aws-resource-elasticache-cachecluster.html)`
+ `[AWS::ElastiCache::ReplicationGroup](https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/aws-resource-elasticache-replicationgroup.html)`
+ `[AWS::Neptune::DBCluster](https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/aws-resource-neptune-dbcluster.html)`
+ `[AWS::RDS::DBCluster](https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/aws-resource-rds-dbcluster.html)`
+ `[AWS::RDS::DBInstance](https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/aws-resource-rds-dbinstance.html)`
+ `[AWS::Redshift::Cluster](https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/aws-resource-redshift-cluster.html)`