AWS CloudFormation User Guide Cloud Formation Gettng Started

User Manual:

Open the PDF directly: View PDF PDF.
Page Count: 2474

DownloadAWS CloudFormation - User Guide Cloud Formation Gettng Started
Open PDF In BrowserView PDF
AWS CloudFormation
User Guide
API Version 2010-05-15

AWS CloudFormation User Guide

AWS CloudFormation: User Guide

Copyright © 2018 Amazon Web Services, Inc. and/or its affiliates. All rights reserved.
Amazon's trademarks and trade dress may not be used in connection with any product or service that is not Amazon's, in any manner
that is likely to cause confusion among customers, or in any manner that disparages or discredits Amazon. All other trademarks not
owned by Amazon are the property of their respective owners, who may or may not be affiliated with, connected to, or sponsored by
Amazon.

AWS CloudFormation User Guide

Table of Contents
What is AWS CloudFormation? ............................................................................................................. 1
Simplify Infrastructure Management ............................................................................................. 1
Quickly Replicate Your Infrastructure ............................................................................................ 1
Easily Control and Track Changes to Your Infrastructure .................................................................. 1
Related Information ................................................................................................................... 2
AWS CloudFormation Concepts .................................................................................................... 2
Templates ......................................................................................................................... 2
Stacks ............................................................................................................................... 4
Change Sets ...................................................................................................................... 5
How Does AWS CloudFormation Work? ......................................................................................... 5
Updating a Stack with Change Sets ...................................................................................... 7
Deleting a Stack ................................................................................................................ 8
Additional Resources .......................................................................................................... 8
Setting Up ........................................................................................................................................ 9
Signing Up for an AWS Account and Pricing .................................................................................. 9
Pricing .............................................................................................................................. 9
Controlling Access with IAM ........................................................................................................ 9
AWS CloudFormation Actions ............................................................................................. 10
AWS CloudFormation Resources ......................................................................................... 11
AWS CloudFormation Conditions ........................................................................................ 12
Acknowledging IAM Resources in AWS CloudFormation Templates .......................................... 15
Manage Credentials for Applications Running on Amazon EC2 Instances .................................. 16
Grant Temporary Access (Federated Access) ......................................................................... 16
AWS CloudFormation Service Role ...................................................................................... 17
Logging API Calls ..................................................................................................................... 17
AWS CloudFormation Information in CloudTrail .................................................................... 18
Understanding AWS CloudFormation Log File Entries ............................................................ 18
Limits ..................................................................................................................................... 21
Endpoints ................................................................................................................................ 23
AWS CloudFormation and VPC Endpoints .................................................................................... 24
Getting Started ................................................................................................................................ 25
Get Started ............................................................................................................................. 25
Step 1: Pick a template ..................................................................................................... 25
Step 2: Make sure you have prepared any required items for the stack ..................................... 30
Step 3: Create the stack .................................................................................................... 31
Step 4: Monitor the progress of stack creation ..................................................................... 31
Step 5: Use your stack resources ........................................................................................ 32
Step 6: Clean Up .............................................................................................................. 33
Learn Template Basics .............................................................................................................. 33
What is an AWS CloudFormation Template? ......................................................................... 33
Resources: Hello Bucket! .................................................................................................... 34
Resource Properties and Using Resources Together ............................................................... 34
Receiving User Input Using Input Parameters ....................................................................... 40
Specifying Conditional Values Using Mappings ..................................................................... 42
Constructed Values and Output Values ............................................................................... 44
Next Steps ....................................................................................................................... 46
Walkthrough: Updating a Stack .................................................................................................. 47
A Simple Application ........................................................................................................ 48
Create the Initial Stack ..................................................................................................... 53
Update the Application ..................................................................................................... 54
Changing Resource Properties ............................................................................................ 56
Adding Resource Properties ............................................................................................... 59
Change the Stack's Resources ............................................................................................ 60
Availability and Impact Considerations ................................................................................ 66
API Version 2010-05-15
iii

AWS CloudFormation User Guide

Related Resources ............................................................................................................ 67
Best Practices .................................................................................................................................. 68
Organize Your Stacks By Lifecycle and Ownership ........................................................................ 68
Use Cross-Stack References to Export Shared Resources ................................................................ 69
Use IAM to Control Access ......................................................................................................... 69
Verify Quotas for All Resource Types .......................................................................................... 69
Reuse Templates to Replicate Stacks in Multiple Environments ....................................................... 70
Use Nested Stacks to Reuse Common Template Patterns ............................................................... 70
Do Not Embed Credentials in Your Templates .............................................................................. 70
Use AWS-Specific Parameter Types ............................................................................................. 70
Use Parameter Constraints ........................................................................................................ 71
Use AWS::CloudFormation::Init to Deploy Software Applications on Amazon EC2 Instances ................. 71
Use the Latest Helper Scripts ..................................................................................................... 71
Validate Templates Before Using Them ....................................................................................... 71
Manage All Stack Resources Through AWS CloudFormation ........................................................... 72
Create Change Sets Before Updating Your Stacks ......................................................................... 72
Use Stack Policies ..................................................................................................................... 72
Use AWS CloudTrail to Log AWS CloudFormation Calls .................................................................. 72
Use Code Reviews and Revision Controls to Manage Your Templates ............................................... 73
Update Your Amazon EC2 Linux Instances Regularly ..................................................................... 73
Continuous Delivery .......................................................................................................................... 74
Walkthrough: Building a Pipeline for Test and Production Stacks .................................................... 74
Prerequisites .................................................................................................................... 74
Walkthrough Overview ...................................................................................................... 75
Step 1: Edit the Artifact and Upload It to an S3 Bucket ......................................................... 75
Step 2: Create the Pipeline Stack ....................................................................................... 76
Step 3: View the WordPress Stack ...................................................................................... 80
Step 4: Clean Up Resources .............................................................................................. 80
Configuration Properties Reference ............................................................................................. 81
Configuration Properties (Console) ..................................................................................... 81
Configuration Properties (JSON Object) .............................................................................. 83
AWS CloudFormation Artifacts ................................................................................................... 85
Stack Template File .......................................................................................................... 85
Template Configuration File ............................................................................................... 85
Using Parameter Override Functions with AWS CodePipeline Pipelines ............................................ 86
Fn::GetArtifactAtt ............................................................................................................. 86
Fn::GetParam ................................................................................................................... 87
Working with Stacks ......................................................................................................................... 90
Using the Console .................................................................................................................... 90
In This Section ................................................................................................................. 90
Logging In to the Console ................................................................................................. 91
Creating a Stack ............................................................................................................... 92
Creating an EC2 Key Pair ................................................................................................... 98
Estimating the Cost of Your Stack ...................................................................................... 99
Viewing Stack Data and Resources ..................................................................................... 99
Monitor and Roll Back Stack Operations ............................................................................ 102
Creating Quick-Create Links for Stacks .............................................................................. 103
Deleting a Stack ............................................................................................................. 105
Protecting a Stack From Being Deleted ............................................................................. 106
Viewing Deleted Stacks ................................................................................................... 107
Related Topics ................................................................................................................ 108
Using the AWS CLI .................................................................................................................. 108
Creating a Stack ............................................................................................................. 108
Describing and Listing Your Stacks .................................................................................... 109
Viewing Stack Event History ............................................................................................ 112
Listing Resources ............................................................................................................ 114
Retrieving a Template ..................................................................................................... 114
API Version 2010-05-15
iv

AWS CloudFormation User Guide

Validating a Template .....................................................................................................
Uploading Local Artifacts to an S3 Bucket .........................................................................
Quickly Deploying Templates with Transforms ...................................................................
Deleting a Stack .............................................................................................................
Stack Updates ........................................................................................................................
Update Behaviors of Stack Resources ................................................................................
Modifying a Stack Template .............................................................................................
Updating Stacks Using Change Sets ..................................................................................
Updating Stacks Directly .................................................................................................
Monitoring Progress ........................................................................................................
Canceling a Stack Update ................................................................................................
Prevent Updates to Stack Resources .................................................................................
Continue Rolling Back an Update .....................................................................................
Exporting Stack Output Values .................................................................................................
Exporting Stack Output Values vs. Using Nested Stacks .......................................................
Listing Exported Output Values ........................................................................................
Listing Stacks That Import an Exported Output Value .................................................................
Working with Nested Stacks ....................................................................................................
Working with Windows Stacks ..................................................................................................
In This Section ...............................................................................................................
Windows AMIs and Templates ..........................................................................................
Bootstrapping Windows Stacks .........................................................................................
Working with Templates ..................................................................................................................
Template Formats ...................................................................................................................
Template Anatomy .................................................................................................................
JSON ............................................................................................................................
YAML ............................................................................................................................
Template Sections ..........................................................................................................
Format Version ...............................................................................................................
Description ....................................................................................................................
Metadata .......................................................................................................................
Parameters ....................................................................................................................
Mappings .......................................................................................................................
Conditions .....................................................................................................................
Transform ......................................................................................................................
Resources ......................................................................................................................
Outputs .........................................................................................................................
What Is AWS CloudFormation Designer? ....................................................................................
Why Use Designer? .........................................................................................................
Interface Overview .........................................................................................................
How to Get Started ........................................................................................................
Walkthroughs .........................................................................................................................
Walkthrough: Use AWS CloudFormation Designer to Create a Basic Web Server .......................
Walkthrough: Use AWS CloudFormation Designer to Modify a Stack's Template ......................
Peer with a VPC in Another Account .................................................................................
Walkthrough: Refer to Resource Outputs in Another AWS CloudFormation Stack .....................
Create a Scalable, Load-balancing Web Server ...................................................................
Deploying Applications ....................................................................................................
Creating Wait Conditions .................................................................................................
Template Snippets ..................................................................................................................
General .........................................................................................................................
Auto Scaling ..................................................................................................................
AWS CloudFormation ......................................................................................................
CloudFront .....................................................................................................................
CloudWatch ...................................................................................................................
CloudWatch Logs ............................................................................................................
DynamoDB .....................................................................................................................
API Version 2010-05-15
v

115
116
117
117
118
118
119
122
136
139
140
141
150
153
153
154
154
155
157
157
157
157
162
162
163
163
164
164
165
166
166
167
182
187
191
196
199
202
202
204
213
213
213
230
241
248
250
260
276
280
280
288
292
296
303
307
333

AWS CloudFormation User Guide

Amazon EC2 .................................................................................................................. 337
Amazon ECS .................................................................................................................. 353
Amazon EFS ................................................................................................................... 369
Elastic Beanstalk ............................................................................................................. 384
Elastic Load Balancing ..................................................................................................... 386
IAM ............................................................................................................................... 387
AWS Lambda ................................................................................................................. 400
AWS OpsWorks .............................................................................................................. 404
Amazon Redshift ............................................................................................................ 410
Amazon RDS .................................................................................................................. 416
Route 53 ........................................................................................................................ 422
Amazon S3 .................................................................................................................... 426
Amazon SNS .................................................................................................................. 431
Amazon SQS .................................................................................................................. 432
Custom Resources ................................................................................................................... 432
How Custom Resources Work ........................................................................................... 432
Amazon Simple Notification Service-backed Custom Resources ............................................. 434
AWS Lambda-backed Custom Resources ............................................................................ 439
Custom Resource Reference ............................................................................................. 446
Using Regular Expressions ....................................................................................................... 458
Using CloudFormer to Create Templates .................................................................................... 458
Step 1: Create a CloudFormer Stack .................................................................................. 459
Step 2: Launch the CloudFormer Stack .............................................................................. 459
Step 3: Use CloudFormer to Create a Template .................................................................. 460
Step 4: Delete the CloudFormer Stack ............................................................................... 464
Working with AWS CloudFormation StackSets .................................................................................... 465
StackSets Concepts ................................................................................................................. 465
Administrator and target accounts .................................................................................... 466
Stack sets ...................................................................................................................... 466
Stack instances ............................................................................................................... 466
Stack set operations ....................................................................................................... 467
Stack set operation options ............................................................................................. 468
Tags .............................................................................................................................. 469
Stack set and stack instance status codes .......................................................................... 469
Prerequisites: Granting Permissions for Stack Set Operations ....................................................... 470
Set Up Basic Permissions for Stack Sets Operations ............................................................ 470
Set Up Advanced Permissions Options for Stack Set Operations ........................................... 473
Getting Started ...................................................................................................................... 478
Create a New Stack Set ................................................................................................... 478
Update Your Stack Set .................................................................................................... 483
Add Stacks to a Stack Set ............................................................................................... 488
Override Parameters on Stack Instances ............................................................................ 489
Delete Stack Instances .................................................................................................... 490
Delete Stack Sets ........................................................................................................... 492
Target account gates ............................................................................................................... 494
Setup Requirements ........................................................................................................ 494
Sample Lambda Account Gating Functions ........................................................................ 494
Best Practices ......................................................................................................................... 495
Defining the Template .................................................................................................... 495
Creating or Adding Stacks to the Stack Set ........................................................................ 495
Updating Stacks in a Stack Set ......................................................................................... 495
Limitations of StackSets .......................................................................................................... 496
Sample Templates .................................................................................................................. 496
Troubleshooting ..................................................................................................................... 497
Common reasons for stack operation failure ...................................................................... 497
Retrying failed stack creation or update operations ............................................................. 497
Stack instance deletion fails ............................................................................................. 498
API Version 2010-05-15
vi

AWS CloudFormation User Guide

Template Reference ........................................................................................................................
AWS Resource Types ...............................................................................................................
AWS::AmazonMQ::Broker .................................................................................................
AWS::AmazonMQ::Configuration .......................................................................................
AWS::ApiGateway::Account ...............................................................................................
AWS::ApiGateway::ApiKey ................................................................................................
AWS::ApiGateway::Authorizer ...........................................................................................
AWS::ApiGateway::BasePathMapping .................................................................................
AWS::ApiGateway::ClientCertificate ....................................................................................
AWS::ApiGateway::Deployment .........................................................................................
AWS::ApiGateway::DocumentationPart ...............................................................................
AWS::ApiGateway::DocumentationVersion ..........................................................................
AWS::ApiGateway::DomainName .......................................................................................
AWS::ApiGateway::GatewayResponse .................................................................................
AWS::ApiGateway::Method ...............................................................................................
AWS::ApiGateway::Model .................................................................................................
AWS::ApiGateway::RequestValidator ..................................................................................
AWS::ApiGateway::Resource ..............................................................................................
AWS::ApiGateway::RestApi ................................................................................................
AWS::ApiGateway::Stage ..................................................................................................
AWS::ApiGateway::UsagePlan ...........................................................................................
AWS::ApiGateway::UsagePlanKey ......................................................................................
AWS::ApiGateway::VpcLink ...............................................................................................
AWS::ApplicationAutoScaling::ScalableTarget ......................................................................
AWS::ApplicationAutoScaling::ScalingPolicy ........................................................................
AWS::AppSync::ApiKey .....................................................................................................
AWS::AppSync::DataSource ...............................................................................................
AWS::AppSync::GraphQLApi .............................................................................................
AWS::AppSync::GraphQLSchema .......................................................................................
AWS::AppSync::Resolver ...................................................................................................
AWS::Athena::NamedQuery ..............................................................................................
AWS::AutoScaling::AutoScalingGroup .................................................................................
AWS::AutoScaling::LaunchConfiguration .............................................................................
AWS::AutoScaling::LifecycleHook .......................................................................................
AWS::AutoScaling::ScalingPolicy ........................................................................................
AWS::AutoScaling::ScheduledAction ...................................................................................
AWS::AutoScalingPlans::ScalingPlan ..................................................................................
AWS::Batch::ComputeEnvironment ....................................................................................
AWS::Batch::JobDefinition ................................................................................................
AWS::Batch::JobQueue .....................................................................................................
AWS::Budgets::Budget .....................................................................................................
AWS::CertificateManager::Certificate ..................................................................................
AWS::Cloud9::EnvironmentEC2 ..........................................................................................
AWS::CloudFormation::Authentication ................................................................................
AWS::CloudFormation::CustomResource .............................................................................
AWS::CloudFormation::Init ................................................................................................
AWS::CloudFormation::Interface ........................................................................................
AWS::CloudFormation::Stack .............................................................................................
AWS::CloudFormation::WaitCondition ................................................................................
AWS::CloudFormation::WaitConditionHandle ......................................................................
AWS::CloudFront::Distribution ...........................................................................................
AWS::CloudFront::CloudFrontOriginAccessIdentity ...............................................................
AWS::CloudFront::StreamingDistribution ............................................................................
AWS::CloudTrail::Trail .......................................................................................................
AWS::CloudWatch::Alarm .................................................................................................
AWS::CloudWatch::Dashboard ...........................................................................................
AWS::CodeBuild::Project ...................................................................................................
API Version 2010-05-15
vii

499
499
506
513
516
518
522
525
527
528
531
534
538
545
548
556
558
561
563
570
574
577
578
581
594
601
604
608
611
613
618
620
628
637
640
646
650
651
655
658
660
663
666
668
674
677
691
694
696
699
700
703
705
708
714
719
720

AWS CloudFormation User Guide

AWS::CodeCommit::Repository ..........................................................................................
AWS::CodeDeploy::Application ..........................................................................................
AWS::CodeDeploy::DeploymentConfig ................................................................................
AWS::CodeDeploy::DeploymentGroup ................................................................................
AWS::CodePipeline::CustomActionType ..............................................................................
AWS::CodePipeline::Pipeline .............................................................................................
AWS::CodePipeline::Webhook ...........................................................................................
AWS::Cognito::IdentityPool ...............................................................................................
AWS::Cognito::IdentityPoolRoleAttachment ........................................................................
AWS::Cognito::UserPool ...................................................................................................
AWS::Cognito::UserPoolClient ...........................................................................................
AWS::Cognito::UserPoolGroup ...........................................................................................
AWS::Cognito::UserPoolUser .............................................................................................
AWS::Cognito::UserPoolUserToGroupAttachment ................................................................
AWS::Config::AggregationAuthorization .............................................................................
AWS::Config::ConfigRule ..................................................................................................
AWS::Config::ConfigurationAggregator ...............................................................................
AWS::Config::ConfigurationRecorder ..................................................................................
AWS::Config::DeliveryChannel ...........................................................................................
AWS::DataPipeline::Pipeline ..............................................................................................
AWS::DAX::Cluster ...........................................................................................................
AWS::DAX::ParameterGroup ..............................................................................................
AWS::DAX::SubnetGroup ..................................................................................................
AWS::DirectoryService::MicrosoftAD ...................................................................................
AWS::DirectoryService::SimpleAD ......................................................................................
AWS::DMS::Certificate ......................................................................................................
AWS::DMS::Endpoint ........................................................................................................
AWS::DMS::EventSubscription ...........................................................................................
AWS::DMS::ReplicationInstance .........................................................................................
AWS::DMS::ReplicationSubnetGroup ..................................................................................
AWS::DMS::ReplicationTask ...............................................................................................
AWS::DynamoDB::Table ...................................................................................................
AWS::EC2::CustomerGateway ............................................................................................
AWS::EC2::DHCPOptions ..................................................................................................
AWS::EC2::EgressOnlyInternetGateway ...............................................................................
AWS::EC2::EIP .................................................................................................................
AWS::EC2::EIPAssociation .................................................................................................
AWS::EC2::FlowLog ..........................................................................................................
AWS::EC2::Host ...............................................................................................................
AWS::EC2::Instance ..........................................................................................................
AWS::EC2::InternetGateway ..............................................................................................
AWS::EC2::LaunchTemplate ..............................................................................................
AWS::EC2::NatGateway ....................................................................................................
AWS::EC2::NetworkAcl .....................................................................................................
AWS::EC2::NetworkAclEntry ..............................................................................................
AWS::EC2::NetworkInterface .............................................................................................
AWS::EC2::NetworkInterfaceAttachment ............................................................................
AWS::EC2::NetworkInterfacePermission ..............................................................................
AWS::EC2::PlacementGroup ..............................................................................................
AWS::EC2::Route .............................................................................................................
AWS::EC2::RouteTable ......................................................................................................
AWS::EC2::SecurityGroup .................................................................................................
AWS::EC2::SecurityGroupEgress .........................................................................................
AWS::EC2::SecurityGroupIngress ........................................................................................
AWS::EC2::SpotFleet ........................................................................................................
AWS::EC2::Subnet ...........................................................................................................
AWS::EC2::SubnetCidrBlock ..............................................................................................
API Version 2010-05-15
viii

729
731
733
735
751
755
760
763
766
768
772
774
776
779
780
788
794
797
799
801
810
816
818
821
825
828
830
835
838
842
845
848
861
863
867
868
870
875
877
879
890
891
893
895
897
901
906
908
910
911
915
917
921
925
932
935
938

AWS CloudFormation User Guide

AWS::EC2::SubnetNetworkAclAssociation ............................................................................ 940
AWS::EC2::SubnetRouteTableAssociation ............................................................................ 942
AWS::EC2::Volume ........................................................................................................... 944
AWS::EC2::VolumeAttachment .......................................................................................... 948
AWS::EC2::VPC ................................................................................................................ 950
AWS::EC2::VPCCidrBlock ................................................................................................... 953
AWS::EC2::VPCDHCPOptionsAssociation ............................................................................. 956
AWS::EC2::VPCEndpoint ................................................................................................... 958
AWS::EC2::VPCEndpointConnectionNotification ................................................................... 961
AWS::EC2::VPCEndpointService ......................................................................................... 963
AWS::EC2::VPCEndpointServicePermissions ......................................................................... 964
AWS::EC2::VPCGatewayAttachment ................................................................................... 965
AWS::EC2::VPCPeeringConnection ..................................................................................... 967
AWS::EC2::VPNConnection ................................................................................................ 977
AWS::EC2::VPNConnectionRoute ....................................................................................... 980
AWS::EC2::VPNGateway ................................................................................................... 982
AWS::EC2::VPNGatewayRoutePropagation .......................................................................... 984
AWS::ECR::Repository ...................................................................................................... 985
AWS::ECS::Cluster ............................................................................................................ 989
AWS::ECS::Service ........................................................................................................... 991
AWS::ECS::TaskDefinition ................................................................................................ 1002
AWS::EFS::FileSystem ..................................................................................................... 1009
AWS::EFS::MountTarget .................................................................................................. 1013
AWS::EKS::Cluster .......................................................................................................... 1015
AWS::ElastiCache::CacheCluster ....................................................................................... 1018
AWS::ElastiCache::ParameterGroup .................................................................................. 1026
AWS::ElastiCache::ReplicationGroup ................................................................................. 1028
AWS::ElastiCache::SecurityGroup ..................................................................................... 1039
AWS::ElastiCache::SecurityGroupIngress ........................................................................... 1040
AWS::ElastiCache::SubnetGroup ....................................................................................... 1041
AWS::ElasticBeanstalk::Application ................................................................................... 1043
AWS::ElasticBeanstalk::ApplicationVersion ........................................................................ 1045
AWS::ElasticBeanstalk::ConfigurationTemplate .................................................................. 1047
AWS::ElasticBeanstalk::Environment ................................................................................. 1050
AWS::ElasticLoadBalancing::LoadBalancer ......................................................................... 1063
AWS::ElasticLoadBalancingV2::Listener ............................................................................. 1074
AWS::ElasticLoadBalancingV2::ListenerCertificate .............................................................. 1077
AWS::ElasticLoadBalancingV2::ListenerRule ....................................................................... 1080
AWS::ElasticLoadBalancingV2::LoadBalancer ..................................................................... 1082
AWS::ElasticLoadBalancingV2::TargetGroup ...................................................................... 1088
AWS::Elasticsearch::Domain ............................................................................................ 1096
AWS::EMR::Cluster ......................................................................................................... 1104
AWS::EMR::InstanceFleetConfig ....................................................................................... 1122
AWS::EMR::InstanceGroupConfig ..................................................................................... 1124
AWS::EMR::SecurityConfiguration .................................................................................... 1127
AWS::EMR::Step ............................................................................................................ 1130
AWS::Events::Rule .......................................................................................................... 1132
AWS::GameLift::Alias ..................................................................................................... 1138
AWS::GameLift::Build ..................................................................................................... 1140
AWS::GameLift::Fleet ..................................................................................................... 1142
AWS::Glue::Classifier ...................................................................................................... 1146
AWS::Glue::Connection ................................................................................................... 1147
AWS::Glue::Crawler ........................................................................................................ 1149
AWS::Glue::Database ...................................................................................................... 1154
AWS::Glue::DevEndpoint ................................................................................................ 1155
AWS::Glue::Job .............................................................................................................. 1157
AWS::Glue::Partition ...................................................................................................... 1162
API Version 2010-05-15
ix

AWS CloudFormation User Guide

AWS::Glue::Table ...........................................................................................................
AWS::Glue::Trigger .........................................................................................................
AWS::GuardDuty::Detector ..............................................................................................
AWS::GuardDuty::Filter ...................................................................................................
AWS::GuardDuty::Master ................................................................................................
AWS::GuardDuty::Member ..............................................................................................
AWS::GuardDuty::IPSet ...................................................................................................
AWS::GuardDuty::ThreatIntelSet ......................................................................................
AWS::IAM::AccessKey .....................................................................................................
AWS::IAM::Group ...........................................................................................................
AWS::IAM::InstanceProfile ...............................................................................................
AWS::IAM::ManagedPolicy ..............................................................................................
AWS::IAM::Policy ...........................................................................................................
AWS::IAM::Role .............................................................................................................
AWS::IAM::ServiceLinkedRole ..........................................................................................
AWS::IAM::User .............................................................................................................
AWS::IAM::UserToGroupAddition .....................................................................................
AWS::Inspector::AssessmentTarget ...................................................................................
AWS::Inspector::AssessmentTemplate ...............................................................................
AWS::Inspector::ResourceGroup .......................................................................................
AWS::IoT::Certificate ......................................................................................................
AWS::IoT::Policy ............................................................................................................
AWS::IoT::PolicyPrincipalAttachment ................................................................................
AWS::IoT::Thing .............................................................................................................
AWS::IoT::ThingPrincipalAttachment ................................................................................
AWS::IoT::TopicRule .......................................................................................................
AWS::Kinesis::Stream .....................................................................................................
AWS::KinesisAnalytics::Application ...................................................................................
AWS::KinesisAnalytics::ApplicationOutput .........................................................................
AWS::KinesisAnalytics::ApplicationReferenceDataSource .....................................................
AWS::KinesisFirehose::DeliveryStream ..............................................................................
AWS::KMS::Alias ............................................................................................................
AWS::KMS::Key ..............................................................................................................
AWS::Lambda::EventSourceMapping ................................................................................
AWS::Lambda::Alias .......................................................................................................
AWS::Lambda::Function .................................................................................................
AWS::Lambda::Permission ...............................................................................................
AWS::Lambda::Version ...................................................................................................
AWS::Logs::Destination ..................................................................................................
AWS::Logs::LogGroup .....................................................................................................
AWS::Logs::LogStream ...................................................................................................
AWS::Logs::MetricFilter ..................................................................................................
AWS::Logs::SubscriptionFilter ..........................................................................................
AWS::Neptune::DBCluster ...............................................................................................
AWS::Neptune::DBClusterParameterGroup ........................................................................
AWS::Neptune::DBInstance .............................................................................................
AWS::Neptune::DBParameterGroup ..................................................................................
AWS::Neptune::DBSubnetGroup ......................................................................................
AWS::OpsWorks::App .....................................................................................................
AWS::OpsWorks::ElasticLoadBalancerAttachment ...............................................................
AWS::OpsWorks::Instance ...............................................................................................
AWS::OpsWorks::Layer ...................................................................................................
AWS::OpsWorks::Stack ...................................................................................................
AWS::OpsWorks::UserProfile ...........................................................................................
AWS::OpsWorks::Volume ................................................................................................
AWS::RDS::DBCluster .....................................................................................................
AWS::RDS::DBClusterParameterGroup ..............................................................................
API Version 2010-05-15
x

1164
1165
1171
1172
1175
1177
1180
1182
1184
1186
1188
1190
1194
1197
1204
1205
1208
1209
1211
1214
1215
1218
1220
1221
1224
1225
1228
1231
1234
1235
1237
1245
1247
1251
1254
1257
1263
1265
1267
1270
1272
1273
1275
1278
1282
1284
1288
1290
1293
1297
1298
1305
1316
1327
1329
1331
1338

AWS CloudFormation User Guide

AWS::RDS::DBInstance ....................................................................................................
AWS::RDS::DBParameterGroup ........................................................................................
AWS::RDS::DBSecurityGroup ...........................................................................................
AWS::RDS::DBSecurityGroupIngress .................................................................................
AWS::RDS::DBSubnetGroup .............................................................................................
AWS::RDS::EventSubscription ..........................................................................................
AWS::RDS::OptionGroup .................................................................................................
AWS::Redshift::Cluster ....................................................................................................
AWS::Redshift::ClusterParameterGroup ............................................................................
AWS::Redshift::ClusterSecurityGroup ................................................................................
AWS::Redshift::ClusterSecurityGroupIngress ......................................................................
AWS::Redshift::ClusterSubnetGroup .................................................................................
AWS::Route53::HealthCheck ...........................................................................................
AWS::Route53::HostedZone ............................................................................................
AWS::Route53::RecordSet ...............................................................................................
AWS::Route53::RecordSetGroup ......................................................................................
AWS::S3::Bucket ............................................................................................................
AWS::S3::BucketPolicy ....................................................................................................
AWS::SageMaker::Endpoint .............................................................................................
AWS::SageMaker::EndpointConfig ....................................................................................
AWS::SageMaker::Model .................................................................................................
AWS::SageMaker::NotebookInstance ................................................................................
AWS::SageMaker::NotebookInstanceLifecycleConfig ...........................................................
AWS::SDB::Domain ........................................................................................................
AWS::ServiceCatalog::AcceptedPortfolioShare ...................................................................
AWS::ServiceCatalog::CloudFormationProduct ...................................................................
AWS::ServiceCatalog::CloudFormationProvisionedProduct ...................................................
AWS::ServiceCatalog::LaunchNotificationConstraint ...........................................................
AWS::ServiceCatalog::LaunchRoleConstraint ......................................................................
AWS::ServiceCatalog::LaunchTemplateConstraint ...............................................................
AWS::ServiceCatalog::Portfolio ........................................................................................
AWS::ServiceCatalog::PortfolioPrincipalAssociation ............................................................
AWS::ServiceCatalog::PortfolioProductAssociation .............................................................
AWS::ServiceCatalog::PortfolioShare ................................................................................
AWS::ServiceCatalog::TagOption .....................................................................................
AWS::ServiceCatalog::TagOptionAssociation ......................................................................
AWS::ServiceDiscovery::Instance ......................................................................................
AWS::ServiceDiscovery::PrivateDnsNamespace ...................................................................
AWS::ServiceDiscovery::PublicDnsNamespace ....................................................................
AWS::ServiceDiscovery::Service ........................................................................................
AWS::SES::ConfigurationSet ............................................................................................
AWS::SES::ConfigurationSetEventDestination ....................................................................
AWS::SES::ReceiptFilter ..................................................................................................
AWS::SES::ReceiptRule ...................................................................................................
AWS::SES::ReceiptRuleSet ...............................................................................................
AWS::SES::Template .......................................................................................................
AWS::SNS::Subscription ..................................................................................................
AWS::SNS::Topic ............................................................................................................
AWS::SNS::TopicPolicy ....................................................................................................
AWS::SQS::Queue ..........................................................................................................
AWS::SQS::QueuePolicy ..................................................................................................
AWS::SSM::Association ...................................................................................................
AWS::SSM::Document ....................................................................................................
AWS::SSM::MaintenanceWindow ......................................................................................
AWS::SSM::MaintenanceWindowTarget .............................................................................
AWS::SSM::MaintenanceWindowTask ................................................................................
AWS::SSM::Parameter ....................................................................................................
API Version 2010-05-15
xi

1341
1357
1360
1363
1365
1367
1370
1373
1381
1384
1386
1388
1390
1392
1395
1401
1403
1419
1421
1425
1430
1435
1440
1444
1444
1445
1448
1453
1455
1456
1458
1460
1461
1463
1464
1465
1466
1468
1470
1471
1473
1475
1479
1480
1484
1486
1488
1492
1494
1495
1503
1504
1507
1511
1513
1515
1518

AWS CloudFormation User Guide

AWS::SSM::PatchBaseline ...............................................................................................
AWS::SSM::ResourceDataSync .........................................................................................
AWS::StepFunctions::Activity ...........................................................................................
AWS::StepFunctions::StateMachine ..................................................................................
AWS::WAF::ByteMatchSet ...............................................................................................
AWS::WAF::IPSet ...........................................................................................................
AWS::WAF::Rule ............................................................................................................
AWS::WAF::SizeConstraintSet ..........................................................................................
AWS::WAF::SqlInjectionMatchSet .....................................................................................
AWS::WAF::WebACL .......................................................................................................
AWS::WAF::XssMatchSet .................................................................................................
AWS::WAFRegional::ByteMatchSet ...................................................................................
AWS::WAFRegional::IPSet ...............................................................................................
AWS::WAFRegional::Rule ................................................................................................
AWS::WAFRegional::SizeConstraintSet ..............................................................................
AWS::WAFRegional::SqlInjectionMatchSet .........................................................................
AWS::WAFRegional::WebACL ...........................................................................................
AWS::WAFRegional::WebACLAssociation ...........................................................................
AWS::WAFRegional::XssMatchSet .....................................................................................
AWS::WorkSpaces::Workspace .........................................................................................
Resource Property Types ........................................................................................................
Amazon MQ Broker ConfigurationId ................................................................................
Amazon MQ Broker MaintenanceWindow .........................................................................
Amazon MQ Broker User ...............................................................................................
API Gateway ApiKey StageKey ........................................................................................
API Gateway Deployment StageDescription ......................................................................
API Gateway Deployment MethodSetting .........................................................................
API Gateway DocumentationPart Location .......................................................................
API Gateway DomainName EndpointConfiguration ............................................................
API Gateway Method Integration ....................................................................................
API Gateway Method Integration IntegrationResponse .......................................................
API Gateway Method MethodResponse ............................................................................
API Gateway RestApi S3Location ....................................................................................
API Gateway RestApi EndpointConfiguration ....................................................................
API Gateway Stage MethodSetting ..................................................................................
API Gateway UsagePlan ApiStage ...................................................................................
API Gateway UsagePlan QuotaSettings ............................................................................
API Gateway UsagePlan ThrottleSettings .........................................................................
Application Auto Scaling ScalingPolicy CustomizedMetricSpecification .................................
Application Auto Scaling ScalingPolicy MetricDimension ....................................................
Application Auto Scaling ScalingPolicy PredefinedMetricSpecification ..................................
Application Auto Scaling ScalingPolicy StepScalingPolicyConfiguration ................................
Application Auto Scaling ScalingPolicy StepScalingPolicyConfiguration StepAdjustment .........
Application Auto Scaling ScalingPolicy TargetTrackingScalingPolicyConfiguration ..................
Application Auto Scaling ScalableTarget ScalableTargetAction ............................................
Application Auto Scaling ScalableTarget ScheduledAction ..................................................
AWS AppSync DataSource DynamoDBConfig ....................................................................
AWS AppSync DataSource HttpConfig .............................................................................
AWS AppSync DataSource ElasticsearchConfig ..................................................................
AWS AppSync DataSource LambdaConfig ........................................................................
AWS AppSync GraphQLApi LogConfig .............................................................................
AWS AppSync GraphQLApi UserPoolConfig ......................................................................
AWS AppSync GraphQLApi OpenId Connect Config ...........................................................
Amazon EC2 Auto Scaling Block Device Mapping ..............................................................
Amazon EC2 Auto Scaling EBS Block Device .....................................................................
Amazon EC2 Auto Scaling AutoScalingGroup LifecycleHookSpecification ..............................
Amazon EC2 Auto Scaling AutoScalingGroup LaunchTemplateSpecification ..........................
API Version 2010-05-15
xii

1522
1524
1527
1529
1532
1535
1539
1541
1544
1547
1551
1555
1558
1561
1563
1567
1570
1574
1575
1579
1581
1594
1595
1596
1597
1598
1600
1602
1604
1604
1607
1609
1610
1611
1612
1614
1615
1615
1616
1618
1618
1619
1621
1622
1624
1624
1626
1627
1628
1629
1630
1630
1632
1633
1634
1636
1639

AWS CloudFormation User Guide

Amazon EC2 Auto Scaling AutoScalingGroup MetricsCollection ...........................................
Amazon EC2 Auto Scaling AutoScalingGroup NotificationConfiguration ................................
Amazon EC2 Auto Scaling AutoScalingGroup TagProperty ..................................................
Amazon EC2 Auto Scaling ScalingPolicy CustomizedMetricSpecification ...............................
Amazon EC2 Auto Scaling ScalingPolicy MetricDimension ..................................................
Amazon EC2 Auto Scaling ScalingPolicy PredefinedMetricSpecification ................................
Amazon EC2 Auto Scaling ScalingPolicy StepAdjustments ..................................................
Amazon EC2 Auto Scaling ScalingPolicy TargetTrackingConfiguration ..................................
AWS Auto Scaling ScalingPlan ApplicationSource ..............................................................
AWS Auto Scaling ScalingPlan CustomizedScalingMetricSpecification ...................................
AWS Auto Scaling ScalingPlan MetricDimension ................................................................
AWS Auto Scaling ScalingPlan PredefinedScalingMetricSpecification ....................................
AWS Auto Scaling ScalingPlan ScalingInstruction ..............................................................
AWS Auto Scaling ScalingPlan TagFilter ...........................................................................
AWS Auto Scaling ScalingPlan TargetTrackingConfiguration ...............................................
AWS Batch ComputeEnvironment ComputeResources ........................................................
AWS Batch JobDefinition ContainerProperties ..................................................................
AWS Batch JobDefinition Environment ............................................................................
AWS Batch JobDefinition MountPoints ............................................................................
AWS Batch JobDefinition RetryStrategy ...........................................................................
AWS Batch JobDefinition Timeout ...................................................................................
AWS Batch JobDefinition Ulimit ......................................................................................
AWS Batch JobDefinition Volumes ..................................................................................
AWS Batch JobDefinition VolumesHost ............................................................................
AWS Batch JobQueue ComputeEnvironmentOrder ............................................................
Billing and Cost Management Budget BudgetData ............................................................
Billing and Cost Management Budget CostTypes ...............................................................
Billing and Cost Management Budget Notification ............................................................
Billing and Cost Management Budget NotificationWithSubscribers ......................................
Billing and Cost Management Budget Spend ....................................................................
Billing and Cost Management Budget Subscriber ..............................................................
Billing and Cost Management Budget TimePeriod .............................................................
AWS Cloud9 EnvironmentEC2 Repository .........................................................................
ACM Certificate DomainValidationOption .........................................................................
AWS CloudFormation Stack Parameters ...........................................................................
AWS CloudFormation Interface Label ..............................................................................
AWS CloudFormation Interface ParameterGroup ...............................................................
AWS CloudFormation Interface ParameterLabel ................................................................
CloudFront CloudFrontOriginAccessIdentity CloudFrontOriginAccessIdentityConfig ................
CloudFront Distribution CacheBehavior ............................................................................
CloudFront Distribution Cookies .....................................................................................
CloudFront Distribution CustomErrorResponse ..................................................................
CloudFront Distribution CustomOriginConfig ....................................................................
CloudFront Distribution DefaultCacheBehavior ..................................................................
CloudFront Distribution DistributionConfig .......................................................................
CloudFront Distribution ForwardedValues ........................................................................
CloudFront Distribution GeoRestriction ............................................................................
CloudFront Distribution LambdaFunctionAssociation .........................................................
CloudFront Distribution Logging .....................................................................................
CloudFront Distribution Origin ........................................................................................
CloudFront Distribution OriginCustomHeader ...................................................................
CloudFront Distribution Restrictions ................................................................................
CloudFront Distribution S3Origin ....................................................................................
CloudFront Distribution ViewerCertificate ........................................................................
CloudFront StreamingDistribution Logging .......................................................................
CloudFront StreamingDistribution S3Origin ......................................................................
CloudFront StreamingDistribution StreamingDistributionConfig ..........................................
API Version 2010-05-15
xiii

1640
1641
1642
1644
1645
1646
1647
1648
1649
1650
1652
1652
1653
1655
1656
1658
1660
1664
1664
1665
1666
1667
1668
1668
1669
1670
1672
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1685
1686
1689
1690
1691
1692
1695
1699
1700
1701
1702
1703
1705
1705
1706
1707
1708
1709
1710

AWS CloudFormation User Guide

CloudFront StreamingDistribution Tag .............................................................................
CloudFront StreamingDistribution TrustedSigners .............................................................
CloudTrail Trail EventSelector .........................................................................................
CloudTrail Trail DataResource .........................................................................................
CloudWatch Metric Dimension ........................................................................................
CloudWatch Events Rule EcsParameters ...........................................................................
CloudWatch Events Rule InputTransformer .......................................................................
CloudWatch Events Rule KinesisParameters ......................................................................
CloudWatch Events Rule RunCommandParameters ............................................................
CloudWatch Events Rule RunCommandTarget ..................................................................
CloudWatch Events Rule Target ......................................................................................
CloudWatch Logs MetricFilter MetricTransformation Property .............................................
AWS CodeBuild Project Artifacts .....................................................................................
AWS CodeBuild Project Environment ...............................................................................
AWS CodeBuild Project EnvironmentVariable ....................................................................
AWS CodeBuild Project ProjectCache ...............................................................................
AWS CodeBuild Project Source .......................................................................................
AWS CodeBuild Project SourceAuth .................................................................................
AWS CodeBuild Project ProjectTriggers ............................................................................
AWS CodeBuild Project VpcConfig ...................................................................................
AWS CodeCommit Repository Trigger ..............................................................................
AWS CodeDeploy DeploymentConfig MinimumHealthyHosts ..............................................
AWS CodeDeploy DeploymentGroup Alarm ......................................................................
AWS CodeDeploy DeploymentGroup AlarmConfiguration ...................................................
AWS CodeDeploy DeploymentGroup AutoRollbackConfiguration .........................................
AWS CodeDeploy DeploymentGroup Deployment .............................................................
AWS CodeDeploy DeploymentGroup DeploymentStyle ......................................................
AWS CodeDeploy DeploymentGroup ELBInfo ....................................................................
AWS CodeDeploy DeploymentGroup LoadBalancerInfo ......................................................
AWS CodeDeploy DeploymentGroup TargetGroupInfo .......................................................
AWS CodeDeploy DeploymentGroup Deployment Revision .................................................
AWS CodeDeploy DeploymentGroup Deployment Revision GitHubLocation ...........................
AWS CodeDeploy DeploymentGroup Deployment Revision S3Location .................................
AWS CodeDeploy DeploymentGroup Ec2TagFilters ............................................................
AWS CodeDeploy DeploymentGroup OnPremisesInstanceTagFilters .....................................
AWS CodeDeploy DeploymentGroup TriggerConfig ...........................................................
AWS CodePipeline CustomActionType ArtifactDetails ........................................................
AWS CodePipeline CustomActionType ConfigurationProperties ...........................................
AWS CodePipeline CustomActionType Settings .................................................................
AWS CodePipeline Pipeline ArtifactStore .........................................................................
AWS CodePipeline Pipeline ArtifactStore EncryptionKey .....................................................
AWS CodePipeline Pipeline DisableInboundStageTransitions ...............................................
AWS CodePipeline Pipeline Stages ..................................................................................
AWS CodePipeline Pipeline Stages Actions .......................................................................
AWS CodePipeline Pipeline Stages Actions ActionTypeId ....................................................
AWS CodePipeline Pipeline Stages Actions InputArtifacts ...................................................
AWS CodePipeline Pipeline Stages Actions OutputArtifacts ................................................
AWS CodePipeline Pipeline Stages Blockers ......................................................................
AWS CodePipeline Webhook WebhookAuthConfiguration ...................................................
AWS CodePipeline Webhook WebhookFilterRule ...............................................................
Amazon Cognito IdentityPool CognitoStreams ..................................................................
Amazon Cognito IdentityPool PushSync ...........................................................................
Amazon Cognito IdentityPoolRoleAttachment RoleMapping ...............................................
Amazon Cognito IdentityPoolRoleAttachment MappingRule ...............................................
Amazon Cognito IdentityPool CognitoIdentityProvider .......................................................
Amazon Cognito IdentityPoolRoleAttachment RoleMapping RulesConfiguration ....................
Amazon Cognito UserPool AdminCreateUserConfig ...........................................................
API Version 2010-05-15
xiv

1712
1713
1714
1715
1716
1718
1719
1720
1720
1721
1722
1727
1728
1730
1731
1732
1733
1735
1736
1737
1738
1739
1740
1740
1741
1742
1743
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1754
1756
1757
1758
1759
1759
1760
1762
1763
1763
1764
1765
1765
1766
1767
1768
1769
1770
1771
1772

AWS CloudFormation User Guide

Amazon Cognito UserPool DeviceConfiguration ................................................................
Amazon Cognito UserPool EmailConfiguration ..................................................................
Amazon Cognito UserPool InviteMessageTemplate ............................................................
Amazon Cognito UserPool LambdaConfig ........................................................................
Amazon Cognito UserPool NumberAttributeConstraints .....................................................
Amazon Cognito UserPool PasswordPolicy .......................................................................
Amazon Cognito UserPool Policies ..................................................................................
Amazon Cognito UserPool SchemaAttribute .....................................................................
Amazon Cognito UserPool SmsConfiguration ...................................................................
Amazon Cognito UserPool StringAttributeConstraints ........................................................
Amazon Cognito UserPoolUser AttributeType ...................................................................
Amazon Cognito UserPool InviteMessageTemplate ............................................................
AWS Config ConfigRule Scope ........................................................................................
AWS Config ConfigRule Source .......................................................................................
AWS Config ConfigRule SourceDetails .............................................................................
AWS Config ConfigurationAggregator AccountAggregationSource .......................................
AWS Config ConfigurationAggregator OrganizationAggregationSource .................................
AWS Config ConfigurationRecorder RecordingGroup ..........................................................
AWS Config DeliveryChannel ConfigSnapshotDeliveryProperties .........................................
AWS Data Pipeline Pipeline ParameterObjects ..................................................................
AWS Data Pipeline Parameter Objects Attributes ..............................................................
AWS Data Pipeline Pipeline ParameterValues ...................................................................
AWS Data Pipeline PipelineObject ...................................................................................
AWS Data Pipeline Pipeline Field ....................................................................................
AWS Data Pipeline Pipeline PipelineTags .........................................................................
AWS DMS Endpoint DynamoDBSettings ...........................................................................
AWS DMS Endpoint MongoDbSettings .............................................................................
AWS DMS Endpoint S3Settings .......................................................................................
AWS Directory Service MicrosoftAD VpcSettings ...............................................................
AWS Directory Service SimpleAD VpcSettings ...................................................................
DAX Cluster SSESpecification .........................................................................................
DynamoDB Table AttributeDefinition ...............................................................................
DynamoDB Table GlobalSecondaryIndex ..........................................................................
DynamoDB Table KeySchema .........................................................................................
DynamoDB Table LocalSecondaryIndex ............................................................................
DynamoDB Table PointInTimeRecoverySpecification ..........................................................
DynamoDB Table Projection ...........................................................................................
DynamoDB Table ProvisionedThroughput ........................................................................
DynamoDB SSESpecification ...........................................................................................
DynamoDB Table StreamSpecification .............................................................................
DynamoDB Table TimeToLiveSpecification .......................................................................
Amazon EC2 Block Device Mapping Property ....................................................................
Amazon Elastic Block Store Block Device Property ............................................................
Amazon EC2 Instance CreditSpecification .........................................................................
Amazon EC2 Instance ElasticGpuSpecification ...................................................................
Amazon EC2 Instance LaunchTemplateSpecification ..........................................................
Amazon EC2 Instance SsmAssociations AssociationParameters ............................................
Amazon EC2 Instance SsmAssociations ............................................................................
Amazon EC2 LaunchTemplate BlockDeviceMapping ...........................................................
Amazon EC2 LaunchTemplate CreditSpecification .............................................................
Amazon EC2 LaunchTemplate Ebs ...................................................................................
Amazon EC2 LaunchTemplate ElasticGpuSpecification .......................................................
Amazon EC2 LaunchTemplate IamInstanceProfile ..............................................................
Amazon EC2 LaunchTemplate InstanceMarketOptions .......................................................
Amazon EC2 LaunchTemplate Ipv6Add ............................................................................
Amazon EC2 LaunchTemplate LaunchTemplateData ..........................................................
Amazon EC2 LaunchTemplate Monitoring ........................................................................
API Version 2010-05-15
xv

1773
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1791
1792
1794
1795
1796
1797
1799
1800
1801
1802
1802
1803
1804
1805
1806
1807
1808
1809
1809
1810
1811
1813
1814
1815
1816
1817
1818
1818
1820
1820
1822
1823
1824
1825
1826
1830

AWS CloudFormation User Guide

Amazon EC2 LaunchTemplate NetworkInterface ...............................................................
Amazon EC2 LaunchTemplate Placement .........................................................................
Amazon EC2 LaunchTemplate PrivateIpAdd ......................................................................
Amazon EC2 LaunchTemplate SpotOptions ......................................................................
Amazon EC2 LaunchTemplate TagSpecification .................................................................
EC2 MountPoint ...........................................................................................................
EC2 Network Interface ..................................................................................................
EC2 NetworkAclEntry Icmp ............................................................................................
EC2 NetworkAclEntry PortRange .....................................................................................
EC2 NetworkInterface Ipv6Addresses ...............................................................................
EC2 Network Interface Private IP Specification .................................................................
EC2 Security Group Rule ................................................................................................
Amazon EC2 SpotFleet SpotFleetRequestConfigData .........................................................
Amazon EC2 SpotFleet LaunchSpecifications ....................................................................
Amazon EC2 SpotFleet BlockDeviceMappings ...................................................................
Amazon EC2 SpotFleet Ebs ............................................................................................
Amazon EC2 SpotFleet FleetLaunchTemplateSpecification ..................................................
Amazon EC2 SpotFleet IamInstanceProfile .......................................................................
Amazon EC2 SpotFleet LaunchTemplateConfig .................................................................
Amazon EC2 SpotFleet LaunchTemplateOverrides .............................................................
Amazon EC2 SpotFleet Monitoring ..................................................................................
Amazon EC2 SpotFleet NetworkInterfaces ........................................................................
Amazon EC2 SpotFleet PrivateIpAddresses .......................................................................
Amazon EC2 SpotFleet Placement ..................................................................................
Amazon EC2 SpotFleet SecurityGroups ............................................................................
Amazon EC2 SpotFleet SpotFleetTagSpecification .............................................................
EC2 VPNConnection VpnTunnelOptionsSpecification .........................................................
Amazon ECS Service AwsVpcConfiguration .......................................................................
Amazon ECR Repository LifecyclePolicy ...........................................................................
Amazon ECS Service DeploymentConfiguration ................................................................
Amazon ECS Service NetworkConfiguration ......................................................................
Amazon ECS Service PlacementConstraint ........................................................................
Amazon ECS Service PlacementStrategies ........................................................................
Amazon ECS Service LoadBalancers .................................................................................
Amazon ECS Service ServiceRegistry ...............................................................................
Amazon ECS TaskDefinition HealthCheck .........................................................................
Amazon ECS TaskDefinition ContainerDefinition ...............................................................
Amazon ECS TaskDefinition Device ..................................................................................
Amazon ECS TaskDefinition HostEntry .............................................................................
Amazon ECS TaskDefinition KernelCapabilities ..................................................................
Amazon ECS TaskDefinition KeyValuePair .........................................................................
Amazon ECS TaskDefinition LinuxParameters ....................................................................
Amazon ECS TaskDefinition LogConfiguration ..................................................................
Amazon ECS TaskDefinition MountPoint ..........................................................................
Amazon ECS TaskDefinition ContainerDefinitions PortMapping ...........................................
Amazon ECS TaskDefinition Ulimit ..................................................................................
Amazon ECS TaskDefinition VolumeFrom .........................................................................
Amazon ECS Service PlacementConstraint ........................................................................
Amazon ECS TaskDefinition Volumes ...............................................................................
Amazon ECS TaskDefinition Volumes Host .......................................................................
Amazon Elastic File System FileSystem FileSystemTags ......................................................
EKS Cluster ResourcesVpcConfig .....................................................................................
Elastic Beanstalk Application ApplicationResourceLifecycleConfig ........................................
Elastic Beanstalk Application ApplicationVersionLifecycleConfig ..........................................
Elastic Beanstalk Application MaxAgeRule ........................................................................
Elastic Beanstalk Application MaxCountRule .....................................................................
Elastic Beanstalk ConfigurationTemplate ConfigurationOptionSetting ..................................
API Version 2010-05-15
xvi

1831
1834
1835
1836
1837
1838
1840
1842
1843
1844
1844
1845
1850
1853
1856
1857
1859
1860
1860
1861
1862
1863
1865
1866
1866
1867
1868
1869
1870
1871
1872
1872
1873
1874
1875
1876
1878
1883
1884
1885
1886
1887
1888
1889
1890
1891
1891
1892
1893
1894
1895
1895
1896
1897
1898
1899
1900

AWS CloudFormation User Guide

Elastic Beanstalk ConfigurationTemplate SourceConfiguration ............................................
Elastic Beanstalk Environment Tier ..................................................................................
Elastic Beanstalk Environment OptionSetting ...................................................................
Elastic Beanstalk SourceBundle Property Type ..................................................................
ElastiCache ReplicationGroup NodeGroupConfiguration .....................................................
Elastic Load Balancing AccessLoggingPolicy .....................................................................
AppCookieStickinessPolicy .............................................................................................
Elastic Load Balancing ConnectionDrainingPolicy ..............................................................
Elastic Load Balancing ConnectionSettings .......................................................................
ElasticLoadBalancing LoadBalancer HealthCheck ...............................................................
LBCookieStickinessPolicy ................................................................................................
ElasticLoadBalancing Listener .........................................................................................
ElasticLoadBalancing Policy ............................................................................................
Elastic Load Balancing Listener Certificate .......................................................................
Elastic Load Balancing ListenerCertificate Certificate .........................................................
Elastic Load Balancing Listener Action .............................................................................
Elastic Load Balancing ListenerRule Actions ......................................................................
Elastic Load Balancing ListenerRule Conditions .................................................................
Elastic Load Balancing LoadBalancer LoadBalancerAttributes ..............................................
Elastic Load Balancing LoadBalancer SubnetMapping ........................................................
Elastic Load Balancing TargetGroup Matcher ....................................................................
Elastic Load Balancing TargetGroup TargetDescription .......................................................
Elastic Load Balancing TargetGroup TargetGroupAttributes ................................................
Amazon ES Domain EBSOptions .....................................................................................
Amazon ES Domain ElasticsearchClusterConfig .................................................................
Amazon ES Domain EncryptionAtRestOptions ..................................................................
Amazon ES Domain SnapshotOptions .............................................................................
Amazon ES Domain VPCOptions .....................................................................................
Amazon EMR Cluster Application ....................................................................................
Amazon EMR Cluster AutoScalingPolicy ...........................................................................
Amazon EMR Cluster BootstrapActionConfig ....................................................................
Amazon EMR Cluster CloudWatchAlarmDefinition .............................................................
Amazon EMR Cluster Configurations ...............................................................................
Amazon EMR Cluster InstanceFleetConfig ........................................................................
Amazon EMR Cluster InstanceFleetProvisioningSpecifications .............................................
Amazon EMR Cluster InstanceGroupConfig .......................................................................
Amazon EMR Cluster InstanceTypeConfig .........................................................................
Amazon EMR Cluster JobFlowInstancesConfig ..................................................................
Amazon EMR Cluster MetricDimension ............................................................................
Amazon EMR Cluster PlacementType ...............................................................................
Amazon EMR Cluster ScalingAction .................................................................................
Amazon EMR Cluster ScalingConstraints ..........................................................................
Amazon EMR Cluster ScalingRule ....................................................................................
Amazon EMR Cluster ScalingTrigger ................................................................................
Amazon EMR Cluster ScriptBootstrapActionConfig ............................................................
Amazon EMR Cluster SimpleScalingPolicyConfiguration .....................................................
Amazon EMR Cluster SpotProvisioningSpecification ...........................................................
Amazon EMR Cluster KerberosAttributes ..........................................................................
Amazon EMR EbsConfiguration .......................................................................................
Amazon EMR EbsConfiguration EbsBlockDeviceConfigs ......................................................
Amazon EMR EbsConfiguration EbsBlockDeviceConfig VolumeSpecification ..........................
Amazon EMR InstanceFleetConfig Configuration ...............................................................
Amazon EMR InstanceFleetConfig EbsBlockDeviceConfig ....................................................
Amazon EMR InstanceFleetConfig EbsConfiguration ..........................................................
Amazon EMR InstanceFleetConfig InstanceFleetProvisioningSpecifications ............................
Amazon EMR InstanceFleetConfig InstanceTypeConfig .......................................................
Amazon EMR InstanceFleetConfig SpotProvisioningSpecification .........................................
API Version 2010-05-15
xvii

1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1914
1916
1917
1917
1918
1919
1919
1920
1921
1922
1922
1923
1924
1926
1927
1927
1928
1929
1930
1931
1933
1934
1935
1936
1938
1939
1943
1944
1944
1945
1946
1947
1947
1948
1949
1950
1952
1953
1954
1955
1956
1957
1957
1958
1960

AWS CloudFormation User Guide

Amazon EMR InstanceFleetConfig VolumeSpecification ......................................................
Amazon EMR InstanceGroupConfig AutoScalingPolicy ........................................................
Amazon EMR InstanceGroupConfig CloudWatchAlarmDefinition ..........................................
Amazon EMR InstanceGroupConfig MetricDimension .........................................................
Amazon EMR InstanceGroupConfig ScalingAction ..............................................................
Amazon EMR InstanceGroupConfig ScalingConstraints .......................................................
Amazon EMR InstanceGroupConfig ScalingRule ................................................................
Amazon EMR InstanceGroupConfig ScalingTrigger .............................................................
Amazon EMR InstanceGroupConfig SimpleScalingPolicyConfiguration ..................................
Amazon EMR Step HadoopJarStepConfig .........................................................................
Amazon EMR Step KeyValue ..........................................................................................
GameLift Alias RoutingStrategy ......................................................................................
GameLift Build StorageLocation .....................................................................................
GameLift Fleet EC2InboundPermission ............................................................................
AWS Glue Classifier GrokClassifier ...................................................................................
AWS Glue Connection ConnectionInput ...........................................................................
AWS Glue Connection PhysicalConnectionRequirements .....................................................
AWS Glue Crawler JdbcTarget ........................................................................................
AWS Glue Crawler S3Target ...........................................................................................
AWS Glue Crawler Schedule ...........................................................................................
AWS Glue Crawler SchemaChangePolicy ..........................................................................
AWS Glue Crawler Targets .............................................................................................
AWS Glue Database DatabaseInput .................................................................................
AWS Glue Job ConnectionsList .......................................................................................
AWS Glue Job ExecutionProperty ....................................................................................
AWS Glue Job JobCommand ..........................................................................................
AWS Glue Partition Column ...........................................................................................
AWS Glue Partition Order ..............................................................................................
AWS Glue Partition PartitionInput ...................................................................................
AWS Glue Partition SerdeInfo .........................................................................................
AWS Glue Partition SkewedInfo ......................................................................................
AWS Glue Partition StorageDescriptor .............................................................................
AWS Glue Table Column ................................................................................................
AWS Glue Table Order ...................................................................................................
AWS Glue Table SerdeInfo .............................................................................................
AWS Glue Table SkewedInfo ..........................................................................................
AWS Glue Table StorageDescriptor ..................................................................................
AWS Glue Table TableInput ............................................................................................
AWS Glue Trigger Action ...............................................................................................
AWS Glue Trigger Condition ...........................................................................................
AWS Glue Trigger Predicate ...........................................................................................
GuardDuty Filter FindingCriteria .....................................................................................
GuardDuty Filter Condition ............................................................................................
IAM Policies .................................................................................................................
IAM User LoginProfile ....................................................................................................
AWS IoT TopicRule Action ..............................................................................................
AWS IoT TopicRule CloudwatchAlarmAction .....................................................................
AWS IoT TopicRule CloudwatchMetricAction .....................................................................
AWS IoT TopicRule DynamoDBAction ..............................................................................
AWS IoT TopicRule DynamoDBv2Action ...........................................................................
AWS IoT TopicRule ElasticsearchAction ............................................................................
AWS IoT TopicRule FirehoseAction ..................................................................................
AWS IoT TopicRule KinesisAction ....................................................................................
AWS IoT TopicRule LambdaAction ...................................................................................
AWS IoT TopicRule PutItemInput ....................................................................................
AWS IoT TopicRule RepublishAction ................................................................................
AWS IoT TopicRule S3Action ..........................................................................................
API Version 2010-05-15
xviii

1961
1962
1965
1967
1968
1969
1970
1971
1971
1972
1973
1974
1975
1976
1977
1978
1980
1981
1982
1982
1983
1984
1985
1986
1987
1987
1988
1989
1990
1991
1992
1993
1996
1997
1998
1999
2000
2003
2006
2007
2008
2009
2009
2011
2012
2012
2015
2016
2017
2019
2020
2021
2022
2022
2023
2024
2024

AWS CloudFormation User Guide

AWS IoT TopicRule SnsAction .........................................................................................
AWS IoT TopicRule SqsAction .........................................................................................
AWS IoT Thing AttributePayload .....................................................................................
AWS IoT TopicRule TopicRulePayload ..............................................................................
Kinesis StreamEncryption ...............................................................................................
Kinesis Data Analytics Application CSVMappingParameters .................................................
Kinesis Data Analytics Application Input ..........................................................................
Kinesis Data Analytics Application InputLambdaProcessor ..................................................
Kinesis Data Analytics Application InputParallelism ...........................................................
Kinesis Data Analytics Application InputProcessingConfiguration .........................................
Kinesis Data Analytics Application InputSchema ................................................................
Kinesis Data Analytics Application JSONMappingParameters ..............................................
Kinesis Data Analytics Application KinesisFirehoseInput .....................................................
Kinesis Data Analytics Application KinesisStreamsInput ......................................................
Kinesis Data Analytics Application MappingParameters ......................................................
Kinesis Data Analytics Application RecordColumn ..............................................................
Kinesis Data Analytics Application RecordFormat ..............................................................
Kinesis Data Analytics ApplicationOutput DestinationSchema .............................................
Kinesis Data Analytics ApplicationOutput KinesisFirehoseOutput .........................................
Kinesis Data Analytics ApplicationOutput KinesisStreamsOutput .........................................
Kinesis Data Analytics ApplicationOutput LambdaOutput ...................................................
Kinesis Data Analytics ApplicationOutput Output ..............................................................
Kinesis Data Analytics ApplicationReferenceDataSource CSVMappingParameters ...................
Kinesis Data Analytics ApplicationReferenceDataSource JSONMappingParameters .................
Kinesis Data Analytics ApplicationReferenceDataSource MappingParameters .........................
Kinesis Data Analytics ApplicationReferenceDataSource RecordColumn ................................
Kinesis Data Analytics ApplicationReferenceDataSource RecordFormat .................................
Kinesis Data Analytics ApplicationReferenceDataSource ReferenceDataSource .......................
Kinesis Data Analytics ApplicationReferenceDataSource ReferenceSchema ............................
Kinesis Data Analytics ApplicationReferenceDataSource S3ReferenceDataSource ...................
Kinesis Data Firehose DeliveryStream BufferingHints .........................................................
Kinesis Data Firehose DeliveryStream CloudWatchLoggingOptions ......................................
Kinesis Data Firehose DeliveryStream CopyCommand ........................................................
Kinesis Data Firehose DeliveryStream ElasticsearchBufferingHints ........................................
Kinesis Data Firehose DeliveryStream ElasticsearchDestinationConfiguration .........................
Kinesis Data Firehose DeliveryStream ElasticsearchRetryOptions .........................................
Kinesis Data Firehose DeliveryStream EncryptionConfiguration ...........................................
Kinesis Data Firehose DeliveryStream ExtendedS3DestinationConfiguration ..........................
Kinesis Data Firehose DeliveryStream KinesisStreamSourceConfiguration ..............................
Kinesis Data Firehose DeliveryStream KMSEncryptionConfig ...............................................
Kinesis Data Firehose DeliveryStream ProcessingConfiguration ............................................
Kinesis Data Firehose DeliveryStream Processor ................................................................
Kinesis Data Firehose DeliveryStream ProcessorParameter ..................................................
Kinesis Data Firehose DeliveryStream RedshiftDestinationConfiguration ...............................
Kinesis Data Firehose DeliveryStream S3DestinationConfiguration .......................................
Kinesis Data Firehose DeliveryStream SplunkDestinationConfiguration .................................
Kinesis Data Firehose DeliveryStream SplunkRetryOptions .................................................
AWS Lambda Alias AliasRoutingConfiguration ..................................................................
AWS Lambda Alias VersionWeight ...................................................................................
AWS Lambda Function DeadLetterConfig .........................................................................
AWS Lambda Function Environment ................................................................................
AWS Lambda Function Code ..........................................................................................
AWS Lambda Function TracingConfig ..............................................................................
AWS Lambda Function VpcConfig ...................................................................................
Name Type ..................................................................................................................
AWS OpsWorks App DataSource .....................................................................................
AWS OpsWorks App Environment ...................................................................................
API Version 2010-05-15
xix

2025
2026
2027
2028
2029
2030
2031
2033
2033
2034
2035
2036
2037
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2060
2061
2061
2064
2065
2065
2066
2067
2068
2070
2072
2074
2075
2076
2077
2077
2078
2084
2085
2085
2087
2088

AWS CloudFormation User Guide

AWS OpsWorks AutoScalingThresholds Type ....................................................................
AWS OpsWorks ChefConfiguration Type ..........................................................................
AWS OpsWorks Layer LifeCycleConfiguration ....................................................................
AWS OpsWorks Layer LifeCycleConfiguration ShutdownEventConfiguration ..........................
AWS OpsWorks LoadBasedAutoScaling Type ....................................................................
AWS OpsWorks Instance BlockDeviceMapping ..................................................................
AWS OpsWorks Instance BlockDeviceMapping EbsBlockDevice ............................................
AWS OpsWorks Recipes Type .........................................................................................
AWS OpsWorks Source Type ..........................................................................................
AWS OpsWorks SslConfiguration Type .............................................................................
AWS OpsWorks Stack ElasticIp .......................................................................................
AWS OpsWorks Stack RdsDbInstance ...............................................................................
AWS OpsWorks StackConfigurationManager Type .............................................................
AWS OpsWorks TimeBasedAutoScaling Type ....................................................................
AWS OpsWorks VolumeConfiguration Type ......................................................................
Amazon Redshift Parameter Type ...................................................................................
Amazon Redshift Cluster LoggingProperties .....................................................................
AWS CloudFormation Resource Tags ................................................................................
Amazon RDS OptionGroup OptionConfiguration ...............................................................
Amazon RDS OptionGroup OptionSetting ........................................................................
RDS Security Group Rule ...............................................................................................
Route 53 AliasTarget Property ........................................................................................
Route 53 Record Set GeoLocation Property ......................................................................
Route 53 HealthCheck HealthCheckConfig .......................................................................
Route 53 HealthCheck AlarmIdentifier .............................................................................
Route 53 HealthCheck HealthCheckTags ..........................................................................
Route 53 HostedZoneConfig Property .............................................................................
Amazon Route 53 HostedZoneTags .................................................................................
Route 53 QueryLoggingConfig ........................................................................................
Route 53 HostedZoneVPCs .............................................................................................
Amazon S3 Bucket AbortIncompleteMultipartUpload ........................................................
Amazon S3 Bucket AccelerateConfiguration .....................................................................
Amazon S3 Bucket AccessControlTranslation ....................................................................
Amazon S3 Bucket AnalyticsConfiguration .......................................................................
Amazon S3 Bucket BucketEncryption ..............................................................................
Amazon S3 Bucket CorsConfiguration ..............................................................................
Amazon S3 Bucket CorsRule ...........................................................................................
Amazon S3 Bucket DataExport .......................................................................................
Amazon S3 Bucket Destination .......................................................................................
Amazon S3 EncryptionConfiguration ...............................................................................
Amazon S3 Bucket FilterRule .........................................................................................
Amazon S3 Bucket InventoryConfiguration ......................................................................
Amazon S3 Bucket LambdaConfiguration .........................................................................
Amazon S3 Bucket LifecycleConfiguration ........................................................................
Amazon S3 Bucket LoggingConfiguration ........................................................................
Amazon S3 Bucket MetricsConfiguration ..........................................................................
Amazon S3 Bucket NoncurrentVersionTransition ...............................................................
Amazon S3 Bucket NotificationConfiguration ...................................................................
Amazon S3 Bucket NotificationFilter ...............................................................................
Amazon S3 Bucket QueueConfiguration ...........................................................................
Amazon S3 Bucket ReplicationConfiguration ....................................................................
Amazon S3 Bucket ReplicationDestination .......................................................................
Amazon S3 Bucket ReplicationRule .................................................................................
Amazon S3 Bucket Rule .................................................................................................
Amazon S3 Bucket S3KeyFilter .......................................................................................
Amazon S3 Bucket ServerSideEncryptionRule ...................................................................
Amazon S3 Bucket ServerSideEncryptionByDefault ...........................................................
API Version 2010-05-15
xx

2089
2090
2091
2092
2092
2093
2094
2096
2097
2099
2099
2100
2101
2102
2103
2104
2105
2106
2108
2110
2111
2112
2113
2114
2118
2118
2119
2120
2120
2121
2122
2122
2124
2124
2125
2126
2127
2128
2129
2130
2131
2131
2133
2135
2135
2136
2137
2138
2139
2140
2141
2141
2143
2144
2147
2148
2148

AWS CloudFormation User Guide

Amazon S3 Bucket SseKmsEncryptedObjects ....................................................................
Amazon S3 Bucket SourceSelectionCriteria .......................................................................
Amazon S3 Bucket StorageClassAnalysis ..........................................................................
Amazon S3 Bucket TagFilter ...........................................................................................
Amazon S3 Bucket TopicConfiguration ............................................................................
Amazon S3 Bucket Transition .........................................................................................
Amazon S3 Bucket VersioningConfiguration .....................................................................
Amazon S3 Website Configuration Property .....................................................................
Amazon S3 Website Configuration Redirect All Requests To Property ...................................
Amazon S3 Website Configuration Routing Rules Property .................................................
Amazon S3 Website Configuration Routing Rules Redirect Rule Property ..............................
Amazon S3 Website Configuration Routing Rules Routing Rule Condition Property ................
Amazon SageMaker Endpoint Tag ...................................................................................
Amazon SageMaker EndpointConfig ProductionVariant ......................................................
Amazon SageMaker EndpointConfig Tag ..........................................................................
Amazon SageMaker NotebookInstance Tag ......................................................................
Amazon SageMaker NotebookInstanceLifecycleConfig NotebookInstanceLifecycleHook ..........
Amazon SageMaker Model ContainerDefinition .................................................................
Amazon SageMaker Model Tag .......................................................................................
Amazon SageMaker Model VpcConfig ..............................................................................
AWS Service Catalog CloudFormationProduct ProvisioningArtifactProperties ........................
AWS Service Catalog CloudFormationProvisionedProduct ProvisioningParameter ...................
Amazon Route 53 ServiceDiscovery DnsConfig ..................................................................
Amazon Route 53 ServiceDiscovery DnsRecord .................................................................
Amazon Route 53 ServiceDiscovery HealthCheckConfig ......................................................
Route 53 ServiceDiscovery Service HealthCheckCustomConfig ............................................
Amazon SES ConfigurationSetEventDestination CloudWatchDestination ...............................
Amazon SES ConfigurationSetEventDestination DimensionConfiguration ..............................
Amazon SES ConfigurationSetEventDestination EventDestination ........................................
Amazon SES ConfigurationSetEventDestination KinesisFirehoseDestination ..........................
Amazon SES ReceiptFilter Filter ......................................................................................
Amazon SES ReceiptFilter IpFilter ...................................................................................
Amazon SES ReceiptRule Action .....................................................................................
Amazon SES ReceiptRule AddHeaderAction ......................................................................
Amazon SES ReceiptRule BounceAction ...........................................................................
Amazon SES ReceiptRule LambdaAction ..........................................................................
Amazon SES ReceiptRule Rule ........................................................................................
Amazon SES ReceiptRule S3Action ..................................................................................
Amazon SES ReceiptRule SNSAction ................................................................................
Amazon SES ReceiptRule StopAction ...............................................................................
Amazon SES ReceiptRule WorkmailAction ........................................................................
Amazon SES Template Template ....................................................................................
Systems Manager Association InstanceAssociationOutputLocation .......................................
Systems Manager Association S3OutputLocation ..............................................................
Systems Manager Association Targets ..............................................................................
Systems Manager MaintenanceWindowTarget Targets .......................................................
Systems Manager MaintenanceWindowTask LoggingInfo ....................................................
Systems Manager MaintenanceWindowTask MaintenanceWindowAutomationParameters .......
Systems Manager MaintenanceWindowTask MaintenanceWindowLambdaParameters .............
Systems Manager MaintenanceWindowTask MaintenanceWindowRunCommandParameters ....
Systems Manager MaintenanceWindowTask MaintenanceWindowStepFunctionsParameters ....
Systems Manager MaintenanceWindowTask NotificationConfig ...........................................
Systems Manager MaintenanceWindowTask Target ............................................................
Systems Manager MaintenanceWindowTask TaskInvocationParameters ................................
Systems Manager PatchBaseline PatchFilterGroup .............................................................
Systems Manager PatchBaseline Rule ..............................................................................
Systems Manager PatchBaseline PatchFilter .....................................................................
API Version 2010-05-15
xxi

2149
2150
2150
2151
2152
2153
2154
2154
2156
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2177
2178
2179
2180
2182
2183
2185
2186
2188
2190
2192
2193
2194
2195
2196
2196
2197
2198
2199
2200
2201
2203
2204
2205
2206
2208
2208
2210

AWS CloudFormation User Guide

Systems Manager PatchBaseline RuleGroup ......................................................................
Amazon SNS Subscription ..............................................................................................
Amazon SQS RedrivePolicy ............................................................................................
AWS WAF ByteMatchSet ByteMatchTuples .......................................................................
AWS WAF ByteMatchSet ByteMatchTuples FieldToMatch ....................................................
AWS WAF IPSet IPSetDescriptors ....................................................................................
AWS WAF Rule Predicates ..............................................................................................
AWS WAF SizeConstraintSet SizeConstraint ......................................................................
AWS WAF SizeConstraintSet SizeConstraint FieldToMatch ..................................................
AWS WAF SqlInjectionMatchSet SqlInjectionMatchTuples ...................................................
AWS WAF SqlInjectionMatchSet SqlInjectionMatchTuples FieldToMatch ................................
AWS WAF XssMatchSet XssMatchTuple ............................................................................
AWS WAF XssMatchSet XssMatchTuple FieldToMatch .........................................................
AWS WAF WebACL Action ..............................................................................................
AWS WAF WebACL ActivatedRule ....................................................................................
AWS WAF Regional ByteMatchSet ByteMatchTuples ..........................................................
AWS WAF Regional ByteMatchSet ByteMatchTuples FieldToMatch .......................................
AWS WAF Regional IPSet IPSetDescriptors .......................................................................
AWS WAF Regional Rule Predicates .................................................................................
AWS WAF Regional SizeConstraintSet SizeConstraint .........................................................
AWS WAF Regional SizeConstraintSet SizeConstraint FieldToMatch ......................................
AWS WAF Regional SqlInjectionMatchSet SqlInjectionMatchTuples ......................................
AWS WAF Regional SqlInjectionMatchSet SqlInjectionMatchTuples FieldToMatch ...................
AWS WAF Regional XssMatchSet XssMatchTuple ...............................................................
AWS WAF Regional XssMatchSet XssMatchTuple FieldToMatch ............................................
AWS WAF Regional WebACL Action .................................................................................
AWS WAF Regional WebACL Rules ..................................................................................
Resource Specification ...........................................................................................................
Specification Format .....................................................................................................
Resource Attributes ...............................................................................................................
CreationPolicy ..............................................................................................................
DeletionPolicy ..............................................................................................................
DependsOn ..................................................................................................................
Metadata .....................................................................................................................
UpdatePolicy ................................................................................................................
Intrinsic Functions .................................................................................................................
Fn::Base64 ................................................................................................................
Fn::Cidr ....................................................................................................................
Condition Functions ......................................................................................................
Fn::FindInMap ..........................................................................................................
Fn::GetAtt ................................................................................................................
Fn::GetAZs ................................................................................................................
Fn::ImportValue .......................................................................................................
Fn::Join ....................................................................................................................
Fn::Select ................................................................................................................
Fn::Split ..................................................................................................................
Fn::Sub .....................................................................................................................
Ref .............................................................................................................................
Pseudo Parameters ...............................................................................................................
Example ......................................................................................................................
AWS::AccountId .............................................................................................................
AWS::NotificationARNs ...................................................................................................
AWS::NoValue ...............................................................................................................
AWS::Partition ..............................................................................................................
AWS::Region .................................................................................................................
AWS::StackId ................................................................................................................
AWS::StackName ...........................................................................................................
API Version 2010-05-15
xxii

2211
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2231
2232
2233
2234
2234
2236
2244
2245
2248
2250
2254
2255
2264
2265
2266
2268
2283
2285
2298
2300
2302
2304
2306
2308
2311
2322
2322
2322
2322
2323
2324
2324
2324
2324

AWS CloudFormation User Guide

AWS::URLSuffix ............................................................................................................. 2324
CloudFormation Helper Scripts ............................................................................................... 2324
Amazon Linux AMI Images ............................................................................................. 2325
Downloading Packages for Other Platforms ..................................................................... 2325
Permissions for helper scripts ......................................................................................... 2326
Using the Latest Version ................................................................................................ 2327
cfn-init ........................................................................................................................ 2328
cfn-signal ..................................................................................................................... 2331
cfn-get-metadata .......................................................................................................... 2335
cfn-hup ....................................................................................................................... 2337
Sample Templates ........................................................................................................................ 2342
Troubleshooting ............................................................................................................................ 2343
Troubleshooting Guide .......................................................................................................... 2343
Troubleshooting Errors .......................................................................................................... 2343
Delete Stack Fails ......................................................................................................... 2344
Dependency Error ......................................................................................................... 2344
Error Parsing Parameter When Passing a List .................................................................... 2345
Insufficient IAM Permissions ........................................................................................... 2345
Invalid Value or Unsupported Resource Property .............................................................. 2345
Limit Exceeded ............................................................................................................. 2345
Nested Stacks are Stuck in UPDATE_COMPLETE_CLEANUP_IN_PROGRESS,
UPDATE_ROLLBACK_COMPLETE_CLEANUP_IN_PROGRESS, or
UPDATE_ROLLBACK_IN_PROGRESS ................................................................................. 2345
No Updates to Perform ................................................................................................. 2346
Resource Failed to Stabilize During a Create, Update, or Delete Stack Operation .................... 2346
Security Group Does Not Exist in VPC .............................................................................. 2346
Update Rollback Failed ................................................................................................. 2347
Wait Condition Didn't Receive the Required Number of Signals from an Amazon EC2 Instance .. 2348
Contacting Support ............................................................................................................... 2348
Release History ............................................................................................................................. 2349
Earlier Updates ..................................................................................................................... 2366
Supported AWS Services ........................................................................................................ 2436
Analytics ...................................................................................................................... 2437
Application Services ...................................................................................................... 2438
Compute ...................................................................................................................... 2438
Customer Engagement .................................................................................................. 2440
Database ..................................................................................................................... 2440
Developer Tools ............................................................................................................ 2442
Enterprise Applications .................................................................................................. 2442
Game Development ...................................................................................................... 2442
Internet of Things ......................................................................................................... 2443
Machine Learning ......................................................................................................... 2443
Management Tools ....................................................................................................... 2443
Mobile Services ............................................................................................................ 2445
Networking .................................................................................................................. 2445
Security and Identity ..................................................................................................... 2447
Storage and Content Delivery ........................................................................................ 2448
Additional Software and Services .................................................................................... 2449
Release History for Helper Scripts ........................................................................................... 2449
AWS Glossary ............................................................................................................................... 2451

API Version 2010-05-15
xxiii

AWS CloudFormation User Guide
Simplify Infrastructure Management

What is AWS CloudFormation?
AWS CloudFormation is a service that helps you model and set up your Amazon Web Services resources
so that you can spend less time managing those resources and more time focusing on your applications
that run in AWS. You create a template that describes all the AWS resources that you want (like Amazon
EC2 instances or Amazon RDS DB instances), and AWS CloudFormation takes care of provisioning and
configuring those resources for you. You don't need to individually create and configure AWS resources
and figure out what's dependent on what; AWS CloudFormation handles all of that. The following
scenarios demonstrate how AWS CloudFormation can help.

Simplify Infrastructure Management
For a scalable web application that also includes a back-end database, you might use an Auto Scaling
group, an Elastic Load Balancing load balancer, and an Amazon Relational Database Service database
instance. Normally, you might use each individual service to provision these resources. And after you
create the resources, you would have to configure them to work together. All these tasks can add
complexity and time before you even get your application up and running.
Instead, you can create or modify an existing AWS CloudFormation template. A template describes all
of your resources and their properties. When you use that template to create an AWS CloudFormation
stack, AWS CloudFormation provisions the Auto Scaling group, load balancer, and database for you.
After the stack has been successfully created, your AWS resources are up and running. You can delete the
stack just as easily, which deletes all the resources in the stack. By using AWS CloudFormation, you easily
manage a collection of resources as a single unit.

Quickly Replicate Your Infrastructure
If your application requires additional availability, you might replicate it in multiple regions so that if
one region becomes unavailable, your users can still use your application in other regions. The challenge
in replicating your application is that it also requires you to replicate your resources. Not only do you
need to record all the resources that your application requires, but you must also provision and configure
those resources in each region.
When you use AWS CloudFormation, you can reuse your template to set up your resources consistently
and repeatedly. Just describe your resources once and then provision the same resources over and over in
multiple regions.

Easily Control and Track Changes to Your
Infrastructure
In some cases, you might have underlying resources that you want to upgrade incrementally. For
example, you might change to a higher performing instance type in your Auto Scaling launch
configuration so that you can reduce the maximum number of instances in your Auto Scaling group. If
problems occur after you complete the update, you might need to roll back your infrastructure to the
original settings. To do this manually, you not only have to remember which resources were changed, you
also have to know what the original settings were.
API Version 2010-05-15
1

AWS CloudFormation User Guide
Related Information

When you provision your infrastructure with AWS CloudFormation, the AWS CloudFormation template
describes exactly what resources are provisioned and their settings. Because these templates are text
files, you simply track differences in your templates to track changes to your infrastructure, similar to
the way developers control revisions to source code. For example, you can use a version control system
with your templates so that you know exactly what changes were made, who made them, and when. If
at any point you need to reverse changes to your infrastructure, you can use a previous version of your
template.

Related Information
• For more information about AWS CloudFormation stacks and templates, see AWS CloudFormation
Concepts (p. 2).
• For an overview about how to use AWS CloudFormation, see How Does AWS CloudFormation
Work? (p. 5).
• For pricing information, see AWS CloudFormation Pricing.

AWS CloudFormation Concepts
When you use AWS CloudFormation, you work with templates and stacks. You create templates to
describe your AWS resources and their properties. Whenever you create a stack, AWS CloudFormation
provisions the resources that are described in your template.
Topics
• Templates (p. 2)
• Stacks (p. 4)
• Change Sets (p. 5)

Templates
An AWS CloudFormation template is a JSON or YAML formatted text file. You can save these files with
any extension, such as .json, .yaml, .template, or .txt. AWS CloudFormation uses these templates
as blueprints for building your AWS resources. For example, in a template, you can describe an Amazon
EC2 instance, such as the instance type, the AMI ID, block device mappings, and its Amazon EC2 key pair
name. Whenever you create a stack, you also specify a template that AWS CloudFormation uses to create
whatever you described in the template.
For example, if you created a stack with the following template, AWS CloudFormation provisions an
instance with an ami-2f726546 AMI ID, t1.micro instance type, testkey key pair name, and an
Amazon EBS volume.

Example JSON
{

"AWSTemplateFormatVersion" : "2010-09-09",
"Description" : "A sample template",
"Resources" : {
"MyEC2Instance" : {
"Type" : "AWS::EC2::Instance",
"Properties" : {
"ImageId" : "ami-2f726546",
"InstanceType" : "t1.micro",
"KeyName" : "testkey",

API Version 2010-05-15
2

AWS CloudFormation User Guide
Templates

}

}

}

}

"BlockDeviceMappings" : [
{
"DeviceName" : "/dev/sdm",
"Ebs" : {
"VolumeType" : "io1",
"Iops" : "200",
"DeleteOnTermination" : "false",
"VolumeSize" : "20"
}
}
]

Example YAML
AWSTemplateFormatVersion: "2010-09-09"
Description: A sample template
Resources:
MyEC2Instance:
Type: "AWS::EC2::Instance"
Properties:
ImageId: "ami-2f726546"
InstanceType: t1.micro
KeyName: testkey
BlockDeviceMappings:
DeviceName: /dev/sdm
Ebs:
VolumeType: io1
Iops: 200
DeleteOnTermination: false
VolumeSize: 20

You can also specify multiple resources in a single template and configure these resources to work
together. For example, you can modify the previous template to include an Elastic IP (EIP) and associate
it with the Amazon EC2 instance, as shown in the following example:

Example JSON
{

"AWSTemplateFormatVersion" : "2010-09-09",
"Description" : "A sample template",
"Resources" : {
"MyEC2Instance" : {
"Type" : "AWS::EC2::Instance",
"Properties" : {
"ImageId" : "ami-2f726546",
"InstanceType" : "t1.micro",
"KeyName" : "testkey",
"BlockDeviceMappings" : [
{
"DeviceName" : "/dev/sdm",
"Ebs" : {
"VolumeType" : "io1",
"Iops" : "200",
"DeleteOnTermination" : "false",
"VolumeSize" : "20"
}
}

API Version 2010-05-15
3

AWS CloudFormation User Guide
Stacks

}

}

}

]

},
"MyEIP" : {
"Type" : "AWS::EC2::EIP",
"Properties" : {
"InstanceId" : {"Ref": "MyEC2Instance"}
}
}

Example YAML
AWSTemplateFormatVersion: "2010-09-09"
Description: A sample template
Resources:
MyEC2Instance:
Type: "AWS::EC2::Instance"
Properties:
ImageId: "ami-2f726546"
InstanceType: t1.micro
KeyName: testkey
BlockDeviceMappings:
DeviceName: /dev/sdm
Ebs:
VolumeType: io1
Iops: 200
DeleteOnTermination: false
VolumeSize: 20
MyEIP:
Type: AWS::EC2::EIP
Properties:
InstanceId: !Ref MyEC2Instance

The previous templates are centered around a single Amazon EC2 instance; however, AWS
CloudFormation templates have additional capabilities that you can use to build complex sets of
resources and reuse those templates in multiple contexts. For example, you can add input parameters
whose values are specified when you create an AWS CloudFormation stack. In other words, you can
specify a value like the instance type when you create a stack instead of when you create the template,
making the template easier to reuse in different situations.
For more information about template creation and capabilities, see Template Anatomy (p. 163).
For more information about declaring specific resources, see AWS Resource Types Reference (p. 499).
To start designing your own templates with AWS CloudFormation Designer, go to https://
console.aws.amazon.com/cloudformation/designer.

Stacks
When you use AWS CloudFormation, you manage related resources as a single unit called a stack. You
create, update, and delete a collection of resources by creating, updating, and deleting stacks. All the
resources in a stack are defined by the stack's AWS CloudFormation template. Suppose you created a
template that includes an Auto Scaling group, Elastic Load Balancing load balancer, and an Amazon
Relational Database Service (Amazon RDS) database instance. To create those resources, you create
a stack by submitting the template that you created, and AWS CloudFormation provisions all those
resources for you. You can work with stacks by using the AWS CloudFormation console, API, or AWS CLI.
API Version 2010-05-15
4

AWS CloudFormation User Guide
Change Sets

For more information about creating, updating, or deleting stacks, see Working with Stacks (p. 90).

Change Sets
If you need to make changes to the running resources in a stack, you update the stack. Before making
changes to your resources, you can generate a change set, which is summary of your proposed changes.
Change sets allow you to see how your changes might impact your running resources, especially for
critical resources, before implementing them.
For example, if you change the name of an Amazon RDS database instance, AWS CloudFormation
will create a new database and delete the old one. You will lose the data in the old database unless
you've already backed it up. If you generate a change set, you will see that your change will cause your
database to be replaced, and you will be able to plan accordingly before you update your stack. For more
information, see Updating Stacks Using Change Sets (p. 122).

How Does AWS CloudFormation Work?
When you create a stack, AWS CloudFormation makes underlying service calls to AWS to provision
and configure your resources. Note that AWS CloudFormation can perform only actions that you
have permission to do. For example, to create EC2 instances by using AWS CloudFormation, you need
permissions to create instances. You'll need similar permissions to terminate instances when you delete
stacks with instances. You use AWS Identity and Access Management (IAM) to manage permissions.
The calls that AWS CloudFormation makes are all declared by your template. For example, suppose
you have a template that describes an EC2 instance with a t1.micro instance type. When you use that
template to create a stack, AWS CloudFormation calls the Amazon EC2 create instance API and specifies
the instance type as t1.micro. The following diagram summarizes the AWS CloudFormation workflow
for creating stacks.

API Version 2010-05-15
5

AWS CloudFormation User Guide
How Does AWS CloudFormation Work?

1. You can design an AWS CloudFormation template (a JSON or YAML-formatted document) in AWS
CloudFormation Designer or write one in a text editor. You can also choose to use a provided
template. The template describes the resources you want and their settings. For example, suppose you
want to create an EC2 instance. Your template can declare an EC2 instance and describe its properties,
as shown in the following example:

Example JSON Syntax
{

}

"AWSTemplateFormatVersion" : "2010-09-09",
"Description" : "A simple EC2 instance",
"Resources" : {
"MyEC2Instance" : {
"Type" : "AWS::EC2::Instance",
"Properties" : {
"ImageId" : "ami-2f726546",
"InstanceType" : "t1.micro"
}
}
}

Example YAML Syntax
AWSTemplateFormatVersion: '2010-09-09'
Description: A simple EC2 instance
Resources:
MyEC2Instance:
Type: AWS::EC2::Instance
Properties:
ImageId: ami-2f726546
InstanceType: t1.micro

2. Save the template locally or in an S3 bucket. If you created a template, save it with any file extension
like .json, .yaml, or .txt.
3. Create an AWS CloudFormation stack by specifying the location of your template file , such as a path
on your local computer or an Amazon S3 URL. If the template contains parameters, you can specify
input values when you create the stack. Parameters enable you to pass in values to your template so
that you can customize your resources each time you create a stack.
You can create stacks by using the AWS CloudFormation console (p. 92), API, or AWS CLI.

Note

If you specify a template file stored locally, AWS CloudFormation uploads it to an S3 bucket
in your AWS account. AWS CloudFormation creates a bucket for each region in which
you upload a template file. The buckets are accessible to anyone with Amazon Simple
Storage Service (Amazon S3) permissions in your AWS account. If a bucket created by AWS
CloudFormation is already present, the template is added to that bucket.
You can use your own bucket and manage its permissions by manually uploading templates
to Amazon S3. Then whenever you create or update a stack, specify the Amazon S3 URL of a
template file.
AWS CloudFormation provisions and configures resources by making calls to the AWS services that are
described in your template.
After all the resources have been created, AWS CloudFormation reports that your stack has been created.
You can then start using the resources in your stack. If stack creation fails, AWS CloudFormation rolls
back your changes by deleting the resources that it created.
API Version 2010-05-15
6

AWS CloudFormation User Guide
Updating a Stack with Change Sets

Updating a Stack with Change Sets
When you need to update your stack's resources, you can modify the stack's template. You don't need
to create a new stack and delete the old one. To update a stack, create a change set by submitting
a modified version of the original stack template, different input parameter values, or both. AWS
CloudFormation compares the modified template with the original template and generates a change
set. The change set lists the proposed changes. After reviewing the changes, you can execute the change
set to update your stack or you can create a new change set. The following diagram summarizes the
workflow for updating a stack.

Important

Updates can cause interruptions. Depending on the resource and properties that you are
updating, an update might interrupt or even replace an existing resource. For more information,
see AWS CloudFormation Stacks Updates (p. 118).
1. You can modify an AWS CloudFormation stack template by using AWS CloudFormation Designer or
a text editor. For example, if you want to change the instance type for an EC2 instance, you would
change the value of the InstanceType property in the original stack's template.
For more information, see Modifying a Stack Template (p. 119).
2. Save the AWS CloudFormation template locally or in an S3 bucket.
3. Create a change set by specifying the stack that you want to update and the location of the modified
template, such as a path on your local computer or an Amazon S3 URL. If the template contains
parameters, you can specify values when you create the change set.
For more information about creating change sets, see Updating Stacks Using Change Sets (p. 122).

Note

If you specify a template that is stored on your local computer, AWS CloudFormation
automatically uploads your template to an S3 bucket in your AWS account.
4. View the change set to check that AWS CloudFormation will perform the changes that you expect. For
example, check whether AWS CloudFormation will replace any critical stack resources. You can create
as many change sets as you need until you have included the changes that you want.

Important

Change sets don't indicate whether your stack update will be successful. For example,
a change set doesn't check if you will surpass an account limit (p. 21), if you're
updating a resource (p. 499) that doesn't support updates, or if you have insufficient
permissions (p. 9) to modify a resource, all of which can cause a stack update to fail.
5. Execute the change set that you want to apply to your stack. AWS CloudFormation updates your stack
by updating only the resources that you modified and signals that your stack has been successfully
updated. If the stack updates fails, AWS CloudFormation rolls back changes to restore the stack to the
last known working state.

API Version 2010-05-15
7

AWS CloudFormation User Guide
Deleting a Stack

Deleting a Stack
When you delete a stack, you specify the stack to delete, and AWS CloudFormation deletes the stack and
all the resources in that stack. You can delete stacks by using the AWS CloudFormation console (p. 105),
API, or AWS CLI.
If you want to delete a stack but want to retain some resources in that stack, you can use a deletion
policy (p. 2248) to retain those resources.
After all the resources have been deleted, AWS CloudFormation signals that your stack has been
successfully deleted. If AWS CloudFormation cannot delete a resource, the stack will not be deleted. Any
resources that haven't been deleted will remain until you can successfully delete the stack.

Additional Resources
• For more information about creating AWS CloudFormation templates, see Template
Anatomy (p. 163).
• For more information about creating, updating, or deleting stacks, see Working with Stacks (p. 90).

API Version 2010-05-15
8

AWS CloudFormation User Guide
Signing Up for an AWS Account and Pricing

Setting Up
Before you start using AWS CloudFormation, you might need to know what IAM permissions you need,
how to start logging AWS CloudFormation API calls, or what endpoints to use. The following topics
provide this information so that you can start using AWS CloudFormation.
Topics
• Signing Up for an AWS Account and Pricing (p. 9)
• Controlling Access with AWS Identity and Access Management (p. 9)
• Logging AWS CloudFormation API Calls with AWS CloudTrail (p. 17)
• AWS CloudFormation Limits (p. 21)
• AWS CloudFormation Endpoints (p. 23)
• AWS CloudFormation and VPC Endpoints (p. 24)

Signing Up for an AWS Account and Pricing
Before you can use AWS CloudFormation or any Amazon Web Services, you must first sign up for an AWS
account.

To sign up for an AWS account
1.

Open https://aws.amazon.com/, and then choose Create an AWS Account.

Note

2.

This might be unavailable in your browser if you previously signed into the AWS
Management Console. In that case, choose Sign in to a different account, and then choose
Create a new AWS account.
Follow the online instructions.
Part of the sign-up procedure involves receiving a phone call and entering a PIN using the phone
keypad.

After signing up for an AWS account, you can use AWS CloudFormation through the AWS Management
Console, AWS CloudFormation API, or AWS CLI.

Pricing
AWS CloudFormation is a free service; however, you are charged for the AWS resources you include in
your stacks at the current rates for each. For more information about AWS pricing, go to the detail page
for each product on http://aws.amazon.com.

Controlling Access with AWS Identity and Access
Management
With AWS Identity and Access Management (IAM), you can create IAM users to control who has access
to which resources in your AWS account. You can use IAM with AWS CloudFormation to control what
users can do with AWS CloudFormation, such as whether they can view stack templates, create stacks, or
delete stacks.
API Version 2010-05-15
9

AWS CloudFormation User Guide
AWS CloudFormation Actions

In addition to AWS CloudFormation actions, you can manage what AWS services and resources are
available to each user. That way, you can control which resources users can access when they use
AWS CloudFormation. For example, you can specify which users can create Amazon EC2 instances,
terminate database instances, or update VPCs. Those same permissions are applied anytime they use
AWS CloudFormation to do those actions.
For more information about all the services that you can control access to, see AWS Services that
Support IAM in IAM User Guide.
Topics
• AWS CloudFormation Actions (p. 10)
• AWS CloudFormation Resources (p. 11)
• AWS CloudFormation Conditions (p. 12)
• Acknowledging IAM Resources in AWS CloudFormation Templates (p. 15)
• Manage Credentials for Applications Running on Amazon EC2 Instances (p. 16)
• Grant Temporary Access (Federated Access) (p. 16)
• AWS CloudFormation Service Role (p. 17)

AWS CloudFormation Actions
When you create a group or an IAM user in your AWS account, you can associate an IAM policy with that
group or user, which specifies the permissions that you want to grant. For example, imagine you have
a group of entry-level developers. You can create a Junior application developers group that
includes all entry-level developers. Then, you associate a policy with that group that allows users to only
view AWS CloudFormation stacks. In this scenario, you might have a policy such as the following sample:

Example A sample policy that grants view stack permissions
{

}

"Version":"2012-10-17",
"Statement":[{
"Effect":"Allow",
"Action":[
"cloudformation:DescribeStacks",
"cloudformation:DescribeStackEvents",
"cloudformation:DescribeStackResource",
"cloudformation:DescribeStackResources"
],
"Resource":"*"
}]

The policy grants permissions to all DescribeStack API actions listed in the Action element.

Note

If you don't specify a stack name or ID in your statement, you must also grant the permission to
use all resources for the action using the * wildcard for the Resource element.
In addition to AWS CloudFormation actions, IAM users who create or delete stacks require additional
permissions that depends on the stack templates. For example, if you have a template that describes
an Amazon SQS Queue, the user must have the corresponding permissions for Amazon SQS actions to
successfully create the stack, as shown in the following sample policy:

Example A sample policy that grants create and view stack actions and all Amazon SQS
actions
{

API Version 2010-05-15
10

AWS CloudFormation User Guide
AWS CloudFormation Resources

}

"Version":"2012-10-17",
"Statement":[{
"Effect":"Allow",
"Action":[
"sqs:*",
"cloudformation:CreateStack",
"cloudformation:DescribeStacks",
"cloudformation:DescribeStackEvents",
"cloudformation:DescribeStackResources",
"cloudformation:GetTemplate",
"cloudformation:ValidateTemplate"
],
"Resource":"*"
}]

For a list of all AWS CloudFormation actions that you can allow or deny, see the AWS CloudFormation API
Reference.

AWS CloudFormation Console-Specific Actions
IAM users who use the AWS CloudFormation console require additional permissions that are not required
for using the AWS Command Line Interface or AWS CloudFormation APIs. Compared to the CLI and API,
the console provides additional features that require additional permissions, such as template uploads to
Amazon S3 buckets and drop-down lists for AWS-specific parameter types (p. 171).
For all the following actions, grant permissions to all resources; don't limit actions to specific stacks or
buckets.
The following required action is used only by the AWS CloudFormation console and is not documented in
the API reference. The action allows users to upload templates to Amazon S3 buckets.
cloudformation:CreateUploadBucket

When users upload templates, they require the following Amazon S3 permissions:
s3:PutObject
s3:ListBucket
s3:GetObject
s3:CreateBucket

For templates with AWS-specific parameter types (p. 171), users need permissions
to make the corresponding describe API calls. For example, if a template includes the
AWS::EC2::KeyPair::KeyName parameter type, users need permission to call the EC2
DescribeKeyPairs action (this is how the console gets values for the parameter drop-down list). The
following examples are actions that users need for other parameter types:
ec2:DescribeSecurityGroups (for the AWS::EC2::SecurityGroup::Id parameter type)
ec2:DescribeSubnets (for the Subnet::Id parameter type)
ec2:DescribeVpcs (for the AWS::EC2::VPC::Id parameter type)

AWS CloudFormation Resources
AWS CloudFormation supports resource-level permissions, so you can specify actions for a specific stack,
as shown in the following policy:
API Version 2010-05-15
11

AWS CloudFormation User Guide
AWS CloudFormation Conditions

Example A sample policy that denies the delete and update stack actions for the
MyProductionStack
{

*"
}

"Version":"2012-10-17",
"Statement":[{
"Effect":"Deny",
"Action":[
"cloudformation:DeleteStack",
"cloudformation:UpdateStack"
],
"Resource":"arn:aws:cloudformation:us-east-1:123456789012:stack/MyProductionStack/
}]

The policy above uses a wild card at the end of the stack name so that delete stack and update stack are
denied on the full stack ID (such as arn:aws:cloudformation:us-east-1:123456789012:stack/
MyProductionStack/abc9dbf0-43c2-11e3-a6e8-50fa526be49c) and on the stack name (such as
MyProductionStack).
To allow AWS::Serverless transforms to create a change set, the policy should include the
arn:aws:cloudformation::aws:transform/Serverless-2016-10-31 resource-level
permission, as shown in the folllowing policy:

Example A sample policy that allows the create change set action for the transform
{

}

"Version": "2012-10-17",
"Statement": [{
"Effect": "Allow",
"Action": [
"cloudformation:CreateChangeSet"
],
"Resource": "arn:aws:cloudformation:us-west-2:aws:transform/Serverless-2016-10-31"
}]

AWS CloudFormation Conditions
In an IAM policy, you can optionally specify conditions that control when a policy is in effect. For
example, you can define a policy that allows IAM users to create a stack only when they specify a certain
template URL. You can define AWS CloudFormation-specific conditions and AWS-wide conditions, such
as DateLessThan, which specifies when a policy stops taking effect. For more information and a list of
AWS-wide conditions, see Condition in IAM Policy Elements Reference in IAM User Guide.

Note

Do not use the aws:SourceIp AWS-wide condition. AWS CloudFormation provisions resources
by using its own IP address, not the IP address of the originating request. For example, when
you create a stack, AWS CloudFormation makes requests from its IP address to launch an EC2
instance or to create an S3 bucket, not from the IP address from the CreateStack call or the
aws cloudformation create-stack command.
The following list describes the AWS CloudFormation-specific conditions. These conditions are applied
only when users create or update stacks:
cloudformation:ChangeSetName
An AWS CloudFormation change set name that you want to associate with a policy. Use this
condition to control which change sets IAM users can execute or delete.
API Version 2010-05-15
12

AWS CloudFormation User Guide
AWS CloudFormation Conditions

cloudformation:ResourceTypes
The template resource types, such as AWS::EC2::Instance, that you want to associate with
a policy. Use this condition to control which resource types IAM users can work with when they
create or update a stack. This condition is checked against the resource types that users declare
in the ResourceTypes parameter, which is currently supported only for CLI and API requests.
When using this parameter, users must specify all the resource types that are in their template. For
more information about the ResourceTypes parameter, see the CreateStack action in the AWS
CloudFormation API Reference.
The following list describes how to define resource types. For a list of resource types, see AWS
Resource Types Reference (p. 499).
AWS::*
Specify all AWS resources.
AWS::service_name::*
Specify all resources for a specific AWS service.
AWS::service_name::resource_type
Specify a specific AWS resource type, such as AWS::EC2::Instance (all EC2 instances).
Custom::*
Specify all custom resources.
Custom::resource_type
Specify a specific custom resource type, which is defined in the template.
cloudformation:RoleARN
The Amazon Resource Name (ARN) of an IAM service role that you want to associate with a policy.
Use this condition to control which service role IAM users can use when they work with stacks or
change sets.
cloudformation:StackPolicyUrl
An Amazon S3 stack policy URL that you want to associate with a policy. Use this condition to
control which stack policies IAM users can associate with a stack during a create or update stack
action. For more information about stack policies, see Prevent Updates to Stack Resources (p. 141).

Note

To ensure that IAM users can only create or update stacks with the stack policies that you
uploaded, set the S3 bucket to read only for those users.
cloudformation:TemplateUrl
An Amazon S3 template URL that you want to associate with a policy. Use this condition to control
which templates IAM users can use when they create or update stacks.

Note

To ensure that IAM users can only create or update stacks with the templates that you
uploaded, set the S3 bucket to read only for those users.

Examples
The following example policy allows users to use only the https://s3.amazonaws.com/
testbucket/test.template template URL to create or update a stack.
API Version 2010-05-15
13

AWS CloudFormation User Guide
AWS CloudFormation Conditions

Example Template URL Condition
{

"Version":"2012-10-17",
"Statement":[
{
"Effect" : "Allow",
"Action" : [ "cloudformation:CreateStack", "cloudformation:UpdateStack" ],
"Resource" : "*",
"Condition" : {
"ForAllValues:StringEquals" : {
"cloudformation:TemplateUrl" : [ "https://s3.amazonaws.com/testbucket/
test.template" ]
}
}
}
]
}

The following example policy allows users to create stacks but denies requests if the stack's template
include any resource from the IAM service. The policy also requires users to specify the ResourceTypes
parameter, which is available only for CLI and API requests. This policy uses explicit deny statements so
that if any other policy grants additional permissions, this policy always remain in effect (an explicit deny
statement always overrides an explicit allow statement).

Example Resource Type Condition
{

}

"Version":"2012-10-17",
"Statement":[
{
"Effect" : "Allow",
"Action" : [ "cloudformation:CreateStack" ],
"Resource" : "*"
},
{
"Effect" : "Deny",
"Action" : [ "cloudformation:CreateStack" ],
"Resource" : "*",
"Condition" : {
"ForAnyValue:StringLikeIfExists" : {
"cloudformation:ResourceTypes" : [ "AWS::IAM::*" ]
}
}
},
{
"Effect": "Deny",
"Action" : [ "cloudformation:CreateStack" ],
"Resource": "*",
"Condition": {
"Null": {
"cloudformation:ResourceTypes": "true"
}
}
}
]

The following example policy is similar to the preceding example. The policy allows users to create a
stack unless the stack's template includes any resource from the IAM service. It also requires users to
specify the ResourceTypes parameter, which is available only for CLI and API requests. This policy is
API Version 2010-05-15
14

AWS CloudFormation User Guide
Acknowledging IAM Resources in
AWS CloudFormation Templates

simpler, but it doesn't use explicit deny statements. Other policies, granting additional permissions, could
override this policy.

Example Resource Type Condition
{

}

"Version":"2012-10-17",
"Statement":[
{
"Effect" : "Allow",
"Action" : [ "cloudformation:CreateStack" ],
"Resource" : "*",
"Condition" : {
"ForAllValues:StringNotLikeIfExists" : {
"cloudformation:ResourceTypes" : [ "AWS::IAM::*" ]
},
"Null":{
"cloudformation:ResourceTypes": "false"
}
}
}
]

Acknowledging IAM Resources in AWS
CloudFormation Templates
Before you can create a stack, AWS CloudFormation validates your template. During validation, AWS
CloudFormation checks your template for IAM resources that it might create. IAM resources, such as
an IAM user with full access, can access and modify any resource in your AWS account. Therefore, we
recommend that you review the permissions associated with each IAM resource before proceeding so
that you don't unintentionally create resources with escalated permissions. To ensure that you've done
so, you must acknowledge that the template contains those resources, giving AWS CloudFormation the
specified capabilities before it creates the stack.
You can acknowledge the capabilities of AWS CloudFormation templates by using the AWS
CloudFormation console, AWS Command Line Interface (CLI), or API:
• In the AWS CloudFormation console, on the Review page of the Create Stack or Update Stack wizards,
choose I acknowledge that this template may create IAM resources.
• In the CLI, when you use the aws cloudformation create-stack and aws cloudformation
update-stack commands, specify the CAPABILITY_IAM or CAPABILITY_NAMED_IAM value
for the --capabilities parameter. If your template includes IAM resources, you can specify
either capability. If your template includes custom names for IAM resources, you must specify
CAPABILITY_NAMED_IAM.
• In the API, when you use the CreateStack and UpdateStack
actions, specify Capabilities.member.1=CAPABILITY_IAM or
Capabilities.member.1=CAPABILITY_NAMED_IAM. If your template includes IAM resources, you
can specify either capability. If your template includes custom names for IAM resources, you must
specify CAPABILITY_NAMED_IAM.

Important

If your template contains custom named IAM resources, don't create multiple stacks reusing
the same template. IAM resources must be globally unique within your account. If you use the
same template to create multiple stacks in different regions, your stacks might share the same
IAM resources, instead of each having a unique one. Shared resources among stacks can have
API Version 2010-05-15
15

AWS CloudFormation User Guide
Manage Credentials for Applications
Running on Amazon EC2 Instances

unintended consequences from which you can't recover. For example, if you delete or update
shared IAM resources in one stack, you will unintentionally modify the resources of other stacks.

Manage Credentials for Applications Running on
Amazon EC2 Instances
If you have an application that runs on an Amazon EC2 instance and needs to make requests to AWS
resources such as Amazon S3 buckets or an DynamoDB table, the application requires AWS security
credentials. However, distributing and embedding long-term security credentials in every instance that
you launch is a challenge and a potential security risk. Instead of using long-term credentials, like IAM
user credentials, we recommend that you create an IAM role that is associated with an Amazon EC2
instance when the instance is launched. An application can then get temporary security credentials from
the Amazon EC2 instance. You don't have to embed long-term credentials on the instance. Also, to make
managing credentials easier, you can specify just a single role for multiple Amazon EC2 instances; you
don't have to create unique credentials for each instance.
For a template snippet that shows how to launch an instance with a role, see IAM Role Template
Examples (p. 396).

Note

Applications on instances that use temporary security credentials can call any AWS
CloudFormation actions. However, because AWS CloudFormation interacts with many other AWS
services, you must verify that all the services that you want to use support temporary security
credentials. For more information, see AWS Services that Support AWS STS.

Grant Temporary Access (Federated Access)
In some cases, you might want to grant users with no AWS credentials temporary access to your AWS
account. Instead of creating and deleting long-term credentials whenever you want to grant temporary
access, use AWS Security Token Service (AWS STS). For example, you can use IAM roles. From one IAM
role, you can programmatically create and then distribute many temporary security credentials (which
include an access key, secret access key, and security token). These credentials have a limited life, so they
cannot be used to access your AWS account after they expire. You can also create multiple IAM roles
in order to grant individual users different levels of permissions. IAM roles are useful for scenarios like
federated identities and single sign-on.
A federated identity is a distinct identity that you can use across multiple systems. For enterprise users
with an established on-premises identity system (such as LDAP or Active Directory), you can handle
all authentication with your on-premises identity system. After a user has been authenticated, you
provide temporary security credentials from the appropriate IAM user or role. For example, you can
create an administrators role and a developers role, where administrators have full access to
the AWS account and developers have permissions to work only with AWS CloudFormation stacks.
After an administrator is authenticated, the administrator is authorized to obtain temporary security
credentials from the administrators role. However, for developers, they can obtain temporary
security credentials from only the developers role.
You can also grant federated users access to the AWS Management Console. After users authenticate
with your on-premises identity system, you can programmatically construct a temporary URL that gives
direct access to the AWS Management Console. When users use the temporary URL, they won't need to
sign in to AWS because they have already been authenticated (single sign-on). Also, because the URL is
constructed from the users' temporary security credentials, the permissions that are available with those
credentials determine what permissions users have in the AWS Management Console.
You can use several different AWS STS APIs to generate temporary security credentials. For more
information about which API to use, see Ways to Get Temporary Security Credentials in Using Temporary
Security Credentials.
API Version 2010-05-15
16

AWS CloudFormation User Guide
AWS CloudFormation Service Role

Important

You cannot work with IAM when you use temporary security credentials that were generated
from the GetFederationToken API. Instead, if you need to work with IAM, use temporary
security credentials from a role.
AWS CloudFormation interacts with many other AWS services. When you use temporary security
credentials with AWS CloudFormation, verify that all the services that you want to use support
temporary security credentials. For more information, see AWS Services that Support AWS STS.
For more information, see the following related resources in Using Temporary Security Credentials:
• Scenarios for Granting Temporary Access
• Giving Federated Users Direct Access to the AWS Management Console

AWS CloudFormation Service Role
A service role is an AWS Identity and Access Management (IAM) role that allows AWS CloudFormation
to make calls to resources in a stack on your behalf. You can specify an IAM role that allows AWS
CloudFormation to create, update, or delete your stack resources. By default, AWS CloudFormation uses
a temporary session that it generates from your user credentials for stack operations. If you specify a
service role, AWS CloudFormation uses the role's credentials.
Use a service role to explicitly specify the actions that AWS CloudFormation can perform which
might not always be the same actions that you or other users can do. For example, you might have
administrative privileges, but you can limit AWS CloudFormation access to only Amazon EC2 actions.
You create the service role and its permission policy with the IAM service. For more information about
creating a service role, see Creating a Role to Delegate Permissions to an AWS Service in the IAM User
Guide. Specify AWS CloudFormation (cloudformation.amazonaws.com) as the service that can
assume the role.
To associate a service role with a stack, specify the role when you create the stack. For details, see
Setting Stack Options (p. 95). You can also change the service role when you update (p. 118)
or delete the stack. Before you specify a service role, ensure that you have permission to pass it
(iam:PassRole). The iam:PassRole permission specifies which roles you can use.

Important

When you specify a service role, AWS CloudFormation always uses that role for all operations
that are performed on that stack. Other users that have permissions to perform operations on
this stack will be able to use this role, even if they don't have permission to pass it. If the role
includes permissions that the user shouldn't have, you can unintentionally escalate a user's
permissions. Ensure that the role grants least privilege.

Logging AWS CloudFormation API Calls with AWS
CloudTrail
AWS CloudFormation is integrated with AWS CloudTrail, a service that provides a record of actions
taken by a user, role, or an AWS service in AWS CloudFormation. CloudTrail captures all API calls for
AWS CloudFormation as events, including calls from the AWS CloudFormation console and from code
calls to the AWS CloudFormation APIs. If you create a trail, you can enable continuous delivery of
CloudTrail events to an Amazon S3 bucket, including events for AWS CloudFormation. If you don't
configure a trail, you can still view the most recent events in the CloudTrail console in Event history.
Using the information collected by CloudTrail, you can determine the request that was made to AWS
CloudFormation, the IP address from which the request was made, who made the request, when it was
made, and additional details.
API Version 2010-05-15
17

AWS CloudFormation User Guide
AWS CloudFormation Information in CloudTrail

To learn more about CloudTrail, see the AWS CloudTrail User Guide.
Topics
• AWS CloudFormation Information in CloudTrail (p. 18)
• Understanding AWS CloudFormation Log File Entries (p. 18)

AWS CloudFormation Information in CloudTrail
CloudTrail is enabled on your AWS account when you create the account. When activity occurs in AWS
CloudFormation, that activity is recorded in a CloudTrail event along with other AWS service events
in Event history. You can view, search, and download recent events in your AWS account. For more
information, see Viewing Events with CloudTrail Event History.
For an ongoing record of events in your AWS account, including events for AWS CloudFormation, create
a trail. A trail enables CloudTrail to deliver log files to an Amazon S3 bucket. By default, when you create
a trail in the console, the trail applies to all regions. The trail logs events from all regions in the AWS
partition and delivers the log files to the Amazon S3 bucket that you specify. Additionally, you can
configure other AWS services to further analyze and act upon the event data collected in CloudTrail logs.
For more information, see:
• Overview for Creating a Trail
• CloudTrail Supported Services and Integrations
• Configuring Amazon SNS Notifications for CloudTrail
• Receiving CloudTrail Log Files from Multiple Regions and Receiving CloudTrail Log Files from Multiple
Accounts
All AWS CloudFormation actions are logged by CloudTrail and are documented in the AWS
CloudFormation API Reference. For example, calls to the CreateStack, DeleteStack, and ListStacks
sections generate entries in the CloudTrail log files.
Every event or log entry contains information about who generated the request. The identity
information helps you determine the following:
• Whether the request was made with root or IAM user credentials.
• Whether the request was made with temporary security credentials for a role or federated user.
• Whether the request was made by another AWS service.
For more information, see the CloudTrail userIdentity Element.

Understanding AWS CloudFormation Log File Entries
A trail is a configuration that enables delivery of events as log files to an Amazon S3 bucket that you
specify. CloudTrail log files contain one or more log entries. An event represents a single request from
any source and includes information about the requested action, the date and time of the action, request
parameters, and so on. CloudTrail log files are not an ordered stack trace of the public API calls, so they
do not appear in any specific order.
The following example shows a CloudTrail log entry that demonstrates the CreateStack action. The
action was made by an IAM user named Alice.

Note

Only the input parameter key names are logged; no parameter values are logged.
{

API Version 2010-05-15
18

AWS CloudFormation User Guide
Understanding AWS CloudFormation Log File Entries
"eventVersion": "1.01",
"userIdentity": {
"type": "IAMUser",
"principalId": "AIDAABCDEFGHIJKLNMOPQ",
"arn": "arn:aws:iam::012345678910:user/Alice",
"accountId": "012345678910",
"accessKeyId": "AKIDEXAMPLE",
"userName": "Alice"
},
"eventTime": "2014-03-24T21:02:43Z",
"eventSource": "cloudformation.amazonaws.com",
"eventName": "CreateStack",
"awsRegion": "us-east-1",
"sourceIPAddress": "127.0.0.1",
"userAgent": "aws-cli/1.2.11 Python/2.7.4 Linux/2.6.18-164.el5",
"requestParameters": {
"templateURL": "https://s3.amazonaws.com/Alice-dev/create_stack",
"tags": [
{
"key": "test",
"value": "tag"
}
],
"stackName": "my-test-stack",
"disableRollback": true,
"parameters": [
{
"parameterKey": "password"
},
{
"parameterKey": "securitygroup"
}
]
},
"responseElements": {
"stackId": "arn:aws:cloudformation:us-east-1:012345678910:stack/my-test-stack/a38e6a60b397-11e3-b0fc-08002755629e"
},
"requestID": "9f960720-b397-11e3-bb75-a5b75389b02d",
"eventID": "9bf6cfb8-83e1-4589-9a70-b971e727099b"
}

The following example shows that Alice called the UpdateStack action on the my-test-stack stack:
{

"eventVersion": "1.01",
"userIdentity": {
"type": "IAMUser",
"principalId": "AIDAABCDEFGHIJKLNMOPQ",
"arn": "arn:aws:iam::012345678910:user/Alice",
"accountId": "012345678910",
"accessKeyId": "AKIDEXAMPLE",
"userName": "Alice"
},
"eventTime": "2014-03-24T21:04:29Z",
"eventSource": "cloudformation.amazonaws.com",
"eventName": "UpdateStack",
"awsRegion": "us-east-1",
"sourceIPAddress": "127.0.0.1",
"userAgent": "aws-cli/1.2.11 Python/2.7.4 Linux/2.6.18-164.el5",
"requestParameters": {
"templateURL": "https://s3.amazonaws.com/Alice-dev/create_stack",
"parameters": [
{
"parameterKey": "password"

API Version 2010-05-15
19

AWS CloudFormation User Guide
Understanding AWS CloudFormation Log File Entries
},
{
}

"parameterKey": "securitygroup"

],
"stackName": "my-test-stack"

},
"responseElements": {
"stackId": "arn:aws:cloudformation:us-east-1:012345678910:stack/my-test-stack/a38e6a60b397-11e3-b0fc-08002755629e"
},
"requestID": "def0bf5a-b397-11e3-bb75-a5b75389b02d",
"eventID": "637707ce-e4a3-4af1-8edc-16e37e851b17"
}

The following example shows that Alice called the ListStacks action.
{

}

"eventVersion": "1.01",
"userIdentity": {
"type": "IAMUser",
"principalId": "AIDAABCDEFGHIJKLNMOPQ",
"arn": "arn:aws:iam::012345678910:user/Alice",
"accountId": "012345678910",
"accessKeyId": "AKIDEXAMPLE",
"userName": "Alice"
},
"eventTime": "2014-03-24T21:03:16Z",
"eventSource": "cloudformation.amazonaws.com",
"eventName": "ListStacks",
"awsRegion": "us-east-1",
"sourceIPAddress": "127.0.0.1",
"userAgent": "aws-cli/1.2.11 Python/2.7.4 Linux/2.6.18-164.el5",
"requestParameters": null,
"responseElements": null,
"requestID": "b7d351d7-b397-11e3-bb75-a5b75389b02d",
"eventID": "918206d0-7281-4629-b778-b91eb0d83ce5"

The following example shows that Alice called the DescribeStacks action on the my-test-stack
stack.
{

"eventVersion": "1.01",
"userIdentity": {
"type": "IAMUser",
"principalId": "AIDAABCDEFGHIJKLNMOPQ",
"arn": "arn:aws:iam::012345678910:user/Alice",
"accountId": "012345678910",
"accessKeyId": "AKIDEXAMPLE",
"userName": "Alice"
},
"eventTime": "2014-03-24T21:06:15Z",
"eventSource": "cloudformation.amazonaws.com",
"eventName": "DescribeStacks",
"awsRegion": "us-east-1",
"sourceIPAddress": "127.0.0.1",
"userAgent": "aws-cli/1.2.11 Python/2.7.4 Linux/2.6.18-164.el5",
"requestParameters": {
"stackName": "my-test-stack"
},
"responseElements": null,
"requestID": "224f2586-b398-11e3-bb75-a5b75389b02d",

API Version 2010-05-15
20

AWS CloudFormation User Guide
Limits

}

"eventID": "9e5b2fc9-1ba8-409b-9c13-587c2ea940e2"

The following example shows that Alice called the DeleteStack action on the my-test-stack stack.
{

}

"eventVersion": "1.01",
"userIdentity": {
"type": "IAMUser",
"principalId": "AIDAABCDEFGHIJKLNMOPQ",
"arn": "arn:aws:iam::012345678910:user/Alice",
"accountId": "012345678910",
"accessKeyId": "AKIDEXAMPLE",
"userName": "Alice"
},
"eventTime": "2014-03-24T21:07:15Z",
"eventSource": "cloudformation.amazonaws.com",
"eventName": "DeleteStack",
"awsRegion": "us-east-1",
"sourceIPAddress": "127.0.0.1",
"userAgent": "aws-cli/1.2.11 Python/2.7.4 Linux/2.6.18-164.el5",
"requestParameters": {
"stackName": "my-test-stack"
},
"responseElements": null,
"requestID": "42dae739-b398-11e3-bb75-a5b75389b02d",
"eventID": "4965eb38-5705-4942-bb7f-20ebe79aa9aa"

AWS CloudFormation Limits
Your AWS account has AWS CloudFormation limits that you might need to know when authoring
templates and creating stacks. By understanding these limits, you can avoid limitation errors that would
require you to redesign your templates or stacks.

AWS CloudFormation limits
Limit

Description

Value

Tuning Strategy

cfn-signal
wait condition
data (p. 2331)

Maximum amount of
data that cfn-signal can
pass.

4,096 bytes

To pass a larger
amount, send the
data to an Amazon S3
bucket, and then use
cfn-signal to pass the
Amazon S3 URL to that
bucket.

Custom resource
response (p. 674)

Maximum amount of
data that a custom
resource provider can
pass.

4,096 bytes

Mappings (p. 163)

Maximum number of
mappings that you
can declare in your
AWS CloudFormation
template.

100 mappings

API Version 2010-05-15
21

To specify more
mappings, separate
your template into
multiple templates
by using, for example,
nested stacks (p. 694).

AWS CloudFormation User Guide
Limits

Limit

Description

Value

Tuning Strategy

Mapping
attributes (p. 163)

Maximum number of
mapping attributes
for each mapping that
you can declare in your
AWS CloudFormation
template.

64 attributes

To specify more
mapping attributes,
separate the attributes
into multiple mappings.

Mapping name and
mapping attribute
name (p. 163)

Maximum size of each
mapping name.

255 characters

Outputs (p. 163)

Maximum number
of outputs that you
can declare in your
AWS CloudFormation
template.

60 outputs

Output name (p. 163)

Maximum size of an
output name.

255 characters

Parameters (p. 163)

Maximum number of
parameters that you
can declare in your
AWS CloudFormation
template.

60 parameters

Parameter
name (p. 163)

Maximum size of a
parameter name.

255 characters

Parameter
value (p. 163)

Maximum size of a
parameter value.

4,096 bytes

To use a larger
parameter value, create
multiple parameters
and then use Fn::Join
to append the multiple
values into a single
value.

Resources (p. 163)

Maximum number of
resources that you
can declare in your
AWS CloudFormation
template.

200 resources

To specify more
resources, separate your
template into multiple
templates by using,
for example, nested
stacks (p. 694).

Resource
name (p. 163)

Maximum size of a
resource name.

255 characters

API Version 2010-05-15
22

To specify more
parameters, you can
use mappings or lists in
order to assign multiple
values to a single
parameter.

AWS CloudFormation User Guide
Endpoints

Limit

Description

Value

Tuning Strategy

Stacks (p. 90)

Maximum number of
AWS CloudFormation
stacks that you can
create.

200 stacks

To create more stacks,
delete stacks that you
don't need or request
an increase in the
maximum number of
stacks in your AWS
account. For more
information, see AWS
Service Limits in the
AWS General Reference.

StackSets (p. 465)

Maximum number of
AWS CloudFormation
stack sets you
can create in your
administrator account.

20 stack sets

StackSets (p. 465)

Maximum number of
stack instances you can
create per stack set.

500 stack instances per
stack set

Template body size in a
request (p. 163)

Maximum size of
a template body
that you can pass
in a CreateStack,
UpdateStack, or
ValidateTemplate
request.

51,200 bytes

To use a larger
template body,
separate your template
into multiple templates
by using, for example,
nested stacks (p. 694).
Or upload the template
to an Amazon S3
bucket.

Template body size
in an Amazon S3
object (p. 163)

Maximum size of a
template body that
you can pass in an
Amazon S3 object
for a CreateStack,
UpdateStack,
ValidateTemplate
request with an
Amazon S3 template
URL.

460,800 bytes

To use a larger
template body,
separate your template
into multiple templates
by using, for example,
nested stacks (p. 694).

Template
description (p. 163)

Maximum size of a
template description.

1,024 bytes

AWS CloudFormation Endpoints
To reduce data latency in your applications, most Amazon Web Services products allow you to select a
regional endpoint to make your requests. An endpoint is a URL that is the entry point for a web service.
When you work with stacks by using the command line interface or API actions, you can specify a
regional endpoint. For more information about the regions and endpoints for AWS CloudFormation, see
Regions and Endpoints in the Amazon Web Services General Reference.
API Version 2010-05-15
23

AWS CloudFormation User Guide
AWS CloudFormation and VPC Endpoints

AWS CloudFormation and VPC Endpoints
You can use a VPC endpoint to create a private connection between your VPC and another AWS service
without requiring access over the Internet, through a NAT instance, a VPN connection, or AWS Direct
Connect. If you use AWS CloudFormation to create resources in a VPC with a VPC endpoint, you might
need to modify your IAM endpoint policy so that it permits access to certain S3 buckets.
AWS CloudFormation has S3 buckets in each region to monitor responses to a custom resource (p. 432)
request or a wait condition (p. 276). If a template includes custom resources or wait conditions in a
VPC, the VPC endpoint policy must allow users to send responses to the following buckets:
• For custom resources, permit traffic to the cloudformation-custom-resourceresponse-region bucket.
• For wait conditions, permit traffic to the cloudformation-waitcondition-region bucket.
If the endpoint policy blocks traffic to these buckets, AWS CloudFormation won't receive responses
and the stack operation fails. For example, if you have a resource in a VPC in the us-west-2
region that must respond to a wait condition, the resource must be able to send a response to the
cloudformation-waitcondition-us-west-2 bucket.
For a list of regions that AWS CloudFormation supports, see the Regions and Endpoints page in the
Amazon Web Services General Reference.

API Version 2010-05-15
24

AWS CloudFormation User Guide
Get Started

Getting Started with AWS
CloudFormation
Because you can use AWS CloudFormation to launch many different types of resources, the getting
started walkthrough will touch on just a few simple concepts to help you get an idea of how to use AWS
CloudFormation.
In this section, you will use the AWS Management Console to create a stack from an example template
from the AWS CloudFormation Sample Template Library and learn the basics of creating a template.
In the following walkthrough, we'll use a sample template to launch, update, and delete a stack. After
you learn the fundamentals, you can learn more about creating more complex templates and stacks.
AWS CloudFormation makes deploying a set of Amazon Web Services (AWS) resources as simple as
submitting a template. A template is a simple text file that describes a stack, a collection of AWS
resources you want to deploy together as a group. You use the template to define all the AWS resources
you want in your stack. This can include Amazon Elastic Compute Cloud instances, Amazon Relational
Database Service DB Instances, and other resources. For a list of resource types, see AWS Resource Types
Reference (p. 499).
The following video walks you through the stack creation example presented in the Get
Started (p. 25) section: Getting Started with AWS CloudFormation
Topics
• Get Started (p. 25)
• Learn Template Basics (p. 33)
• Walkthrough: Updating a Stack (p. 47)

Get Started
With the right template, you can deploy at once all the AWS resources you need for an application.
In this section, you'll examine a template that declares the resources for a WordPress blog, creates a
WordPress blog as a stack, monitors the stack creation process, examines the resources on the stack, and
then deletes the stack. You use the AWS Management Console to complete these tasks.

Step 1: Pick a template
First, you'll need a template that specifies the resources that you want in your stack. For this step, you
use a sample template that is already prepared. The sample template creates a basic WordPress blog
that uses a single Amazon EC2 instance with a local MySQL database for storage. The template also
creates an Amazon EC2 security group to control firewall settings for the Amazon EC2 instance.

Important

AWS CloudFormation is free, but the AWS resources that AWS CloudFormation creates are
live (and not running in a sandbox). You will incur the standard usage fees for these resources
API Version 2010-05-15
25

AWS CloudFormation User Guide
Step 1: Pick a template

until you terminate them in the last task in this tutorial. The total charges will be minimal. For
information about how you might minimize any charges, go to http://aws.amazon.com/free/.

To view the template
•

You can view the JSON or YAML WordPress sample template. You don't need to download it because
you will use the template URL later in this guide. For more information about the template formats,
see AWS CloudFormation Template Formats (p. 162).

A template is a JSON or YAML text file that contains the configuration information about the AWS
resources you want to create in the stack. For this walkthrough, the sample template includes six toplevel sections: AWSTemplateFormatVersion, Description, Parameters, Mappings, Resources,
and Outputs; however, only the Resources section is required.
The Resources section contains the definitions of the AWS resources you want to create with the
template. Each resource is listed separately and specifies the properties that are necessary for creating
that particular resource. The following resource declaration is the configuration for the EC2 instance,
which in this example has the logical name WebServer:

Example JSON
"Resources" : {
...
"WebServer": {
"Type" : "AWS::EC2::Instance",
"Properties": {
"ImageId" : { "Fn::FindInMap" : [ "AWSRegionArch2AMI", { "Ref" : "AWS::Region" },
{ "Fn::FindInMap" : [ "AWSInstanceType2Arch", { "Ref" :
"InstanceType" }, "Arch" ] } ] },
"InstanceType"
: { "Ref" : "InstanceType" },
"SecurityGroups" : [ {"Ref" : "WebServerSecurityGroup"} ],
"KeyName"
: { "Ref" : "KeyName" },
"UserData" : { "Fn::Base64" : { "Fn::Join" : ["", [
"#!/bin/bash -xe\n",
"yum update -y aws-cfn-bootstrap\n",
"/opt/aws/bin/cfn-init -v ",
"
--stack ", { "Ref" : "AWS::StackName" },
"
--resource WebServer ",
"
--configsets wordpress_install ",
"
--region ", { "Ref" : "AWS::Region" }, "\n",

]]}}
},
...

"/opt/aws/bin/cfn-signal -e $? ",
"
--stack ", { "Ref" : "AWS::StackName" },
"
--resource WebServer ",
"
--region ", { "Ref" : "AWS::Region" }, "\n"

},
...
"WebServerSecurityGroup" : {
"Type" : "AWS::EC2::SecurityGroup",
"Properties" : {
"GroupDescription" : "Enable HTTP access via port 80 locked down to the load balancer
+ SSH access",
"SecurityGroupIngress" : [
{"IpProtocol" : "tcp", "FromPort" : "80", "ToPort" : "80", "CidrIp" : "0.0.0.0/0"},
{"IpProtocol" : "tcp", "FromPort" : "22", "ToPort" : "22", "CidrIp" : { "Ref" :
"SSHLocation"}}
]
}

API Version 2010-05-15
26

AWS CloudFormation User Guide
Step 1: Pick a template
},
...

},

Example YAML
Resources:
...
WebServer:
Type: AWS::EC2::Instance
Properties:
ImageId: !FindInMap [AWSRegionArch2AMI, !Ref 'AWS::Region', !FindInMap
[AWSInstanceType2Arch, !Ref InstanceType, Arch]]
InstanceType:
Ref: InstanceType
KeyName:
Ref: KeyName
SecurityGroups:
- Ref: WebServerSecurityGroup
UserData:
Fn::Base64: !Sub |
#!/bin/bash -xe
yum update -y aws-cfn-bootstrap
/opt/aws/bin/cfn-init -v --stack ${AWS::StackId} --resource WebServer -configsets wordpress_install --region ${AWS::Region}
/opt/aws/bin/cfn-signal -e $? --stack ${AWS::StackId} --resource WebServer -region ${AWS::Region}
...
...
WebServerSecurityGroup:
Type: AWS::EC2::SecurityGroup
Properties:
GroupDescription: "Enable HTTP access via port 80 locked down to the load balancer +
SSH access"
SecurityGroupIngress:
- CidrIp: 0.0.0.0/0
FromPort: '80'
IpProtocol: tcp
ToPort: '80'
- CidrIp: !Ref SSHLocation
FromPort: '22'
IpProtocol: tcp
ToPort: '22'
...

If you have created EC2 instances before, you can recognize properties, such as ImageId,
InstanceType, and KeyName, that determine the configuration of the instance. Resource declarations
are an efficient way to specify all these configuration settings at once. When you put resource
declarations in a template, you can create and configure all the declared resources easily by using the
template to create a stack. To launch the same configuration of resources, all you have to do is create a
new stack that uses the same template.
The resource declaration begins with a string that specifies the logical name for the resource. As you'll
see, the logical name can be used to refer to resources within the template.
You use the Parameters section to declare values that can be passed to the template when you create
the stack. A parameter is an effective way to specify sensitive information, such as user names and
passwords, that you don't want to store in the template itself. It is also a way to specify information that
might be unique to the specific application or configuration you are deploying, for example, a domain
name or instance type. When you create the WordPress stack later in this section, you'll see the set of
API Version 2010-05-15
27

AWS CloudFormation User Guide
Step 1: Pick a template

parameters declared in the template appear on the Specify Details page of the Create Stack wizard,
where you can specify the parameters before you create the stack.
The following parameters are used in the template to specify values that are used in properties of the
EC2 instance:

Example JSON
"Parameters" : {
...
"KeyName": {
"Description" : "Name of an existing EC2 KeyPair to enable SSH access to the
instances",
"Type": "AWS::EC2::KeyPair::KeyName",
"ConstraintDescription" : "must be the name of an existing EC2 KeyPair."
},
"InstanceType" : {
"Description" : "WebServer EC2 instance type",
"Type" : "String",
"Default" : "t2.small",
"AllowedValues" : [ "t1.micro", "t2.nano", "t2.micro", "t2.small", "t2.medium",
"t2.large", "m1.small", "m1.medium", "m1.large", "m1.xlarge", "m2.xlarge", "m2.2xlarge",
"m2.4xlarge", "m3.medium", "m3.large", "m3.xlarge", "m3.2xlarge", "m4.large", "m4.xlarge",
"m4.2xlarge", "m4.4xlarge", "m4.10xlarge", "c1.medium", "c1.xlarge", "c3.large",
"c3.xlarge", "c3.2xlarge", "c3.4xlarge", "c3.8xlarge", "c4.large", "c4.xlarge",
"c4.2xlarge", "c4.4xlarge", "c4.8xlarge", "g2.2xlarge", "g2.8xlarge", "r3.large",
"r3.xlarge", "r3.2xlarge", "r3.4xlarge", "r3.8xlarge", "i2.xlarge", "i2.2xlarge",
"i2.4xlarge", "i2.8xlarge", "d2.xlarge", "d2.2xlarge", "d2.4xlarge", "d2.8xlarge",
"hi1.4xlarge", "hs1.8xlarge", "cr1.8xlarge", "cc2.8xlarge", "cg1.4xlarge"],
"ConstraintDescription" : "must be a valid EC2 instance type."
},
...

Example YAML
Parameters:
...
KeyName:
ConstraintDescription: must be the name of an existing EC2 KeyPair.
Description: Name of an existing EC2 KeyPair to enable SSH access to the instances
Type: AWS::EC2::KeyPair::KeyName
InstanceType:
AllowedValues:
- t1.micro
- t2.nano
- t2.micro
- t2.small
- t2.medium
- t2.large
- m1.small
- m1.medium
- m1.large
- m1.xlarge
- m2.xlarge
- m2.2xlarge
- m2.4xlarge
- m3.medium
- m3.large
- m3.xlarge
- m3.2xlarge
- m4.large

API Version 2010-05-15
28

AWS CloudFormation User Guide
Step 1: Pick a template

...

- m4.xlarge
- m4.2xlarge
- m4.4xlarge
- m4.10xlarge
- c1.medium
- c1.xlarge
- c3.large
- c3.xlarge
- c3.2xlarge
- c3.4xlarge
- c3.8xlarge
- c4.large
- c4.xlarge
- c4.2xlarge
- c4.4xlarge
- c4.8xlarge
- g2.2xlarge
- g2.8xlarge
- r3.large
- r3.xlarge
- r3.2xlarge
- r3.4xlarge
- r3.8xlarge
- i2.xlarge
- i2.2xlarge
- i2.4xlarge
- i2.8xlarge
- d2.xlarge
- d2.2xlarge
- d2.4xlarge
- d2.8xlarge
- hi1.4xlarge
- hs1.8xlarge
- cr1.8xlarge
- cc2.8xlarge
- cg1.4xlarge
ConstraintDescription: must be a valid EC2 instance type.
Default: t2.small
Description: WebServer EC2 instance type
Type: String

In the WebServer resource declaration, you see the KeyName property specified with the KeyName
parameter:

Example JSON
"WebServer" : {
"Type": "AWS::EC2::Instance",
"Properties": {
"KeyName" : { "Ref" : "KeyName" },
...
}
},

Example YAML
WebServer:
Type: AWS::EC2::Instance
Properties:
KeyName:
Ref: KeyName

API Version 2010-05-15
29

AWS CloudFormation User Guide
Step 2: Make sure you have prepared
any required items for the stack
...

The braces contain a call to the Ref (p. 2311) function with KeyName as its input. The Ref function
returns the value of the object it refers to. In this case, the Ref function sets the KeyName property to the
value that was specified for KeyName when the stack was created.
The Ref function can also set a resource's property to the value of another resource. For example, the
resource declaration WebServer contains the following property declaration:

Example JSON
"WebServer" : {
"Type": "AWS::EC2::Instance",
"Properties": {
...
"SecurityGroups" : [ {"Ref" : "WebServerSecurityGroup"} ],
...
}
},

Example YAML
WebServer:
Type: AWS::EC2::Instance
Properties:
SecurityGroups:
- Ref: WebServerSecurityGroup
...

The SecurityGroups property takes a list of EC2 security groups. The Ref function has an input of
WebServerSecurityGroup, which is the logical name of a security group in the template, and adds the
name of WebServerSecurityGroup to the SecurityGroups property.
In the template, you'll also find a Mappings section. You use mappings to declare conditional values that
are evaluated in a similar manner as a lookup table statement. The template uses mappings to select
the correct Amazon machine image (AMI) for the region and the architecture type for the instance type.
Outputs define custom values that are returned by the aws cloudformation describe-stacks
command and in the AWS CloudFormation console Outputs tab after the stack is created. You can use
output values to return information from the resources in the stack, such as the URL for a website that
was created in the template. We cover mappings, outputs, and other things about templates in more
detail in Learn Template Basics (p. 33).
That's enough about templates for now. Let's start creating a stack.

Step 2: Make sure you have prepared any required
items for the stack
Before you create a stack from a template, you must ensure that all dependent resources that the
template requires are available. A template can use or refer to both existing AWS resources and resources
declared in the template itself. AWS CloudFormation takes care of checking references to resources in the
template and also checks references to existing resources to ensure that they exist in the region where
you are creating the stack. If your template refers to a dependent resource that does not exist, stack
creation fails.
The example WordPress template contains an input parameter, KeyName, that specifies the key pair used
for the Amazon EC2 instance that is declared in the template. The template depends on the user who
creates a stack from the template to supply a valid Amazon EC2 key pair for the KeyName parameter. If
API Version 2010-05-15
30

AWS CloudFormation User Guide
Step 3: Create the stack

you supply a valid key pair name, the stack creates successfully. If you don't supply a valid key pair name,
the stack is rolled back.
Make sure you have a valid Amazon EC2 key pair and record the key pair name before you create the
stack.
To see your key pairs, open the Amazon EC2 console, then click Key Pairs in the navigation pane.

Note

If you don't have an Amazon EC2 key pair, you must create the key pair in the same region
where you are creating the stack. For information about creating a key pair, see Getting an SSH
Key Pair in the Amazon EC2 User Guide for Linux Instances.
Now that you have a valid key pair, let's use the WordPress template to create a stack.

Step 3: Create the stack
You will create your stack based on the WordPress-1.0.0 file discussed earlier. The template contains
several AWS resources, such as an EC2 instance.

To create the WordPress stack
1.

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

2.

If this is a new AWS CloudFormation account, click Create New Stack. Otherwise, click Create Stack.

3.

In the Template section, select Specify an Amazon S3 Template URL to type or paste the URL for
the sample WordPress template, and then click Next:
https://s3-us-west-2.amazonaws.com/cloudformation-templates-us-west-2/
WordPress_Single_Instance.template

Note

AWS CloudFormation templates that are stored in an S3 bucket must be accessible to the
user who is creating the stack, and must be located in the same region as the stack that is
being created. Therefore, if the S3 bucket is located in the us-east-2 Region, the stack
must also be created in us-east-2.
4.

In the Specify Details section, enter a stack name in the Name field. For this example, use
MyWPTestStack. The stack name cannot contain spaces.

5.

In the KeyName field, enter the name of a valid Amazon EC2 key pair in the same region you are
creating the stack.

Note

On the Specify Parameters page, you'll recognize the parameters from the Parameters
section of the template.
6.

Click Next.

7.

In this scenario, we won't add any tags. Click Next. Tags, which are key-value pairs, can help you
identify your stacks. For more information, see Adding Tags to Your AWS CloudFormation Stack.

8.

Review the information for the stack. When you're satisfied with the settings, click Create.

Your stack might take several minutes to create—but you probably don't want to just sit around waiting.
If you're like us, you'll want to know how the stack creation is going.

Step 4: Monitor the progress of stack creation
After you complete the Create Stack wizard, AWS CloudFormation begins creating the resources that are
specified in the template. Your new stack, MyWPTestStack, appears in the list at the top portion of the
API Version 2010-05-15
31

AWS CloudFormation User Guide
Step 5: Use your stack resources

CloudFormation console. Its status should be CREATE_IN_PROGRESS. You can see detailed status for a
stack by viewing its events.

To view the events for the stack
1.

On the AWS CloudFormation console, select the stack MyWPTestStack in the list.

2.

In the stack details pane, click the Events tab.
The console automatically refreshes the event list with the most recent events every 60 seconds.

The Events tab displays each major step in the creation of the stack sorted by the time of each event,
with latest events on top.
The first event (at the bottom of the event list) is the start of the stack creation process:
2013-04-24 18:54 UTC-7 CREATE_IN_PROGRESS AWS::CloudFormation::Stack
MyWPTestStack User initiated
Next are events that mark the beginning and completion of the creation of each resource. For example,
creation of the EC2 instance results in the following entries:
2013-04-24 18:59 UTC-7 CREATE_COMPLETE AWS::EC2::Instance...
2013-04-24 18:54 UTC-7 CREATE_IN_PROGRESS AWS::EC2::Instance...
The CREATE_IN_PROGRESS event is logged when AWS CloudFormation reports that it has begun to
create the resource. The CREATE_COMPLETE event is logged when the resource is successfully created.
When AWS CloudFormation has successfully created the stack, you will see the following event at the top
of the Events tab:
2013-04-24 19:17 UTC-7 CREATE_COMPLETE AWS::CloudFormation::Stack MyWPTestStack
If AWS CloudFormation cannot create a resource, it reports a CREATE_FAILED event and, by default,
rolls back the stack and deletes any resources that have been created. The Status Reason column
displays the issue that caused the failure.

Step 5: Use your stack resources
When the stack MyWPTestStack has a status of CREATE_COMPLETE, AWS CloudFormation has finished
creating the stack, and you can start using its resources.
The sample WordPress stack creates a WordPress website. You can continue with the WordPress setup by
running the WordPress installation script.

To complete the WordPress installation
1.

On the Outputs tab, in the WebsiteURL row, click the link in the Value column.
The WebsiteURL output value is the URL of the installation script for the WordPress website that
you created with the stack.

2.

On the web page for the WordPress installation, follow the on-screen instructions to complete
the WordPress installation. For more information about installing WordPress, see http://
codex.wordpress.org/Installing_WordPress.
After you complete the installation and log in, you are directed to the dashboard where you can set
additional options for your WordPress blog. Then, you can start writing posts for your blog that you
successfully created by using a AWS CloudFormation template.
API Version 2010-05-15
32

AWS CloudFormation User Guide
Step 6: Clean Up

Step 6: Clean Up
You have completed the AWS CloudFormation getting started tasks. To make sure you are not charged
for any unwanted services, you can clean up by deleting the stack and its resources.

To delete the stack and its resources
1.

From the AWS CloudFormation console, select the MyWPTestStack stack.

2.

Click Delete Stack.

3.

In the confirmation message that appears, click Yes, Delete.

The status for MyWPTestStack changes to DELETE_IN_PROGRESS. In the same way you monitored the
creation of the stack, you can monitor its deletion by using the Event tab. When AWS CloudFormation
completes the deletion of the stack, it removes the stack from the list.
Congratulations! You successfully picked a template, created a stack, viewed and used its resources, and
deleted the stack and its resources. Not only that, you were able to set up a WordPress blog using a AWS
CloudFormation template. You can find other templates in the AWS CloudFormation Sample Template
Library.
Now it's time to learn more about templates so that you can easily modify existing templates or create
your own: Learn Template Basics (p. 33).

Learn Template Basics
Topics
• What is an AWS CloudFormation Template? (p. 33)
• Resources: Hello Bucket! (p. 34)
• Resource Properties and Using Resources Together (p. 34)
• Receiving User Input Using Input Parameters (p. 40)
• Specifying Conditional Values Using Mappings (p. 42)
• Constructed Values and Output Values (p. 44)
• Next Steps (p. 46)
In Get Started (p. 25), you learned how to use a template to create a stack. You saw resources declared
in a template and how they map to resources in the stack. We also touched on input parameters and how
they enable you to pass in specific values when you create a stack from a template. In this section, we'll
go deeper into resources and parameters. We'll also cover the other components of templates so that
you'll know how to use these components together to create templates that produce the AWS resources
you want.

What is an AWS CloudFormation Template?
A template is a declaration of the AWS resources that make up a stack. The template is stored as a text
file whose format complies with the JavaScript Object Notation (JSON) or YAML standard. Because
they are just text files, you can create and edit them in any text editor and manage them in your source
control system with the rest of your source code. For more information about the template formats, see
AWS CloudFormation Template Formats (p. 162).
In the template, you declare the AWS resources you want to create and configure. You declare an object
as a name-value pair or a pairing of a name with a set of child objects enclosed. The syntax depends on
API Version 2010-05-15
33

AWS CloudFormation User Guide
Resources: Hello Bucket!

the format you use. For more information, see the Template Anatomy (p. 163). The only required toplevel object is the Resources object, which must declare at least one resource. Let's start with the most
basic template containing only a Resources object, which contains a single resource declaration.

Resources: Hello Bucket!
The Resources object contains a list of resource objects. A resource declaration contains the resource's
attributes, which are themselves declared as child objects. A resource must have a Type attribute, which
defines the kind of AWS resource you want to create. The Type attribute has a special format:
AWS::ProductIdentifier::ResourceType

For example, the resource type for an Amazon S3 bucket is AWS::S3::Bucket (p. 1403). For a full list of
resource types, see Template Reference (p. 499).
Let's take a look at a very basic template. The following template declares a single resource of type
AWS::S3::Bucket: with the name HelloBucket.

Example JSON
{

}

"Resources" : {
"HelloBucket" : {
"Type" : "AWS::S3::Bucket"
}
}

Example YAML
Resources:
HelloBucket:
Type: AWS::S3::Bucket

If you use this template to create a stack, AWS CloudFormation will create an Amazon S3 bucket.
Creating a bucket is simple, because AWS CloudFormation can create a bucket with default settings.
For other resources, such as an Auto Scaling group or EC2 instance, AWS CloudFormation requires more
information. Resource declarations use a Properties attribute to specify the information used to
create a resource.
Depending on the resource type, some properties are required, such as the ImageId property for an
AWS::EC2::Instance (p. 879) resource, and others are optional. Some properties have default values,
such as the AccessControl property of the AWS::S3::Bucket resource, so specifying a value for those
properties is optional. Other properties are not required but may add functionality that you want,
such as the WebsiteConfiguration property of the AWS::S3::Bucket resource. Specifying a value for
such properties is entirely optional and based on your needs. In the example above, because the
AWS::S3::Bucket resource has only optional properties and we didn't need any of the optional features,
we could accept the defaults and omit the Properties attribute.
To view the properties for each resource type, see the topics in Resource Property Types
Reference (p. 1581).

Resource Properties and Using Resources Together
Usually, a property for a resource is simply a string value. For example, the following template specifies a
canned ACL (PublicRead) for the AccessControl property of the bucket.
API Version 2010-05-15
34

AWS CloudFormation User Guide
Resource Properties and Using Resources Together

Example JSON
{

}

"Resources" : {
"HelloBucket" : {
"Type" : "AWS::S3::Bucket",
"Properties" : {
"AccessControl" : "PublicRead"
}
}
}

Example YAML
Resources:
HelloBucket:
Type: AWS::S3::Bucket
Properties:
AccessControl: PublicRead

Some resources can have multiple properties, and some properties can have one or more subproperties.
For example, the AWS::S3::Bucket (p. 1403) resource has two properties, AccessControl and
WebsiteConfiguration. The WebsiteConfiguration property has two subproperties, IndexDocument
and ErrorDocument. The following template shows our original bucket resource with the additional
properties.

Example JSON
{

}

"Resources" : {
"HelloBucket" : {
"Type" : "AWS::S3::Bucket",
"Properties" : {
"AccessControl" : "PublicRead",
"WebsiteConfiguration" : {
"IndexDocument" : "index.html",
"ErrorDocument" : "error.html"
}
}
}
}

Example YAML
Resources:
HelloBucket:
Type: AWS::S3::Bucket
Properties:
AccessControl: PublicRead
WebsiteConfiguration:
IndexDocument: index.html
ErrorDocument: error.html

One of the greatest benefits of templates and AWS CloudFormation is the ability to create a set of
resources that work together to create an application or solution. The name used for a resource within
the template is a logical name. When AWS CloudFormation creates the resource, it generates a physical
name that is based on the combination of the logical name, the stack name, and a unique ID.
API Version 2010-05-15
35

AWS CloudFormation User Guide
Resource Properties and Using Resources Together

You're probably wondering how you set properties on one resource based on the name or property
of another resource. For example, you can create a CloudFront distribution backed by an S3 bucket
or an EC2 instance that uses EC2 security groups, and all of these resources can be created in the
same template. AWS CloudFormation has a number of intrinsic functions that you can use to refer to
other resources and their properties. You can use the Ref function (p. 2311) to refer to an identifying
property of a resource. Frequently, this is the physical name of the resource; however, sometimes
it can be an identifier, such as the IP address for an AWS::EC2::EIP (p. 868) resource or an Amazon
Resource Name (ARN) for an Amazon SNS topic. For a list of values returned by the Ref function, see
Ref function (p. 2311). The following template contains an AWS::EC2::Instance (p. 879) resource.
The resource's SecurityGroups property calls the Ref function to refer to the AWS::EC2::SecurityGroup
resource InstanceSecurityGroup.

Example JSON
{

}

"Resources": {
"Ec2Instance": {
"Type": "AWS::EC2::Instance",
"Properties": {
"SecurityGroups": [
{
"Ref": "InstanceSecurityGroup"
}
],
"KeyName": "mykey",
"ImageId": ""
}
},
"InstanceSecurityGroup": {
"Type": "AWS::EC2::SecurityGroup",
"Properties": {
"GroupDescription": "Enable SSH access via port 22",
"SecurityGroupIngress": [
{
"IpProtocol": "tcp",
"FromPort": "22",
"ToPort": "22",
"CidrIp": "0.0.0.0/0"
}
]
}
}
}

Example YAML
Resources:
Ec2Instance:
Type: 'AWS::EC2::Instance'
Properties:
SecurityGroups:
- !Ref InstanceSecurityGroup
KeyName: mykey
ImageId: ''
InstanceSecurityGroup:
Type: 'AWS::EC2::SecurityGroup'
Properties:
GroupDescription: Enable SSH access via port 22
SecurityGroupIngress:
- IpProtocol: tcp
FromPort: '22'

API Version 2010-05-15
36

AWS CloudFormation User Guide
Resource Properties and Using Resources Together
ToPort: '22'
CidrIp: 0.0.0.0/0

The SecurityGroups property is a list of security groups, and in the previous example we have only one
item in the list. The following template has an additional item in the SecurityGroups property list.

Example JSON
{

}

"Resources": {
"Ec2Instance": {
"Type": "AWS::EC2::Instance",
"Properties": {
"SecurityGroups": [
{
"Ref": "InstanceSecurityGroup"
},
"MyExistingSecurityGroup"
],
"KeyName": "mykey",
"ImageId": "ami-7a11e213"
}
},
"InstanceSecurityGroup": {
"Type": "AWS::EC2::SecurityGroup",
"Properties": {
"GroupDescription": "Enable SSH access via port 22",
"SecurityGroupIngress": [
{
"IpProtocol": "tcp",
"FromPort": "22",
"ToPort": "22",
"CidrIp": "0.0.0.0/0"
}
]
}
}
}

Example YAML
Resources:
Ec2Instance:
Type: 'AWS::EC2::Instance'
Properties:
SecurityGroups:
- !Ref InstanceSecurityGroup
- MyExistingSecurityGroup
KeyName: mykey
ImageId: ami-7a11e213
InstanceSecurityGroup:
Type: 'AWS::EC2::SecurityGroup'
Properties:
GroupDescription: Enable SSH access via port 22
SecurityGroupIngress:
- IpProtocol: tcp
FromPort: '22'
ToPort: '22'
CidrIp: 0.0.0.0/0

API Version 2010-05-15
37

AWS CloudFormation User Guide
Resource Properties and Using Resources Together

MyExistingSecurityGroup is a string that refers to an existing EC2 security group instead of a security
group declared in a template. You use literal strings to refer to existing AWS resources.
In the example above, the KeyName property of the AWS::EC2::Instance (p. 879) is the literal string
mykey. This means that a key pair with the name mykey must exist in the region where the stack is
being created; otherwise, stack creation will fail because the key pair does not exist. The key pair you
use can vary with the region where you are creating the stack, or you may want to share the template
with someone else so that they can use it with their AWS account. If so, you can use an input parameter
so that the key pair name can be specified when the stack is created. The Ref function can refer to
input parameters that are specified at stack creation time. The following template adds a Parameters
object containing the KeyName parameter, which is used to specify the KeyName property for the
AWS::EC2::Instance resource. The parameter type is AWS::EC2::KeyPair::KeyName, which ensures
a user specifies a valid key pair name in his or her account and in the region where the stack is being
created.

Example JSON
{

}

"Parameters": {
"KeyName": {
"Description": "The EC2 Key Pair to allow SSH access to the instance",
"Type": "AWS::EC2::KeyPair::KeyName"
}
},
"Resources": {
"Ec2Instance": {
"Type": "AWS::EC2::Instance",
"Properties": {
"SecurityGroups": [
{
"Ref": "InstanceSecurityGroup"
},
"MyExistingSecurityGroup"
],
"KeyName": {
"Ref": "KeyName"
},
"ImageId": "ami-7a11e213"
}
},
"InstanceSecurityGroup": {
"Type": "AWS::EC2::SecurityGroup",
"Properties": {
"GroupDescription": "Enable SSH access via port 22",
"SecurityGroupIngress": [
{
"IpProtocol": "tcp",
"FromPort": "22",
"ToPort": "22",
"CidrIp": "0.0.0.0/0"
}
]
}
}
}

Example YAML
Parameters:
KeyName:
Description: The EC2 Key Pair to allow SSH access to the instance

API Version 2010-05-15
38

AWS CloudFormation User Guide
Resource Properties and Using Resources Together
Type: 'AWS::EC2::KeyPair::KeyName'
Resources:
Ec2Instance:
Type: 'AWS::EC2::Instance'
Properties:
SecurityGroups:
- !Ref InstanceSecurityGroup
- MyExistingSecurityGroup
KeyName: !Ref KeyName
ImageId: ami-7a11e213
InstanceSecurityGroup:
Type: 'AWS::EC2::SecurityGroup'
Properties:
GroupDescription: Enable SSH access via port 22
SecurityGroupIngress:
- IpProtocol: tcp
FromPort: '22'
ToPort: '22'
CidrIp: 0.0.0.0/0

The Ref function is handy if the parameter or the value returned for a resource is exactly what you want;
however, you may need other attributes of a resource. For example, if you want to create a CloudFront
distribution with an S3 origin, you need to specify the bucket location by using a DNS-style address.
A number of resources have additional attributes whose values you can use in your template. To get
these attributes, you use the Fn::GetAtt (p. 2285) function. The following template creates a CloudFront
distribution resource that specifies the DNS name of an S3 bucket resource using Fn::GetAtt function to
get the bucket's DomainName attribute.

Example JSON
{

"Resources": {
"myBucket": {
"Type": "AWS::S3::Bucket"
},
"myDistribution": {
"Type": "AWS::CloudFront::Distribution",
"Properties": {
"DistributionConfig": {
"Origins": [
{
"DomainName": {
"Fn::GetAtt": [
"myBucket",
"DomainName"
]
},
"Id": "myS3Origin",
"S3OriginConfig": {}
}
],
"Enabled": "true",
"DefaultCacheBehavior": {
"TargetOriginId": "myS3Origin",
"ForwardedValues": {
"QueryString": "false"
},
"ViewerProtocolPolicy": "allow-all"
}
}
}
}
}

API Version 2010-05-15
39

AWS CloudFormation User Guide
Receiving User Input Using Input Parameters
}

Example YAML
Resources:
myBucket:
Type: 'AWS::S3::Bucket'
myDistribution:
Type: 'AWS::CloudFront::Distribution'
Properties:
DistributionConfig:
Origins:
- DomainName: !GetAtt
- myBucket
- DomainName
Id: myS3Origin
S3OriginConfig: {}
Enabled: 'true'
DefaultCacheBehavior:
TargetOriginId: myS3Origin
ForwardedValues:
QueryString: 'false'
ViewerProtocolPolicy: allow-all

The Fn::GetAtt function takes two parameters, the logical name of the resource and the name of the
attribute to be retrieved. For a full list of available attributes for resources, see Fn::GetAtt (p. 2285).
You'll notice that the Fn::GetAtt function lists its two parameters in an array. For functions that take
multiple parameters, you use an array to specify their parameters.

Receiving User Input Using Input Parameters
So far, you've learned about resources and a little bit about how to use them together within a template.
You've learned how to refer to input parameters, but we haven't gone deeply into how to define the
input parameters themselves. Let's take a look at parameter declarations and how you can restrict and
validate user input.
You declare parameters in a template's Parameters object. A parameter contains a list of attributes that
define its value and constraints against its value. The only required attribute is Type, which can be String,
Number, or an AWS-specific type. You can also add a Description attribute that tells a user more about
what kind of value they should specify. The parameter's name and description appear in the Specify
Parameters page when a user uses the template in the Create Stack wizard.
The following template fragment is a Parameters object that declares the parameters used in the Specify
Parameters page above.

Example JSON
"Parameters": {
"KeyName": {
"Description" : "Name of an existing EC2 KeyPair to enable SSH access into the
WordPress web server",
"Type": "AWS::EC2::KeyPair::KeyName"
},
"WordPressUser": {
"Default": "admin",
"NoEcho": "true",
"Description" : "The WordPress database admin account user name",
"Type": "String",
"MinLength": "1",
"MaxLength": "16",

API Version 2010-05-15
40

AWS CloudFormation User Guide
Receiving User Input Using Input Parameters

}

"AllowedPattern" : "[a-zA-Z][a-zA-Z0-9]*"
},
"WebServerPort": {
"Default": "8888",
"Description" : "TCP/IP port for the WordPress web server",
"Type": "Number",
"MinValue": "1",
"MaxValue": "65535"
}

Example YAML
Parameters:
KeyName:
Description: Name of an existing EC2 KeyPair to enable SSH access into the WordPress
web server
Type: AWS::EC2::KeyPair::KeyName
WordPressUser:
Default: admin
NoEcho: true
Description: The WordPress database admin account user name
Type: String
MinLength: 1
MaxLength: 16
AllowedPattern: "[a-zA-Z][a-zA-Z0-9]*"
WebServerPort:
Default: 8888
Description: TCP/IP port for the WordPress web server
Type: Number
MinValue: 1
MaxValue: 65535

For parameters with default values, AWS CloudFormation uses the default values unless users specify
another value. If you omit the default attribute, users are required to specify a value for that parameter;
however, requiring the user to input a value does not ensure that the value is valid. To validate the value
of a parameter, you can declare constraints or specify an AWS-specific parameter type.
You'll notice that the KeyName parameter has no Default attribute and the other parameters do. For
example, the WordPress parameter has the attribute Default: admin, but the KeyName parameter
has none. Users must specify a key name value at stack creation. If they don’t, AWS CloudFormation fails
to create the stack and throws an exception: Parameters: [KeyName] must have values.
For AWS-specific parameter types, AWS CloudFormation validates input values against existing values
in the user's AWS account and in the region where he or she is creating the stack before creating
any stack resources. In the sample template, the KeyName parameter is an AWS-specific parameter
type of AWS::EC2::KeyPair::KeyName. AWS CloudFormation checks that users specify a valid
EC2 key pair name before creating the stack. Another example of an AWS-specific parameter type is
AWS::EC2::VPC::Id, which requires users to specify a valid VPC ID. In addition to upfront validation,
the AWS console shows a drop-down list of valid values for AWS-specific parameter types, such as valid
EC2 key pair names or VPC IDs, when users use the Create Stack wizard.
For the String type, you can use the following attributes to declare constraints: MinLength,
MaxLength, Default, AllowedValues, and AllowedPattern. In the example above, the
WordPressUser parameter has three constraints: the parameter value must be 1 to 16 character long
(MinLength, MaxLength) and must begin with a letter followed by any combination of letters and
numbers (AllowedPattern).
For the Number type, you can declare the following constraints: MinValue, MaxValue, Default,
and AllowedValues. A number can be an integer or a float value. In the example above, the
WebServerPort parameter must be a number between 1 and 65535 inclusive (MinValue, MaxValue).
API Version 2010-05-15
41

AWS CloudFormation User Guide
Specifying Conditional Values Using Mappings

Earlier in this section, we mentioned that parameters are a good way to specify sensitive or
implementation-specific data, such as passwords or user names, that you need to use but do not want
to embed in the template itself. For sensitive information, you can use the NoEcho attribute to prevent a
parameter value from being displayed in the console, command line tools, or API. If you set the NoEcho
attribute to true, the parameter value is returned as asterisks (*****). In the example above, the
WordPressUser parameter value is not visible to anyone viewing the stack's settings, and its value is
returned as asterisks.

Specifying Conditional Values Using Mappings
Parameters are a great way to enable users to specify unique or sensitive values for use in the properties
of stack resources; however, there may be settings that are region dependent or are somewhat complex
for users to figure out because of other conditions or dependencies. In these cases, you would want to
put some logic in the template itself so that users can specify simpler values (or none at all) to get the
results that they want. In an earlier example, we hardcoded the AMI ID for the ImageId property of our
EC2 instance. This works fine in the US-East region, where it represents the AMI that we want. However,
if the user tries to build the stack in a different region he or she will get the wrong AMI or no AMI at all.
(AMI IDs are unique to a region, so the same AMI ID in a different region may not represent any AMI or a
completely different one.)
To avoid this problem, you need a way to specify the right AMI ID based on a conditional input (in this
example, the region where the stack is created). There are two template features that can help, the
Mappings object and the AWS::Region pseudo parameter.
The AWS::Region pseudo parameter is a value that AWS CloudFormation resolves as the region where
the stack is created. Pseudo parameters are resolved by AWS CloudFormation when you create the
stack. Mappings enable you to use an input value as a condition that determines another value. Similar
to a switch statement, a mapping associates one set of values with another. Using the AWS::Region
parameter together with a mapping, you can ensure that an AMI ID appropriate to the region is specified.
The following template contains a Mappings object with a mapping named RegionMap that is used to
map an AMI ID to the appropriate region.

Example JSON
{

"Parameters": {
"KeyName": {
"Description": "Name of an existing EC2 KeyPair to enable SSH access to the
instance",
"Type": "String"
}
},
"Mappings": {
"RegionMap": {
"us-east-1": {
"AMI": "ami-76f0061f"
},
"us-west-1": {
"AMI": "ami-655a0a20"
},
"eu-west-1": {
"AMI": "ami-7fd4e10b"
},
"ap-southeast-1": {
"AMI": "ami-72621c20"
},
"ap-northeast-1": {
"AMI": "ami-8e08a38f"
}
}

API Version 2010-05-15
42

AWS CloudFormation User Guide
Specifying Conditional Values Using Mappings

}

},
"Resources": {
"Ec2Instance": {
"Type": "AWS::EC2::Instance",
"Properties": {
"KeyName": {
"Ref": "KeyName"
},
"ImageId": {
"Fn::FindInMap": [
"RegionMap",
{
"Ref": "AWS::Region"
},
"AMI"
]
},
"UserData": {
"Fn::Base64": "80"
}
}
}
}

Example YAML
Parameters:
KeyName:
Description: Name of an existing EC2 KeyPair to enable SSH access to the instance
Type: String
Mappings:
RegionMap:
us-east-1:
AMI: ami-76f0061f
us-west-1:
AMI: ami-655a0a20
eu-west-1:
AMI: ami-7fd4e10b
ap-southeast-1:
AMI: ami-72621c20
ap-northeast-1:
AMI: ami-8e08a38f
Resources:
Ec2Instance:
Type: 'AWS::EC2::Instance'
Properties:
KeyName: !Ref KeyName
ImageId: !FindInMap
- RegionMap
- !Ref 'AWS::Region'
- AMI
UserData: !Base64 '80'

In the RegionMap, each region is mapped to a name-value pair. The name-value pair is a label, and the
value to map. In the RegionMap, AMI is the label and the AMI ID is the value. To use a map to return a
value, you use the Fn::FindInMap (p. 2283) function, passing the name of the map, the value used to
find the mapped value, and the label of the mapped value you want to return. In the example above, the
ImageId property of the resource Ec2Instance uses the Fn::FindInMap function to determine its value by
specifying RegionMap as the map to use, AWS::Region as the input value to map from, and AMI as the
label to identify the value to map to. For example, if this template were used to create a stack in the uswest-1 region, ImageId would be set to ami-655a0a20.
API Version 2010-05-15
43

AWS CloudFormation User Guide
Constructed Values and Output Values

Tip

The AWS::Region pseudo parameter enables you to get the
region where the stack is created. Some resources, such as
AWS::EC2::Instance (p. 879), AWS::AutoScaling::AutoScalingGroup (p. 620), and
AWS::ElasticLoadBalancing::LoadBalancer (p. 1063), have a property that specifies availability
zones. You can use the Fn::GetAZs function (p. 2298) to get the list of all availability zones in a
region.

Constructed Values and Output Values
Parameters and mappings are an excellent way to pass or determine specific values at stack creation
time, but there can be situations where a value from a parameter or other resource attribute is only part
of the value you need. For example, in the following fragment from the WordPress template, the Fn::Join
function constructs the Target subproperty of the HealthCheck property for the ElasticLoadBalancer
resource by concatenating the WebServerPort parameter with other literal strings to form the value
needed.

Example JSON
{

"Resources": {
"ElasticLoadBalancer": {
"Type": "AWS::ElasticLoadBalancing::LoadBalancer",
"Properties": {
"AvailabilityZones": {
"Fn::GetAZs": ""
},
"Instances": [
{
"Ref": "Ec2Instance1"
},
{
"Ref": "Ec2Instance2"
}
],
"Listeners": [
{
"LoadBalancerPort": "80",
"InstancePort": {
"Ref": "WebServerPort"
},
"Protocol": "HTTP"
}
],
"HealthCheck": {
"Target": {
"Fn::Join": [
"",
[
"HTTP:",
{
"Ref": "WebServerPort"
},
"/"
]
]
},
"HealthyThreshold": "3",
"UnhealthyThreshold": "5",
"Interval": "30",
"Timeout": "5"
}

API Version 2010-05-15
44

AWS CloudFormation User Guide
Constructed Values and Output Values

}

}

}

}

Example YAML
Resources:
ElasticLoadBalancer:
Type: 'AWS::ElasticLoadBalancing::LoadBalancer'
Properties:
AvailabilityZones: !GetAZs ''
Instances:
- !Ref Ec2Instance1
- !Ref Ec2Instance2
Listeners:
- LoadBalancerPort: '80'
InstancePort: !Ref WebServerPort
Protocol: HTTP
HealthCheck:
Target: !Join
- ''
- - 'HTTP:'
- !Ref WebServerPort
- /
HealthyThreshold: '3'
UnhealthyThreshold: '5'
Interval: '30'
Timeout: '5'

The Fn::Join function takes two parameters, a delimiter that separates the values you want to
concatenate and an array of values in the order that you want them to appear. In the example above, the
Fn::Join function specifies an empty string as the delimiter and HTTP:, the value of the WebServerPort
parameter, and a / character as the values to concatenate. If WebServerPort had a value of 8888, the
Target property would be set to the following value:
HTTP:8888/

The Fn::Join function is also useful for declaring output values for the stack. The Outputs object in
the template contains declarations for the values that you want to have available after the stack is
created. An output is a convenient way to capture important information about your resources or input
parameters. For example, in the WordPress template, we declare the following Outputs object.

Example JSON
"Outputs": {
"InstallURL": {
"Value": {
"Fn::Join": [
"",
[
"http://",
{
"Fn::GetAtt": [
"ElasticLoadBalancer",
"DNSName"
]
},
"/wp-admin/install.php"
]

API Version 2010-05-15
45

AWS CloudFormation User Guide
Next Steps
]
},
"Description": "Installation URL of the WordPress website"

}

},
"WebsiteURL": {
"Value": {
"Fn::Join": [
"",
[
"http://",
{
"Fn::GetAtt": [
"ElasticLoadBalancer",
"DNSName"
]
}
]
]
}
}

Example YAML
Outputs:
InstallURL:
Value: !Join
- ''
- - 'http://'
- !GetAtt
- ElasticLoadBalancer
- DNSName
- /wp-admin/install.php
Description: Installation URL of the WordPress website
WebsiteURL:
Value: !Join
- ''
- - 'http://'
- !GetAtt
- ElasticLoadBalancer
- DNSName

Each output value has a name, a Value attribute that contains declaration of the value returned as
the output value, and optionally a description of the value. In the previous example, InstallURL is the
string returned by a Fn::Join function call that concatenates http://, the DNS name of the resource
ElasticLoadBalancer, and /wp-admin/install.php. The output value would be similar to the following:
http://mywptests-elasticl-1gb51l6sl8y5v-206169572.us-east-2.elb.amazonaws.com/wp-admin/
install.php

In the Get Started tutorial, we used this link to conveniently go to the installation page for the
WordPress blog that we created. AWS CloudFormation generates the output values after it finishes
creating the stack. You can view output values in the Outputs tab of the AWS CloudFormation console or
by using the aws cloudformation describe-stacks command.

Next Steps
We just walked through the basic parts of a template and how to use them. You learned the following
about templates:
API Version 2010-05-15
46

AWS CloudFormation User Guide
Walkthrough: Updating a Stack

• Declaring resources and their properties
• Referencing other resources with the Ref function and resource attributes using the Fn::GetAtt
function
• Using parameters to enable users to specify values at stack creation time and using constraints to
validate parameter input
• Using mappings to determine conditional values
• Using the Fn::Join function to construct values based on parameters, resource attributes, and other
strings
• Using output values based to capture information about the stack's resources.
We didn't cover two top level objects in a template: AWSTemplateFormatVersion and Description.
AWSTemplateFormatVersion is simply the version of the template format—if you don't specify it,
AWS CloudFormation will use the latest version. The Description is any valid JSON or YAML string. This
description appears in the Specify Parameters page of the Create Stack wizard. For more information,
see Format Version (p. 165) and Description (p. 166).
Of course, there are more advanced template and stack features. Here is a list of a few important ones
that you'll want to learn more about:
Optional attributes that can be used with any resource:
• DependsOn attribute (p. 2250) enables you to specify that one resource must be created after
another.
• DeletionPolicy attribute (p. 2248) enables you to specify how AWS CloudFormation should handle the
deletion of a resource.
• Metadata (p. 2254) attribute enables you to specify structured data with a resource.
AWS::CloudFormation::Stack (p. 694) enables you to nest another stack as a resource within your
template.

Walkthrough: Updating a Stack
With AWS CloudFormation, you can update the properties for resources in your existing stacks. These
changes can range from simple configuration changes, such as updating the alarm threshold on a
CloudWatch alarm, to more complex changes, such as updating the Amazon Machine Image (AMI)
running on an Amazon EC2 instance. Many of the AWS resources in a template can be updated, and we
continue to add support for more.
This section walks through a simple progression of updates of a running stack. It shows how the use
of templates makes it possible to use a version control system for the configuration of your AWS
infrastructure, just as you use version control for the software you are running. We will walk through the
following steps:
1. Create the Initial Stack (p. 53)—create a stack using a base Amazon Linux AMI, installing the
Apache Web Server and a simple PHP application using the AWS CloudFormation helper scripts.
2. Update the Application (p. 54)—update one of the files in the application and deploy the software
using AWS CloudFormation.
3. Update the Instance Type (p. 56)—change the instance type of the underlying Amazon EC2
instance.
4. Update the AMI on an Amazon EC2 instance (p. 58)—change the Amazon Machine Image (AMI) for
the Amazon EC2 instance in your stack.
API Version 2010-05-15
47

AWS CloudFormation User Guide
A Simple Application

5. Add a Key Pair to an Instance (p. 59)—add an Amazon EC2 key pair to the instance, and then
update the security group to allow SSH access to the instance.
6. Change the Stack's Resources (p. 60)—add and remove resources from the stack, converting it to an
auto-scaled, load-balanced application by updating the template.

A Simple Application
We'll begin by creating a stack that we can use throughout the rest of this section. We have provided a
simple template that launches a single instance PHP web application hosted on the Apache Web Server
and running on an Amazon Linux AMI.
The Apache Web Server, PHP, and the simple PHP application are all installed by the AWS
CloudFormation helper scripts that are installed by default on the Amazon Linux AMI. The following
template snippet shows the metadata that describes the packages and files to install, in this case the
Apache Web Server and the PHP infrastructure from the Yum repository for the Amazon Linux AMI. The
snippet also shows the Services section, which ensures that the Apache Web Server is running. In the
Properties section of the Amazon EC2 instance definition, the UserData property contains the CloudInit
script that calls cfn-init to install the packages and files.

"WebServerInstance": {
"Type" : "AWS::EC2::Instance",
"Metadata" : {
"AWS::CloudFormation::Init" : {
"config" : {
"packages" : {
"yum" : {
"httpd"
: [],
"php"
: []
}
},
"files" : {
"/var/www/html/index.php" : {
"content" : { "Fn::Join" : ["", [
"AWS CloudFormation sample PHP application';\n",
"echo '

", { "Ref" : "WelcomeMessage" }, "

';\n", "?>\n" ]]}, "mode" : "000644", "owner" : "apache", "group" : "apache" }, }, : } } "services" : { "sysvinit" : { "httpd" : { "enabled" : "true", "ensureRunning" : "true" } } } }, "Properties": { : "UserData" : { "Fn::Base64" : { "Fn::Join" : ["", [ API Version 2010-05-15 48 AWS CloudFormation User Guide A Simple Application "#!/bin/bash\n", "yum install -y aws-cfn-bootstrap\n", : } "# Install the files and packages from the metadata\n", "/opt/aws/bin/cfn-init -v ", " --stack ", { "Ref" : "AWS::StackName" }, " --resource WebServerInstance ", " --region ", { "Ref" : "AWS::Region" }, "\n", : ]]}} }, The application itself is a very simple two-line "Hello, World" example that is entirely defined within the template. For a real-world application, the files may be stored on Amazon S3, GitHub, or another repository and referenced from the template. AWS CloudFormation can download packages (such as RPMs or RubyGems), as well as reference individual files and expand .zip and .tar files to create the application artifacts on the Amazon EC2 instance. The template enables and configures the cfn-hup daemon to listen for changes to the configuration defined in the metadata for the Amazon EC2 instance. By using the cfn-hup daemon, you can update application software, such as the version of Apache or PHP, or you can update the PHP application file itself from AWS CloudFormation. The following snippet from the same Amazon EC2 resource in the template shows the pieces necessary to configure cfn-hup to call cfn-init to update the software if any changes to the metadata are detected: "WebServerInstance": { "Type" : "AWS::EC2::Instance", "Metadata" : { "AWS::CloudFormation::Init" : { "config" : { : "files" : { : "/etc/cfn/cfn-hup.conf" : { "content" : { "Fn::Join" : ["", [ "[main]\n", "stack=", { "Ref" : "AWS::StackName" }, "\n", "region=", { "Ref" : "AWS::Region" }, "\n" ]]}, "mode" : "000400", "owner" : "root", "group" : "root" }, "/etc/cfn/hooks.d/cfn-auto-reloader.conf" : { "content": { "Fn::Join" : ["", [ "[cfn-auto-reloader-hook]\n", "triggers=post.update\n", "path=Resources.WebServerInstance.Metadata.AWS::CloudFormation::Init\n", "action=/opt/aws/bin/cfn-init -s ", { "Ref" : "AWS::StackId" }, " -r WebServerInstance ", " --region ", { "Ref" : "AWS::Region" }, "\n", "runas=root\n" ]]} } API Version 2010-05-15 49 AWS CloudFormation User Guide A Simple Application }, : }, "Properties": { : "UserData" : { "Fn::Base64" : { "Fn::Join" : ["", [ : "# Start up the cfn-hup daemon to listen for changes to the Web Server metadata\n", "/opt/aws/bin/cfn-hup || error_exit 'Failed to start cfn-hup'\n", } : ]]}} }, To complete the stack, the template creates an Amazon EC2 security group. { "AWSTemplateFormatVersion" : "2010-09-09", "Description" : "AWS CloudFormation Sample Template: Sample template that can be used to test EC2 updates. **WARNING** This template creates an Amazon Ec2 Instance. You will be billed for the AWS resources used if you create a stack from this template.", "Parameters" : { "InstanceType" : { "Description" : "WebServer EC2 instance type", "Type" : "String", "Default" : "m1.small", "AllowedValues" : [ "t1.micro", "t2.micro", "t2.small", "t2.medium", "m1.small", "m1.medium", "m1.large", "m1.xlarge", "m2.xlarge", "m2.2xlarge", "m2.4xlarge", "m3.medium", "m3.large", "m3.xlarge", "m3.2xlarge", "c1.medium", "c1.xlarge", "c3.large", "c3.xlarge", "c3.2xlarge", "c3.4xlarge", "c3.8xlarge", "g2.2xlarge", "r3.large", "r3.xlarge", "r3.2xlarge", "r3.4xlarge", "r3.8xlarge", "i2.xlarge", "i2.2xlarge", "i2.4xlarge", "i2.8xlarge", "hi1.4xlarge", "hs1.8xlarge", "cr1.8xlarge", "cc2.8xlarge", "cg1.4xlarge"], "ConstraintDescription" : "must be a valid EC2 instance type." } }, "Mappings" : { "AWSInstanceType2Arch" : { "t1.micro" : { "Arch" "t2.micro" : { "Arch" "t2.small" : { "Arch" "t2.medium" : { "Arch" "m1.small" : { "Arch" "m1.medium" : { "Arch" "m1.large" : { "Arch" "m1.xlarge" : { "Arch" "m2.xlarge" : { "Arch" "m2.2xlarge" : { "Arch" "m2.4xlarge" : { "Arch" "m3.medium" : { "Arch" "m3.large" : { "Arch" "m3.xlarge" : { "Arch" "m3.2xlarge" : { "Arch" "c1.medium" : { "Arch" "c1.xlarge" : { "Arch" : : : : : : : : : : : : : : : : : "PV64" "HVM64" "HVM64" "HVM64" "PV64" "PV64" "PV64" "PV64" "PV64" "PV64" "PV64" "HVM64" "HVM64" "HVM64" "HVM64" "PV64" "PV64" }, }, }, }, }, }, }, }, }, }, }, }, }, }, }, }, }, API Version 2010-05-15 50 AWS CloudFormation User Guide A Simple Application "c3.large" "c3.xlarge" "c3.2xlarge" "c3.4xlarge" "c3.8xlarge" "g2.2xlarge" "r3.large" "r3.xlarge" "r3.2xlarge" "r3.4xlarge" "r3.8xlarge" "i2.xlarge" "i2.2xlarge" "i2.4xlarge" "i2.8xlarge" "hi1.4xlarge" "hs1.8xlarge" "cr1.8xlarge" "cc2.8xlarge" }, : : : : : : : : : : : : : : : : : : : { { { { { { { { { { { { { { { { { { { "Arch" "Arch" "Arch" "Arch" "Arch" "Arch" "Arch" "Arch" "Arch" "Arch" "Arch" "Arch" "Arch" "Arch" "Arch" "Arch" "Arch" "Arch" "Arch" : : : : : : : : : : : : : : : : : : : "AWSRegionArch2AMI" : { "us-east-1" : { "PV64" "ami-3a329952" }, "us-west-2" : { "PV64" "ami-47296a77" }, "us-west-1" : { "PV64" "ami-331b1376" }, "eu-west-1" : { "PV64" "ami-00913777" }, "ap-southeast-1" : { "PV64" "ami-fabe9aa8" }, "ap-northeast-1" : { "PV64" "ami-5dd1ff5c" }, "ap-southeast-2" : { "PV64" "ami-e98ae9d3" }, "sa-east-1" : { "PV64" "NOT_SUPPORTED" }, "cn-north-1" : { "PV64" "NOT_SUPPORTED" }, "eu-central-1" : { "PV64" "ami-b03503ad" } } }, "HVM64" "HVM64" "HVM64" "HVM64" "HVM64" "HVMG2" "HVM64" "HVM64" "HVM64" "HVM64" "HVM64" "HVM64" "HVM64" "HVM64" "HVM64" "HVM64" "HVM64" "HVM64" "HVM64" }, }, }, }, }, }, }, }, }, }, }, }, }, }, }, }, }, }, } : "ami-50842d38", "HVM64" : "ami-08842d60", "HVMG2" : : "ami-af86c69f", "HVM64" : "ami-8786c6b7", "HVMG2" : : "ami-c7a8a182", "HVM64" : "ami-cfa8a18a", "HVMG2" : : "ami-aa8f28dd", "HVM64" : "ami-748e2903", "HVMG2" : : "ami-20e1c572", "HVM64" : "ami-d6e1c584", "HVMG2" : : "ami-21072820", "HVM64" : "ami-35072834", "HVMG2" : : "ami-8b4724b1", "HVM64" : "ami-fd4724c7", "HVMG2" : : "ami-9d6cc680", "HVM64" : "ami-956cc688", "HVMG2" : : "ami-a857c591", "HVM64" : "ami-ac57c595", "HVMG2" : : "ami-a03503bd", "HVM64" : "ami-b43503a9", "HVMG2" : "Resources" : { "WebServerInstance": { "Type" : "AWS::EC2::Instance", "Metadata" : { "Comment" : "Install a simple "AWS::CloudFormation::Init" : "config" : { "packages" : { "yum" : { "httpd" : "php" : } }, PHP application", { [], [] "files" : { "/var/www/html/index.php" : { "content" : { "Fn::Join" : ["", [ "AWS CloudFormation sample PHP application';\n", API Version 2010-05-15 51 AWS CloudFormation User Guide A Simple Application "?>\n" ]]}, "mode" "owner" "group" }, : "000644", : "apache", : "apache" "/etc/cfn/cfn-hup.conf" : { "content" : { "Fn::Join" : ["", [ "[main]\n", "stack=", { "Ref" : "AWS::StackId" }, "\n", "region=", { "Ref" : "AWS::Region" }, "\n" ]]}, "mode" : "000400", "owner" : "root", "group" : "root" }, "/etc/cfn/hooks.d/cfn-auto-reloader.conf" : { "content": { "Fn::Join" : ["", [ "[cfn-auto-reloader-hook]\n", "triggers=post.update\n", "path=Resources.WebServerInstance.Metadata.AWS::CloudFormation::Init\n", "action=/opt/aws/bin/cfn-init -s ", { "Ref" : "AWS::StackId" }, " -r WebServerInstance ", " --region ", { "Ref" : "AWS::Region" }, "\n", "runas=root\n" ]]} } }, "services" : { "sysvinit" : { "httpd" : { "enabled" : "true", "ensureRunning" : "true" }, "cfn-hup" : { "enabled" : "true", "ensureRunning" : "true", "files" : ["/etc/cfn/cfn-hup.conf", "/etc/cfn/hooks.d/cfn-autoreloader.conf"]} } } } } }, "Properties": { "ImageId" : { "Fn::FindInMap" : [ "AWSRegionArch2AMI", { "Ref" : "AWS::Region" }, { "Fn::FindInMap" : [ "AWSInstanceType2Arch", { "Ref" : "InstanceType" }, "Arch" ] } ] }, "InstanceType" : { "Ref" : "InstanceType" }, "SecurityGroups" : [ {"Ref" : "WebServerSecurityGroup"} ], "UserData" : { "Fn::Base64" : { "Fn::Join" : ["", [ "#!/bin/bash -xe\n", "yum install -y aws-cfn-bootstrap\n", "# Install the files and packages from the metadata\n", "/opt/aws/bin/cfn-init -v ", " --stack ", { "Ref" : "AWS::StackName" }, " --resource WebServerInstance ", " --region ", { "Ref" : "AWS::Region" }, "\n", "# Start up the cfn-hup daemon to listen for changes to the Web Server metadata\n", "/opt/aws/bin/cfn-hup || error_exit 'Failed to start cfn-hup'\n", "# Signal the status from cfn-init\n", API Version 2010-05-15 52 AWS CloudFormation User Guide Create the Initial Stack "/opt/aws/bin/cfn-signal -e $? ", " --stack ", { "Ref" : "AWS::StackName" }, " --resource WebServerInstance ", " --region ", { "Ref" : "AWS::Region" }, "\n" ]]}} }, "CreationPolicy" : { "ResourceSignal" : { "Timeout" : "PT5M" } } }, "WebServerSecurityGroup" : { "Type" : "AWS::EC2::SecurityGroup", "Properties" : { "GroupDescription" : "Enable HTTP access via port 80", "SecurityGroupIngress" : [ {"IpProtocol" : "tcp", "FromPort" : "80", "ToPort" : "80", "CidrIp" : "0.0.0.0/0"} ] } } }, "Outputs" : { "WebsiteURL" : { "Description" : "Application URL", "Value" : { "Fn::Join" : ["", ["http://", { "Fn::GetAtt" : [ "WebServerInstance", "PublicDnsName" ]}]] } } } } This example uses a single Amazon EC2 instance, but you can use the same mechanisms on more complex solutions that make use of Elastic Load Balancers and Auto Scaling groups to manage a collection of application servers. There are, however, some special considerations for Auto Scaling groups. For more information, see Updating Auto Scaling Groups (p. 56). Create the Initial Stack For the purposes of this example, we’ll use the AWS Management Console to create an initial stack from the sample template. Warning Completing this procedure will deploy live AWS services. You will be charged the standard usage rates as long as these services are running. To create the stack from the AWS Management Console 1. 2. 3. 4. 5. 6. 7. Copy the previous template and save it locally on your system as a text file. Note the location because you'll need to use the file in a subsequent step. Log in to the AWS CloudFormation console at https://console.aws.amazon.com/cloudformation . Click Create New Stack. In the Create New Stack wizard, on the Select Template screen, type UpdateTutorial in the Name field. On the same page, select Upload a template to Amazon S3 and browse to the file that you downloaded in the first step, and then click Next. On the Specify Parameters screen, in the Instance Type box, type t1.micro. Then click Next. On the Options screen, click Next. On the Review screen, verify that all the settings are as you want them, and then click Create. API Version 2010-05-15 53 AWS CloudFormation User Guide Update the Application After the status of your stack is CREATE_COMPLETE, the output tab will display the URL of your website. If you click the value of the WebsiteURL output, you will see your new PHP application working. Update the Application Now that we have deployed the stack, let's update the application. We'll make a simple change to the text that is printed out by the application. To do so, we’ll add an echo command to the index.php file as shown in this template snippet: "WebServerInstance": { "Type" : "AWS::EC2::Instance", "Metadata" : { "AWS::CloudFormation::Init" : { "config" : { : "files" : { "/var/www/html/index.php" : { "content" : { "Fn::Join" : ["", [ "AWS CloudFormation sample PHP application';\n", "echo 'Updated version via UpdateStack';\n ", "?>\n" ]]}, "mode" : "000644", "owner" : "apache", "group" : "apache" }, : } }, Use a text editor to manually edit the template file that you saved locally. Now, we'll update the stack. To update the stack from the AWS Management Console 1. Log in to the AWS CloudFormation console, at: https://console.aws.amazon.com/cloudformation. 2. On the AWS CloudFormation dashboard, click the stack you created previously, and then click Update Stack. 3. In the Update Stack wizard, on the Select Template screen, select Upload a template to Amazon S3, select the modified template, and then click Next. 4. 5. On the Options screen, click Next. Click Next because the stack doesn't have a stack policy. All resources can be updated without an overriding policy. On the Review screen, verify that all the settings are as you want them, and then click Update. 6. If you update the stack from the AWS Management Console, you will notice that the parameters that were used to create the initial stack are prepopulated on the Parameters page of the Update Stack wizard. If you use the aws cloudformation update-stack command, be sure to type in the same values for the parameters that you used originally to create the stack. When your stack is in the UPDATE_COMPLETE state, you can click the WebsiteURL output value again to verify that the changes to your application have taken effect. By default, the cfn-hup daemon runs API Version 2010-05-15 54 AWS CloudFormation User Guide Update the Application every 15 minutes, so it may take up to 15 minutes for the application to change once the stack has been updated. To see the set of resources that were updated, go to the AWS CloudFormation console. On the Events tab, look at the stack events. In this particular case, the metadata for the Amazon EC2 instance WebServerInstance was updated, which caused AWS CloudFormation to also reevaluate the other resources (WebServerSecurityGroup) to ensure that there were no other changes. None of the other stack resources were modified. AWS CloudFormation will update only those resources in the stack that are affected by any changes to the stack. Such changes can be direct, such as property or metadata changes, or they can be due to dependencies or data flows through Ref, GetAtt, or other intrinsic template functions. This simple update illustrates the process; however, you can make much more complex changes to the files and packages that are deployed to your Amazon EC2 instances. For example, you might decide that you need to add MySQL to the instance, along with PHP support for MySQL. To do so, simply add the additional packages and files along with any additional services to the configuration and then update the stack to deploy the changes. In the following template snippet, the changes are highlighted in red: "WebServerInstance": { "Type" : "AWS::EC2::Instance", "Metadata" : { "Comment" : "Install a simple "AWS::CloudFormation::Init" : "config" : { "packages" : { "yum" : { "httpd" : "php" : "php-mysql" : "mysql-server" : "mysql-libs" : "mysql" : } }, PHP application", { [], [], [], [], [], [] : "services" : { "sysvinit" : { "httpd" : { "enabled" : "true", "ensureRunning" : "true" }, "cfn-hup" : { "enabled" : "true", "ensureRunning" : "true", "files" : ["/etc/cfn/cfn-hup.conf", "/etc/cfn/hooks.d/cfn-autoreloader.conf"]}, "mysqld" : { "enabled" : "true", "ensureRunning" : "true" } } } } } }, } "Properties": { : } You can update the CloudFormation metadata to update to new versions of the packages used by the application. In the previous examples, the version property for each package is empty, indicating that cfn-init should install the latest version of the package. "packages" : { "yum" : { API Version 2010-05-15 55 AWS CloudFormation User Guide Changing Resource Properties } "httpd" "php" : [], : [] You can optionally specify a version string for a package. If you change the version string in subsequent update stack calls, the new version of the package will be deployed. Here's an example of using version numbers for RubyGems packages. Any package that supports versioning can have specific versions. "packages" : { "rubygems" : { "mysql" "rubygems-update" "rake" "rails" } } : : : : [], ["1.6.2"], ["0.8.7"], ["2.3.11"] Updating Auto Scaling Groups If you are using Auto Scaling groups in your template, as opposed to Amazon EC2 instance resources, updating the application will work in exactly the same way; however, AWS CloudFormation does not provide any synchronization or serialization across the Amazon EC2 instances in an Auto Scaling group. The cfn-hup daemon on each host will run independently and update the application on its own schedule. When you use cfn-hup to update the on-instance configuration, each instance will run the cfnhup hooks on its own schedule; there is no coordination between the instances in the stack. You should consider the following: • If the cfn-hup changes run on all Amazon EC2 instances in the Auto Scaling group at the same time, your service might be unavailable during the update. • If the cfn-hup changes run at different times, old and new versions of the software may be running at the same. To avoid these issues, consider forcing a rolling update on your instances in the Auto Scaling group. For more information, see UpdatePolicy (p. 2255). Changing Resource Properties With AWS CloudFormation, you can change the properties of an existing resource in the stack. The following sections describe various updates that solve specific problems; however, any property of any resource that supports updating in the stack can be modified as necessary. Update the Instance Type The stack we have built so far uses a t1.micro Amazon EC2 instance. Let's suppose that your newly created website is getting more traffic than a t1.micro instance can handle, and now you want to move to an m1.small Amazon EC2 instance type. If the architecture of the instance type changes, the instance will be created with a different AMI. If you check out the mappings in the template, you will see that both the t1.micro and m1.small are the same architectures and use the same Amazon Linux AMIs. "Mappings" : { "AWSInstanceType2Arch" : { "t1.micro" : { "Arch" "t2.micro" : { "Arch" "t2.small" : { "Arch" "t2.medium" : { "Arch" "m1.small" : { "Arch" : : : : : "PV64" "HVM64" "HVM64" "HVM64" "PV64" }, }, }, }, }, API Version 2010-05-15 56 AWS CloudFormation User Guide Changing Resource Properties "m1.medium" "m1.large" "m1.xlarge" "m2.xlarge" "m2.2xlarge" "m2.4xlarge" "m3.medium" "m3.large" "m3.xlarge" "m3.2xlarge" "c1.medium" "c1.xlarge" "c3.large" "c3.xlarge" "c3.2xlarge" "c3.4xlarge" "c3.8xlarge" "g2.2xlarge" "r3.large" "r3.xlarge" "r3.2xlarge" "r3.4xlarge" "r3.8xlarge" "i2.xlarge" "i2.2xlarge" "i2.4xlarge" "i2.8xlarge" "hi1.4xlarge" "hs1.8xlarge" "cr1.8xlarge" "cc2.8xlarge" }, : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : { { { { { { { { { { { { { { { { { { { { { { { { { { { { { { { "Arch" "Arch" "Arch" "Arch" "Arch" "Arch" "Arch" "Arch" "Arch" "Arch" "Arch" "Arch" "Arch" "Arch" "Arch" "Arch" "Arch" "Arch" "Arch" "Arch" "Arch" "Arch" "Arch" "Arch" "Arch" "Arch" "Arch" "Arch" "Arch" "Arch" "Arch" : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : "AWSRegionArch2AMI" : { "us-east-1" : { "PV64" "ami-3a329952" }, "us-west-2" : { "PV64" "ami-47296a77" }, "us-west-1" : { "PV64" "ami-331b1376" }, "eu-west-1" : { "PV64" "ami-00913777" }, "ap-southeast-1" : { "PV64" "ami-fabe9aa8" }, "ap-northeast-1" : { "PV64" "ami-5dd1ff5c" }, "ap-southeast-2" : { "PV64" "ami-e98ae9d3" }, "sa-east-1" : { "PV64" "NOT_SUPPORTED" }, "cn-north-1" : { "PV64" "NOT_SUPPORTED" }, "eu-central-1" : { "PV64" "ami-b03503ad" } } } "PV64" "PV64" "PV64" "PV64" "PV64" "PV64" "HVM64" "HVM64" "HVM64" "HVM64" "PV64" "PV64" "HVM64" "HVM64" "HVM64" "HVM64" "HVM64" "HVMG2" "HVM64" "HVM64" "HVM64" "HVM64" "HVM64" "HVM64" "HVM64" "HVM64" "HVM64" "HVM64" "HVM64" "HVM64" "HVM64" }, }, }, }, }, }, }, }, }, }, }, }, }, }, }, }, }, }, }, }, }, }, }, }, }, }, }, }, }, }, } : "ami-50842d38", "HVM64" : "ami-08842d60", "HVMG2" : : "ami-af86c69f", "HVM64" : "ami-8786c6b7", "HVMG2" : : "ami-c7a8a182", "HVM64" : "ami-cfa8a18a", "HVMG2" : : "ami-aa8f28dd", "HVM64" : "ami-748e2903", "HVMG2" : : "ami-20e1c572", "HVM64" : "ami-d6e1c584", "HVMG2" : : "ami-21072820", "HVM64" : "ami-35072834", "HVMG2" : : "ami-8b4724b1", "HVM64" : "ami-fd4724c7", "HVMG2" : : "ami-9d6cc680", "HVM64" : "ami-956cc688", "HVMG2" : : "ami-a857c591", "HVM64" : "ami-ac57c595", "HVMG2" : : "ami-a03503bd", "HVM64" : "ami-b43503a9", "HVMG2" : Let's use the template that we modified in the previous section to change the instance type. Because InstanceType was an input parameter to the template, we don't need to modify the template; we can simply change the value of the parameter in the Stack Update wizard, on the Specify Parameters page. To update the stack from the AWS Management Console 1. Log in to the AWS CloudFormation console at https://console.aws.amazon.com/cloudformation. API Version 2010-05-15 57 AWS CloudFormation User Guide Changing Resource Properties 2. On the AWS CloudFormation dashboard, click the stack you created previously, and then click Update Stack. 3. In the Update Stack wizard, on the Select Template screen, select Use current template, and then click Next. The Specify Details page appears with the parameters that were used to create the initial stack are pre-populated in the Specify Parameters section. 4. Change the value of the InstanceType text box from t1.micro to m1.small. Then, click Next. 5. On the Options screen, click Next. 6. Click Next because the stack doesn't have a stack policy. All resources can be updated without an overriding policy. 7. On the Review screen, verify that all the settings are as you want them, and then click Update. You can dynamically change the instance type of an EBS-backed Amazon EC2 instance by starting and stopping the instance. AWS CloudFormation tries to optimize the change by updating the instance type and restarting the instance, so the instance ID does not change. When the instance is restarted, however, the public IP address of the instance does change. To ensure that the Elastic IP address is bound correctly after the change, AWS CloudFormation will also update the Elastic IP address. You can see the changes in the AWS CloudFormation console on the Events tab. To check the instance type from the AWS Management Console, open the Amazon EC2 console, and locate your instance there. Update the AMI on an Amazon EC2 instance Now let's look at how we might change the Amazon Machine Image (AMI) running on the instance. We will trigger the AMI change by updating the stack to use a new Amazon EC2 instance type, such as t2.medium, which is an HVM64 instance type. As in the previous section, we’ll use our existing template to change the instance type used by our example stack. In the Stack Update wizard, on the Specify Parameters page, change the value of the Instance Type. In this case, we cannot simply start and stop the instance to modify the AMI; AWS CloudFormation considers this a change to an immutable property of the resource. In order to make a change to an immutable property, AWS CloudFormation must launch a replacement resource, in this case a new Amazon EC2 instance running the new AMI. After the new instance is running, AWS CloudFormation updates the other resources in the stack to point to the new resource. When all new resources are created, the old resource is deleted, a process known as UPDATE_CLEANUP. This time, you will notice that the instance ID and application URL of the instance in the stack has changed as a result of the update. The events in the Event table contain a description "Requested update has a change to an immutable property and hence creating a new physical resource" to indicate that a resource was replaced. If you have application code written into the AMI that you want to update, you can use the same stack update mechanism to update the AMI to load your new application. To update the AMI for an instance on your stack 1. Create your new AMIs containing your application or operating system changes. For more information, go to Creating Your Own AMIs in the Amazon EC2 User Guide for Linux Instances. 2. Update your template to incorporate the new AMI IDs. 3. Update the stack, either from the AWS Management Console as explained in Update the Application (p. 54) or by using the AWS command aws cloudformation update-stack. API Version 2010-05-15 58 AWS CloudFormation User Guide Adding Resource Properties When you update the stack, AWS CloudFormation detects that the AMI ID has changed, and then it triggers a stack update in the same way as we triggered the one above. Update the Amazon EC2 Launch Configuration for an Auto Scaling Group If you are using Auto Scaling groups rather than Amazon EC2 instances, the process of updating the running instances is a little different. With Auto Scaling resources, the configuration of the Amazon EC2 instances, such as the instance type or the AMI ID is encapsulated in the Auto Scaling launch configuration. You can make changes to the launch configuration in the same way as we made changes to the Amazon EC2 instance resources in the previous sections. However, changing the launch configuration does not impact any of the running Amazon EC2 instances in the Auto Scaling group. An updated launch configuration applies only to new instances that are created after the update. If you want to propagate the change to your launch configuration across all the instances in your Auto Scaling group, you can use an update attribute. For more information, see UpdatePolicy (p. 2255). Adding Resource Properties So far, we've looked at changing existing properties of a resource in a template. You can also add properties that were not originally specified in the template. To illustrate that, we’ll add an Amazon EC2 key pair to an existing EC2 instance and then open up port 22 in the Amazon EC2 Security Group so that you can use Secure Shell (SSH) to access the instance. Add a Key Pair to an Instance To add SSH access to an existing Amazon EC2 instance 1. Add two additional parameters to the template to pass in the name of an existing Amazon EC2 key pair and SSH location. "Parameters" : { "KeyName" : { "Description" : "Name of an existing Amazon EC2 key pair for SSH access", "Type": "AWS::EC2::KeyPair::KeyName" }, "SSHLocation" : { "Description" : " The IP address range that can be used to SSH to the EC2 instances", "Type": "String", "MinLength": "9", "MaxLength": "18", "Default": "0.0.0.0/0", "AllowedPattern": "(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})/(\\d{1,2})", "ConstraintDescription": "must be a valid IP CIDR range of the form x.x.x.x/x." } : }, 2. Add the KeyName property to the Amazon EC2 instance. "WebServerInstance": { "Type" : "AWS::EC2::Instance", : "Properties": { : "KeyName" : { "Ref" : "KeyName" }, : API Version 2010-05-15 59 AWS CloudFormation User Guide Change the Stack's Resources } }, 3. Add port 22 and the SSH location to the ingress rules for the Amazon EC2 security group. "WebServerSecurityGroup" : { "Type" : "AWS::EC2::SecurityGroup", "Properties" : { "GroupDescription" : "Enable HTTP and SSH", "SecurityGroupIngress" : [ {"IpProtocol" : "tcp", "FromPort" : "22", "ToPort" : "22", "CidrIp" : { "Ref" : "SSHLocation"}}, {"IpProtocol" : "tcp", "FromPort" : "80", "ToPort" : "80", "CidrIp" : "0.0.0.0/0"} ] } }, 4. Update the stack, either from the AWS Management Console as explained in Update the Application (p. 54) or by using the AWS command aws cloudformation update-stack. Change the Stack's Resources Since application needs can change over time, AWS CloudFormation allows you to change the set of resources that make up the stack. To demonstrate, we’ll take the single instance application from Adding Resource Properties (p. 59) and convert it to an auto-scaled, load-balanced application by updating the stack. This will create a simple, single instance PHP application using an Elastic IP address. We'll now turn the application into a highly available, auto-scaled, load balanced application by changing its resources during an update. 1. Add an Elastic Load Balancer resource. "ElasticLoadBalancer" : { "Type" : "AWS::ElasticLoadBalancing::LoadBalancer", "Properties" : { "CrossZone" : "true", "AvailabilityZones" : { "Fn::GetAZs" : "" }, "LBCookieStickinessPolicy" : [ { "PolicyName" : "CookieBasedPolicy", "CookieExpirationPeriod" : "30" } ], "Listeners" : [ { "LoadBalancerPort" : "80", "InstancePort" : "80", "Protocol" : "HTTP", "PolicyNames" : [ "CookieBasedPolicy" ] } ], "HealthCheck" : { "Target" : "HTTP:80/", "HealthyThreshold" : "2", "UnhealthyThreshold" : "5", "Interval" : "10", "Timeout" : "5" } } } 2. Convert the EC2 instance in the template into an Auto Scaling Launch Configuration. The properties are identical, so we only need to change the type name from: API Version 2010-05-15 60 AWS CloudFormation User Guide Change the Stack's Resources "WebServerInstance": { "Type" : "AWS::EC2::Instance", to: "LaunchConfig": { "Type" : "AWS::AutoScaling::LaunchConfiguration", For clarity in the template, we changed the name of the resource from WebServerInstance to LaunchConfig, so you’ll need to update the resource name referenced by cfn-init and cfn-hup (just search for WebServerInstance and replace it with LaunchConfig, except for cfn-signal). For cfnsignal, you'll need to signal the Auto Scaling group (WebServerGroup) not the instance, as shown in the following snippet: "# Signal the status from cfn-init\n", "/opt/aws/bin/cfn-signal -e $? ", " --stack ", { "Ref" : "AWS::StackName" }, " --resource WebServerGroup ", " --region ", { "Ref" : "AWS::Region" }, "\n" 3. Add an Auto Scaling Group resource. "WebServerGroup" : { "Type" : "AWS::AutoScaling::AutoScalingGroup", "Properties" : { "AvailabilityZones" : { "Fn::GetAZs" : "" }, "LaunchConfigurationName" : { "Ref" : "LaunchConfig" }, "MinSize" : "1", "DesiredCapacity" : "1", "MaxSize" : "5", "LoadBalancerNames" : [ { "Ref" : "ElasticLoadBalancer" } ] }, "CreationPolicy" : { "ResourceSignal" : { "Timeout" : "PT15M" } }, "UpdatePolicy": { "AutoScalingRollingUpdate": { "MinInstancesInService": "1", "MaxBatchSize": "1", "PauseTime" : "PT15M", "WaitOnResourceSignals": "true" } } } 4. Update the Security Group definition to lock down the traffic to the instances from the load balancer. "WebServerSecurityGroup" : { "Type" : "AWS::EC2::SecurityGroup", "Properties" : { "GroupDescription" : "Enable HTTP access via port 80 locked down to the ELB and SSH access", "SecurityGroupIngress" : [ API Version 2010-05-15 61 AWS CloudFormation User Guide Change the Stack's Resources {"IpProtocol" : "tcp", "FromPort" : "80", "ToPort" : "80", "SourceSecurityGroupOwnerId" : {"Fn::GetAtt" : ["ElasticLoadBalancer", "SourceSecurityGroup.OwnerAlias"]}, "SourceSecurityGroupName" : {"Fn::GetAtt" : ["ElasticLoadBalancer", "SourceSecurityGroup.GroupName"]}}, {"IpProtocol" : "tcp", "FromPort" : "22", "ToPort" : "22", "CidrIp" : { "Ref" : "SSHLocation"}} ] } } 5. Update the Outputs to return the DNS Name of the Elastic Load Balancer as the location of the application from: "WebsiteURL" : { "Value" : { "Fn::Join" : ["", ["http://", { "Fn::GetAtt" : [ "WebServerInstance", "PublicDnsName" ]}]]}, "Description" : "Application URL" } to: "WebsiteURL" : { "Value" : { "Fn::Join" : ["", ["http://", { "Fn::GetAtt" : [ "ElasticLoadBalancer", "DNSName" ]}]]}, "Description" : "Application URL" } For reference, the follow sample shows the complete template. If you use this template to update the stack, you will convert your simple, single instance application into a highly available, multi-AZ, autoscaled and load balanced application. Only the resources that need to be updated will be altered, so had there been any data stores for this application, the data would have remained intact. Now, you can use AWS CloudFormation to grow or enhance your stacks as your requirements change. { "AWSTemplateFormatVersion" : "2010-09-09", "Description" : "AWS CloudFormation Sample Template: Sample template that can be used to test EC2 updates. **WARNING** This template creates an Amazon Ec2 Instance. You will be billed for the AWS resources used if you create a stack from this template.", "Parameters" : { "KeyName": { "Description" : "Name of an existing EC2 KeyPair to enable SSH access to the instance", "Type": "AWS::EC2::KeyPair::KeyName", "ConstraintDescription" : "must be the name of an existing EC2 KeyPair." }, "SSHLocation" : { "Description" : " The IP address range that can be used to SSH to the EC2 instances", "Type": "String", "MinLength": "9", "MaxLength": "18", "Default": "0.0.0.0/0", "AllowedPattern": "(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})/(\\d{1,2})", "ConstraintDescription": "must be a valid IP CIDR range of the form x.x.x.x/x." }, API Version 2010-05-15 62 AWS CloudFormation User Guide Change the Stack's Resources "InstanceType" : { "Description" : "WebServer EC2 instance type", "Type" : "String", "Default" : "m1.small", "AllowedValues" : [ "t1.micro", "t2.micro", "t2.small", "t2.medium", "m1.small", "m1.medium", "m1.large", "m1.xlarge", "m2.xlarge", "m2.2xlarge", "m2.4xlarge", "m3.medium", "m3.large", "m3.xlarge", "m3.2xlarge", "c1.medium", "c1.xlarge", "c3.large", "c3.xlarge", "c3.2xlarge", "c3.4xlarge", "c3.8xlarge", "g2.2xlarge", "r3.large", "r3.xlarge", "r3.2xlarge", "r3.4xlarge", "r3.8xlarge", "i2.xlarge", "i2.2xlarge", "i2.4xlarge", "i2.8xlarge", "hi1.4xlarge", "hs1.8xlarge", "cr1.8xlarge", "cc2.8xlarge", "cg1.4xlarge"], "ConstraintDescription" : "must be a valid EC2 instance type." } }, "Mappings" : { "AWSInstanceType2Arch" : { "t1.micro" : { "Arch" "t2.micro" : { "Arch" "t2.small" : { "Arch" "t2.medium" : { "Arch" "m1.small" : { "Arch" "m1.medium" : { "Arch" "m1.large" : { "Arch" "m1.xlarge" : { "Arch" "m2.xlarge" : { "Arch" "m2.2xlarge" : { "Arch" "m2.4xlarge" : { "Arch" "m3.medium" : { "Arch" "m3.large" : { "Arch" "m3.xlarge" : { "Arch" "m3.2xlarge" : { "Arch" "c1.medium" : { "Arch" "c1.xlarge" : { "Arch" "c3.large" : { "Arch" "c3.xlarge" : { "Arch" "c3.2xlarge" : { "Arch" "c3.4xlarge" : { "Arch" "c3.8xlarge" : { "Arch" "g2.2xlarge" : { "Arch" "r3.large" : { "Arch" "r3.xlarge" : { "Arch" "r3.2xlarge" : { "Arch" "r3.4xlarge" : { "Arch" "r3.8xlarge" : { "Arch" "i2.xlarge" : { "Arch" "i2.2xlarge" : { "Arch" "i2.4xlarge" : { "Arch" "i2.8xlarge" : { "Arch" "hi1.4xlarge" : { "Arch" "hs1.8xlarge" : { "Arch" "cr1.8xlarge" : { "Arch" "cc2.8xlarge" : { "Arch" }, : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : "AWSRegionArch2AMI" : { "us-east-1" : { "PV64" "ami-3a329952" }, "us-west-2" : { "PV64" "ami-47296a77" }, "us-west-1" : { "PV64" "ami-331b1376" }, "eu-west-1" : { "PV64" "ami-00913777" }, "PV64" "HVM64" "HVM64" "HVM64" "PV64" "PV64" "PV64" "PV64" "PV64" "PV64" "PV64" "HVM64" "HVM64" "HVM64" "HVM64" "PV64" "PV64" "HVM64" "HVM64" "HVM64" "HVM64" "HVM64" "HVMG2" "HVM64" "HVM64" "HVM64" "HVM64" "HVM64" "HVM64" "HVM64" "HVM64" "HVM64" "HVM64" "HVM64" "HVM64" "HVM64" }, }, }, }, }, }, }, }, }, }, }, }, }, }, }, }, }, }, }, }, }, }, }, }, }, }, }, }, }, }, }, }, }, }, }, } : "ami-50842d38", "HVM64" : "ami-08842d60", "HVMG2" : : "ami-af86c69f", "HVM64" : "ami-8786c6b7", "HVMG2" : : "ami-c7a8a182", "HVM64" : "ami-cfa8a18a", "HVMG2" : : "ami-aa8f28dd", "HVM64" : "ami-748e2903", "HVMG2" : API Version 2010-05-15 63 AWS CloudFormation User Guide Change the Stack's Resources "ap-southeast-1" "ami-fabe9aa8" }, "ap-northeast-1" "ami-5dd1ff5c" }, "ap-southeast-2" "ami-e98ae9d3" }, "sa-east-1" "NOT_SUPPORTED" }, "cn-north-1" "NOT_SUPPORTED" }, "eu-central-1" "ami-b03503ad" } } }, : { "PV64" : "ami-20e1c572", "HVM64" : "ami-d6e1c584", "HVMG2" : : { "PV64" : "ami-21072820", "HVM64" : "ami-35072834", "HVMG2" : : { "PV64" : "ami-8b4724b1", "HVM64" : "ami-fd4724c7", "HVMG2" : : { "PV64" : "ami-9d6cc680", "HVM64" : "ami-956cc688", "HVMG2" : : { "PV64" : "ami-a857c591", "HVM64" : "ami-ac57c595", "HVMG2" : : { "PV64" : "ami-a03503bd", "HVM64" : "ami-b43503a9", "HVMG2" : "Resources" : { "ElasticLoadBalancer" : { "Type" : "AWS::ElasticLoadBalancing::LoadBalancer", "Properties" : { "CrossZone" : "true", "AvailabilityZones" : { "Fn::GetAZs" : "" }, "LBCookieStickinessPolicy" : [ { "PolicyName" : "CookieBasedPolicy", "CookieExpirationPeriod" : "30" } ], "Listeners" : [ { "LoadBalancerPort" : "80", "InstancePort" : "80", "Protocol" : "HTTP", "PolicyNames" : [ "CookieBasedPolicy" ] } ], "HealthCheck" : { "Target" : "HTTP:80/", "HealthyThreshold" : "2", "UnhealthyThreshold" : "5", "Interval" : "10", "Timeout" : "5" } } }, "WebServerGroup" : { "Type" : "AWS::AutoScaling::AutoScalingGroup", "Properties" : { "AvailabilityZones" : { "Fn::GetAZs" : "" }, "LaunchConfigurationName" : { "Ref" : "LaunchConfig" }, "MinSize" : "1", "DesiredCapacity" : "1", "MaxSize" : "5", "LoadBalancerNames" : [ { "Ref" : "ElasticLoadBalancer" } ] }, "CreationPolicy" : { "ResourceSignal" : { "Timeout" : "PT15M" } }, "UpdatePolicy": { "AutoScalingRollingUpdate": { "MinInstancesInService": "1", "MaxBatchSize": "1", "PauseTime" : "PT15M", "WaitOnResourceSignals": "true" } } }, API Version 2010-05-15 64 AWS CloudFormation User Guide Change the Stack's Resources "LaunchConfig": { "Type" : "AWS::AutoScaling::LaunchConfiguration", "Metadata" : { "Comment" : "Install a simple PHP application", "AWS::CloudFormation::Init" : { "config" : { "packages" : { "yum" : { "httpd" : [], "php" : [] } }, "files" : { "/var/www/html/index.php" : { "content" : { "Fn::Join" : ["", [ "AWS CloudFormation sample PHP application';\n", "echo 'Updated version via UpdateStack';\n ", "?>\n" ]]}, "mode" : "000644", "owner" : "apache", "group" : "apache" }, "/etc/cfn/cfn-hup.conf" : { "content" : { "Fn::Join" : ["", [ "[main]\n", "stack=", { "Ref" : "AWS::StackId" }, "\n", "region=", { "Ref" : "AWS::Region" }, "\n" ]]}, "mode" : "000400", "owner" : "root", "group" : "root" }, "/etc/cfn/hooks.d/cfn-auto-reloader.conf" : { "content": { "Fn::Join" : ["", [ "[cfn-auto-reloader-hook]\n", "triggers=post.update\n", "path=Resources.LaunchConfig.Metadata.AWS::CloudFormation::Init\n", "action=/opt/aws/bin/cfn-init -s ", { "Ref" : "AWS::StackId" }, " -r LaunchConfig ", " --region ", { "Ref" : "AWS::Region" }, "\n", "runas=root\n" ]]} } }, "services" : { "sysvinit" : { "httpd" : { "enabled" : "true", "ensureRunning" : "true" }, "cfn-hup" : { "enabled" : "true", "ensureRunning" : "true", "files" : ["/etc/cfn/cfn-hup.conf", "/etc/cfn/hooks.d/cfn-autoreloader.conf"]} } } } } }, API Version 2010-05-15 65 AWS CloudFormation User Guide Availability and Impact Considerations "Properties": { "ImageId" : { "Fn::FindInMap" : [ "AWSRegionArch2AMI", { "Ref" : "AWS::Region" }, { "Fn::FindInMap" : [ "AWSInstanceType2Arch", { "Ref" : "InstanceType" }, "Arch" ] } ] }, "InstanceType" : { "Ref" : "InstanceType" }, "KeyName" : { "Ref" : "KeyName" }, "SecurityGroups" : [ {"Ref" : "WebServerSecurityGroup"} ], "UserData" : { "Fn::Base64" : { "Fn::Join" : ["", [ "#!/bin/bash -xe\n", "yum install -y aws-cfn-bootstrap\n", "# Install the files and packages from the metadata\n", "/opt/aws/bin/cfn-init -v ", " --stack ", { "Ref" : "AWS::StackName" }, " --resource LaunchConfig ", " --region ", { "Ref" : "AWS::Region" }, "\n", "# Start up the cfn-hup daemon to listen for changes to the Web Server metadata\n", "/opt/aws/bin/cfn-hup || error_exit 'Failed to start cfn-hup'\n", } ]]}} "# Signal the status from cfn-init\n", "/opt/aws/bin/cfn-signal -e $? ", " --stack ", { "Ref" : "AWS::StackName" }, " --resource WebServerGroup ", " --region ", { "Ref" : "AWS::Region" }, "\n" }, "WebServerSecurityGroup" : { "Type" : "AWS::EC2::SecurityGroup", "Properties" : { "GroupDescription" : "Enable HTTP access via port 80 locked down to the ELB and SSH access", "SecurityGroupIngress" : [ {"IpProtocol" : "tcp", "FromPort" : "80", "ToPort" : "80", "SourceSecurityGroupOwnerId" : {"Fn::GetAtt" : ["ElasticLoadBalancer", "SourceSecurityGroup.OwnerAlias"]},"SourceSecurityGroupName" : {"Fn::GetAtt" : ["ElasticLoadBalancer", "SourceSecurityGroup.GroupName"]}}, {"IpProtocol" : "tcp", "FromPort" : "22", "ToPort" : "22", "CidrIp" : { "Ref" : "SSHLocation"}} ] } } }, "Outputs" : { "WebsiteURL" : { "Description" : "Application URL", "Value" : { "Fn::Join" : ["", ["http://", { "Fn::GetAtt" : [ "ElasticLoadBalancer", "DNSName" ]}]] } } } } Availability and Impact Considerations Different properties have different impacts on the resources in the stack. You can use AWS CloudFormation to update any property; however, before you make any changes, you should consider these questions: API Version 2010-05-15 66 AWS CloudFormation User Guide Related Resources 1. How does the update affect the resource itself? For example, updating an alarm threshold will render the alarm inactive during the update. As we have seen, changing the instance type requires that the instance be stopped and restarted. AWS CloudFormation uses the Update or Modify actions for the underlying resources to make changes to resources. To understand the impact of updates, you should check the documentation for the specific resources. 2. Is the change mutable or immutable? Some changes to resource properties, such as changing the AMI on an Amazon EC2 instance, are not supported by the underlying services. In the case of mutable changes, AWS CloudFormation will use the Update or Modify type APIs for the underlying resources. For immutable property changes, AWS CloudFormation will create new resources with the updated properties and then link them to the stack before deleting the old resources. Although AWS CloudFormation tries to reduce the down time of the stack resources, replacing a resource is a multistep process, and it will take time. During stack reconfiguration, your application will not be fully operational. For example, it may not be able to serve requests or access a database. Related Resources For more information about using AWS CloudFormation to start applications and on integrating with other configuration and deployment services such as Puppet and Opscode Chef, see the following whitepapers: • Bootstrapping Applications via AWS CloudFormation • Integrating AWS CloudFormation with Opscode Chef • Integrating AWS CloudFormation with Puppet The template used throughout this section is a "Hello, World" PHP application. The template library also has an Amazon ElastiCache sample template that shows how to integrate a PHP application with ElasticCache using cfn-hup and cfn-init to respond to changes in the Amazon ElastiCache Cache Cluster configuration, all of which can be performed by Update Stack. API Version 2010-05-15 67 AWS CloudFormation User Guide Organize Your Stacks By Lifecycle and Ownership AWS CloudFormation Best Practices Best practices are recommendations that can help you use AWS CloudFormation more effectively and securely throughout its entire workflow. Learn how to plan and organize your stacks, create templates that describe your resources and the software applications that run on them, and manage your stacks and their resources. The following best practices are based on real-world experience from current AWS CloudFormation customers. Planning and organizing • Organize Your Stacks By Lifecycle and Ownership (p. 68) • Use Cross-Stack References to Export Shared Resources (p. 69) • Use IAM to Control Access (p. 69) • Reuse Templates to Replicate Stacks in Multiple Environments (p. 70) • Verify Quotas for All Resource Types (p. 69) • Use Nested Stacks to Reuse Common Template Patterns (p. 70) Creating templates • Do Not Embed Credentials in Your Templates (p. 70) • Use AWS-Specific Parameter Types (p. 70) • Use Parameter Constraints (p. 71) • Use AWS::CloudFormation::Init to Deploy Software Applications on Amazon EC2 Instances (p. 71) • Use the Latest Helper Scripts (p. 71) • Validate Templates Before Using Them (p. 71) Managing stacks • Manage All Stack Resources Through AWS CloudFormation (p. 72) • Create Change Sets Before Updating Your Stacks (p. 72) • Use Stack Policies (p. 72) • Use AWS CloudTrail to Log AWS CloudFormation Calls (p. 72) • Use Code Reviews and Revision Controls to Manage Your Templates (p. 73) • Update Your Amazon EC2 Linux Instances Regularly (p. 73) Organize Your Stacks By Lifecycle and Ownership Use the lifecycle and ownership of your AWS resources to help you decide what resources should go in each stack. Normally, you might put all your resources in one stack, but as your stack grows in scale and broadens in scope, managing a single stack can be cumbersome and time consuming. By grouping resources with common lifecycles and ownership, owners can make changes to their set of resources by using their own process and schedule without affecting other resources. For example, imagine a team of developers and engineers who own a website that is hosted on autoscaling instances behind a load balancer. Because the website has its own lifecycle and is maintained by the website team, you can create a stack for the website and its resources. Now imagine that the website also uses back-end databases, where the databases are in a separate stack that are owned and maintained by database administrators. Whenever the website team or database team needs to update API Version 2010-05-15 68 AWS CloudFormation User Guide Use Cross-Stack References to Export Shared Resources their resources, they can do so without affecting each other's stack. If all resources were in a single stack, coordinating and communicating updates can be difficult. For additional guidance about organizing your stacks, you can use two common frameworks: a multilayered architecture and service-oriented architecture (SOA). A layered architecture organizes stacks into multiple horizontal layers that build on top of one another, where each layer has a dependency on the layer directly below it. You can have one or more stacks in each layer, but within each layer, your stacks should have AWS resources with similar lifecycles and ownership. With a service-oriented architecture, you can organize big business problems into manageable parts. Each of these parts is a service that has a clearly defined purpose and represents a self-contained unit of functionality. You can map these services to a stack, where each stack has its own lifecycle and owners. All of these services (stacks) can be wired together so that they can interact with one another. Use Cross-Stack References to Export Shared Resources When you organize your AWS resources based on lifecycle and ownership, you might want to build a stack that uses resources that are in another stack. You can hard-code values or use input parameters to pass resource names and IDs. However, these methods can make templates difficult to reuse or can increase the overhead to get a stack running. Instead, use cross-stack references to export resources from a stack so that other stacks can use them. Stacks can use the exported resources by calling them using the Fn::ImportValue function. For example, you might have a network stack that includes a VPC, a security group, and a subnet. You want all public web applications to use these resources. By exporting the resources, you allow all stacks with public web applications to use them. For more information, see Walkthrough: Refer to Resource Outputs in Another AWS CloudFormation Stack (p. 248). Use IAM to Control Access IAM is an AWS service that you can use to manage users and their permissions in AWS. You can use IAM with AWS CloudFormation to specify what AWS CloudFormation actions users can perform, such as viewing stack templates, creating stacks, or deleting stacks. Furthermore, anyone managing AWS CloudFormation stacks will require permissions to resources within those stacks. For example, if users want to use AWS CloudFormation to launch, update, or terminate Amazon EC2 instances, they must have permission to call the relevant Amazon EC2 actions. In most cases, users require full access to manage all of the resources in a template. AWS CloudFormation makes calls to create, modify, and delete those resources on their behalf. To separate permissions between a user and the AWS CloudFormation service, use a service role. AWS CloudFormation uses the service role's policy to make calls instead of the user's policy. For more information, see AWS CloudFormation Service Role (p. 17). Verify Quotas for All Resource Types Before launching a stack, ensure that you can create all the resources that you want without hitting your AWS account limits. If you hit a limit, AWS CloudFormation won't create your stack successfully until you increase your quota or delete extra resources. Each service can have various limits that you API Version 2010-05-15 69 AWS CloudFormation User Guide Reuse Templates to Replicate Stacks in Multiple Environments should be aware of before launching a stack. For example, by default, you can only launch 200 AWS CloudFormation stacks per region in your AWS account. For more information about limits and how to increase the default limits, see AWS Service Limits in the AWS General Reference. Reuse Templates to Replicate Stacks in Multiple Environments After you have your stacks and resources set up, you can reuse your templates to replicate your infrastructure in multiple environments. For example, you can create environments for development, testing, and production so that you can test changes before implementing them into production. To make templates reusable, use the parameters, mappings, and conditions sections so that you can customize your stacks when you create them. For example, for your development environments, you can specify a lower-cost instance type compared to your production environment, but all other configurations and settings remain the same. For more information about parameters, mappings, and conditions, see Template Anatomy (p. 163). Use Nested Stacks to Reuse Common Template Patterns As your infrastructure grows, common patterns can emerge in which you declare the same components in each of your templates. You can separate out these common components and create dedicated templates for them. That way, you can mix and match different templates but use nested stacks to create a single, unified stack. Nested stacks are stacks that create other stacks. To create nested stacks, use the AWS::CloudFormation::Stack (p. 694) resource in your template to reference other templates. For example, assume that you have a load balancer configuration that you use for most of your stacks. Instead of copying and pasting the same configurations into your templates, you can create a dedicated template for the load balancer. Then, you just use the AWS::CloudFormation::Stack (p. 694) resource to reference that template from within other templates. If the load balancer template is updated, any stack that is referencing it will use the updated load balancer (only after you update the stack). In addition to simplifying updates, this approach lets you use experts to create and maintain components that you might not be necessarily familiar with. All you need to do is reference their templates. Do Not Embed Credentials in Your Templates Rather than embedding sensitive information in your AWS CloudFormation templates, use input parameters to pass in information whenever you create or update a stack. If you do, make sure to use the NoEcho property to obfuscate the parameter value. For example, suppose your stack creates a new database instance. When the database is created, AWS CloudFormation needs to pass a database administrator password. You can pass in a password by using an input parameter instead of embedding it in your template. For more information, see Parameters (p. 167). Use AWS-Specific Parameter Types If your template requires inputs for existing AWS-specific values, such as existing Amazon Virtual Private Cloud IDs or an Amazon EC2 key pair name, use AWS-specific parameter types. For example, you can API Version 2010-05-15 70 AWS CloudFormation User Guide Use Parameter Constraints specify a parameter as type AWS::EC2::KeyPair::KeyName, which takes an existing key pair name that is in your AWS account and in the region where you are creating the stack. AWS CloudFormation can quickly validate values for AWS-specific parameter types before creating your stack. Also, if you use the AWS CloudFormation console, AWS CloudFormation shows a drop-down list of valid values, so you don't have to look up or memorize the correct VPC IDs or key pair names. For more information, see Parameters (p. 167). Use Parameter Constraints With constraints, you can describe allowed input values so that AWS CloudFormation catches any invalid values before creating a stack. You can set constraints such as a minimum length, maximum length, and allowed patterns. For example, you can set constraints on a database user name value so that it must be a minimum length of eight character and contain only alpha-numeric characters. For more information, see Parameters (p. 167). Use AWS::CloudFormation::Init to Deploy Software Applications on Amazon EC2 Instances When you launch stacks, you can install and configure software applications on Amazon EC2 instances by using the cfn-init helper script and the AWS::CloudFormation::Init resource. By using AWS::CloudFormation::Init, you can describe the configurations that you want rather than scripting procedural steps. You can also update configurations without recreating instances. And if anything goes wrong with your configuration, AWS CloudFormation generates logs that you can use to investigate issues. In your template, specify installation and configuration states in the AWS::CloudFormation::Init (p. 677) resource. For a walkthrough that shows how to use cfninit and AWS::CloudFormation::Init, see Deploying Applications on Amazon EC2 with AWS CloudFormation (p. 260). Use the Latest Helper Scripts The helper scripts (p. 2324) are updated periodically. Be sure you include the following command in the UserData property of your template before you call the helper scripts to ensure that your launched instances get the latest helper scripts: yum install -y aws-cfn-bootstrap For more information about getting the latest helper scripts, see the CloudFormation Helper Scripts Reference (p. 2324). Validate Templates Before Using Them Before you use a template to create or update a stack, you can use AWS CloudFormation to validate it. Validating a template can help you catch syntax and some semantic errors, such as circular dependencies, before AWS CloudFormation creates any resources. If you use the AWS CloudFormation console, the console automatically validates the template after you specify input parameters. For the API Version 2010-05-15 71 AWS CloudFormation User Guide Manage All Stack Resources Through AWS CloudFormation AWS CLI or AWS CloudFormation API, use the aws cloudformation validate-template command or ValidateTemplate action. During validation, AWS CloudFormation first checks if the template is valid JSON. If it isn't, AWS CloudFormation checks if the template is valid YAML. If both checks fail, AWS CloudFormation returns a template validation error. Manage All Stack Resources Through AWS CloudFormation After you launch a stack, use the AWS CloudFormation console, API, or AWS CLI to update resources in your stack. Do not make changes to stack resources outside of AWS CloudFormation. Doing so can create a mismatch between your stack's template and the current state of your stack resources, which can cause errors if you update or delete the stack. For more information, see Walkthrough: Updating a Stack (p. 47). Create Change Sets Before Updating Your Stacks Change sets allow you to see how proposed changes to a stack might impact your running resources before you implement them. AWS CloudFormation doesn't make any changes to your stack until you execute the change set, allowing you to decide whether to proceed with your proposed changes or create another change set. Use change sets to check how your changes might impact your running resources, especially for critical resources. For example, if you change the name of an Amazon RDS database instance, AWS CloudFormation will create a new database and delete the old one; you will lose the data in the old database unless you've already backed it up. If you generate a change set, you will see that your change will replace your database. This can help you plan before you update your stack. For more information, see Updating Stacks Using Change Sets (p. 122). Use Stack Policies Stack policies help protect critical stack resources from unintentional updates that could cause resources to be interrupted or even replaced. A stack policy is a JSON document that describes what update actions can be performed on designated resources. Specify a stack policy whenever you create a stack that has critical resources. During a stack update, you must explicitly specify the protected resources that you want to update; otherwise, no changes are made to protected resources. For more information, see Prevent Updates to Stack Resources (p. 141). Use AWS CloudTrail to Log AWS CloudFormation Calls AWS CloudTrail tracks anyone making AWS CloudFormation API calls in your AWS account. API calls are logged whenever anyone uses the AWS CloudFormation API, the AWS CloudFormation console, a back-end console, or AWS CloudFormation AWS CLI commands. Enable logging and specify an API Version 2010-05-15 72 AWS CloudFormation User Guide Use Code Reviews and Revision Controls to Manage Your Templates Amazon S3 bucket to store the logs. That way, if you ever need to, you can audit who made what AWS CloudFormation call in your account. For more information, see Logging AWS CloudFormation API Calls with AWS CloudTrail (p. 17). Use Code Reviews and Revision Controls to Manage Your Templates Your stack templates describe the configuration of your AWS resources, such as their property values. To review changes and to keep an accurate history of your resources, use code reviews and revision controls. These methods can help you track changes between different versions of your templates, which can help you track changes to your stack resources. Also, by maintaining a history, you can always revert your stack to a certain version of your template. Update Your Amazon EC2 Linux Instances Regularly On all your Amazon EC2 Linux instances and Amazon EC2 Linux instances created with AWS CloudFormation, regularly run the yum update command to update the RPM package. This ensures that you get the latest fixes and security updates. API Version 2010-05-15 73 AWS CloudFormation User Guide Walkthrough: Building a Pipeline for Test and Production Stacks Continuous Delivery with AWS CodePipeline Continuous delivery is a release practice in which code changes are automatically built, tested, and prepared for release to production. With AWS CloudFormation and AWS CodePipeline, you can use continuous delivery to automatically build and test changes to your AWS CloudFormation templates before promoting them to production stacks. This release process lets you rapidly and reliably make changes to your AWS infrastructure. For example, you can create a workflow that automatically builds a test stack when you submit an updated template to a code repository. After AWS CloudFormation builds the test stack, you can test it and then decide whether to push the changes to a production stack. For more information about the benefits of continuous delivery, see What is Continuous Delivery?. Use AWS CodePipeline to build a continuous delivery workflow by building a pipeline for AWS CloudFormation stacks. AWS CodePipeline has built-in integration with AWS CloudFormation, so you can specify AWS CloudFormation-specific actions, such as creating, updating, or deleting a stack, within a pipeline. For more information about AWS CodePipeline, see the AWS CodePipeline User Guide. Topics • Walkthrough: Building a Pipeline for Test and Production Stacks (p. 74) • AWS CloudFormation Configuration Properties Reference (p. 81) • AWS CloudFormation Artifacts (p. 85) • Using Parameter Override Functions with AWS CodePipeline Pipelines (p. 86) Walkthrough: Building a Pipeline for Test and Production Stacks Imagine a release process where you submit an AWS CloudFormation template, which AWS CloudFormation then uses to automatically build a test stack. After you review the test stack, you can preview how your changes will modify your production stack, and then choose whether to implement them. To accomplish this workflow, you could use AWS CloudFormation to build your test stack, delete the test stack, create a change set, and then execute the change set. However, with each action, you need to manually interact with AWS CloudFormation. In this walkthrough, we'll build an AWS CodePipeline pipeline that automates many of these actions, helping you achieve a continuous delivery workflow with your AWS CloudFormation stacks. Prerequisites This walkthrough assumes that you have used AWS CodePipeline and AWS CloudFormation, and know how pipelines and AWS CloudFormation templates and stacks work. For more information about AWS CodePipeline, see the AWS CodePipeline User Guide. You also need to have an Amazon S3 bucket in the same AWS region in which you will create your pipeline. Important The sample Word Press template creates an EC2 instance that requires a connection to the Internet. Check that you have a default VPC and subnet that allow traffic to the Internet. API Version 2010-05-15 74 AWS CloudFormation User Guide Walkthrough Overview Walkthrough Overview This walkthrough builds a pipeline for a sample WordPress site in a stack. The pipeline is separated into three stages. Each stage must contain at least one action, which is a task the pipeline performs on your artifacts (your input). A stage organizes actions in a pipeline. AWS CodePipeline must complete all actions in a stage before the stage processes new artifacts, for example, if you submitted new input to rerun the pipeline. By the end of this walkthrough, you'll have a pipeline that performs the following workflow: 1. The first stage of the pipeline retrieves a source artifact (an AWS CloudFormation template and its configuration files) from a repository. You'll prepare an artifact that includes a sample WordPress template and upload it to an S3 bucket. 2. In the second stage, the pipeline creates a test stack and then waits for your approval. After you review the test stack, you can choose to continue with the original pipeline or create and submit another artifact to make changes. If you approve, this stage deletes the test stack, and then the pipeline continues to the next stage. 3. In the third stage, the pipeline creates a change set against a production stack, and then waits for your approval. In your initial run, you won't have a production stack. The change set shows you all of the resources that AWS CloudFormation will create. If you approve, this stage executes the change set and builds your production stack. Note AWS CloudFormation is a free service. However, you are charged for the AWS resources, such as the EC2 instance, that you include in your stack at the current rate for each. For more information about AWS pricing, see the detail page for each product at http://aws.amazon.com. Step 1: Edit the Artifact and Upload It to an S3 Bucket Before you build your pipeline, you must set up your source repository and files. AWS CodePipeline copies these source files into your pipeline's artifact store, and then uses them to perform actions in your pipeline, such as creating an AWS CloudFormation stack. When you use Amazon Simple Storage Service (Amazon S3) as the source repository, AWS CodePipeline requires you to zip your source files before uploading them to an S3 bucket. The zipped file is an AWS CodePipeline artifact that can contain an AWS CloudFormation template, a template configuration file, or both. We provide an artifact that contains a sample WordPress template and two template configuration files. The two configuration files specify parameter values for the WordPress template. AWS CodePipeline uses them when it creates the WordPress stacks. One file contains parameter values for a test stack, and the other for a production stack. You'll need to edit the configuration files, for example, to specify an existing EC2 key-pair name that you own. For more information about artifacts, see AWS CloudFormation Artifacts (p. 85). After you build your artifact, you'll upload it to an S3 bucket. To edit and upload the artifact 1. Download and open the sample artifact: https://s3.amazonaws.com/cloudformation-examples/ user-guide/continuous-deployment/wordpress-single-instance.zip. The artifact contains three files: API Version 2010-05-15 75 AWS CloudFormation User Guide Step 2: Create the Pipeline Stack • The sample WordPress template: wordpress-single-instance.yaml • The template configuration file for the test stack.: test-stack-configuration.json • The template configuration file for the production stack: prod-stack-configuration.json 2. Extract all of the files, and then use any text editor to modify the template configuration files. Open the configuration files to see that they contain key-value pairs that map to the WordPress template's parameters. The configuration files specify the parameter values that your pipeline uses when it creates the test and production stacks. Edit the test-stack-configuration.json file to specify parameter values for the test stack and the prod-stack-configuration.json file for the production stack. • Change the values of the DBPassword and DBRootPassword keys to passwords that you can use to log in to your WordPress database. As defined in the WordPress template, the parameter values must contain only alphanumeric characters. • Change the value of the KeyName key to an existing EC2 key-pair name in the region in which you will create your pipeline. 3. Add the modified configuration files to the original artifact (.zip) file, replacing duplicate files. You now have a customized artifact that you can upload to an S3 bucket. 4. Upload the artifact to an S3 bucket that you own. Note the file's location. You'll specify the location of this file when you build your pipeline. Notes about the artifact and S3 bucket: • Use a bucket that is in the same AWS region in which you will create your pipeline. • AWS CodePipeline requires that the bucket is versioning enabled. • You can also use services that don't require you to zip your files before uploading them, like GitHub or AWS CodeCommit, for your source repository. • Artifacts can contain sensitive information such as passwords. Limit access so that only permitted users can view the file. When you do, ensure that AWS CodePipeline can still access the file. You now have an artifact that AWS CodePipeline can pull in to your pipeline. In the next step, you'll specify the artifact's location and build the WordPress pipeline. Step 2: Create the Pipeline Stack To create the WordPress pipeline, you'll use a sample AWS CloudFormation template. In addition to building the pipeline, the template sets up AWS Identity and Access Management (IAM) service roles for AWS CodePipeline and AWS CloudFormation, an S3 bucket for the AWS CodePipeline artifact store, and an Amazon Simple Notification Service (Amazon SNS) topic to which the pipeline sends notifications, such as notifications about reviews. The sample template makes it easy to provision and configure these resources in a single AWS CloudFormation stack. For more details about the configuration of the pipeline, see What the Pipeline Does (p. 77). Important The sample WordPress template creates an EC2 instance that requires a connection to the Internet. Check that your default VPC and subnet allow traffic to the Internet. To create the pipeline stack 1. Download the sample template at https://s3.amazonaws.com/cloudformation-examples/userguide/continuous-deployment/basic-pipeline.yml. Save it on your computer. API Version 2010-05-15 76 AWS CloudFormation User Guide Step 2: Create the Pipeline Stack 2. Open the AWS CloudFormation console at https://console.aws.amazon.com/cloudformation/. 3. Choose an AWS region that supports AWS CodePipeline and AWS CloudFormation. For more information, see AWS Regions and Endpoints in the AWS General Reference. 4. Choose Create Stack. 5. In the Template section, choose Upload a template to Amazon S3, and then choose the template that you just downloaded, basic-pipeline.yml. 6. Choose Next. 7. For Stack name, type sample-WordPress-pipeline. 8. In the Parameters section, specify the following parameter values, and then choose Next. When setting stack parameters, if you kept the same names for the WordPress template and its configuration files, you can use the default values. If not, specify the filenames that you used. PipelineName The name of your pipeline, such as WordPress-test-pipeline. S3Bucket The name of the S3 bucket where you saved your artifact (.zip file). SourceS3Key The filename of your artifact. If you saved the artifact in a folder, include it as part of the filename, such as folder/subfolder/wordpress-single-instance.zip. Email The email address to which AWS CodePipeline sends pipeline notification, such as myemail@example.com. 9. For this walkthrough, you don't need to add tags or specify advanced settings, so choose Next. 10. Ensure that the stack name and template URL are correct, and then choose Create. 11. To acknowledge that you're aware that AWS CloudFormation might create IAM resources, choose the checkbox. It might take several minutes for AWS CloudFormation to create your stack. To monitor progress, view the stack events. For more information, see Viewing Stack Data and Resources (p. 99). After your stack has been created, AWS CodePipeline starts your new pipeline. To view its status, see the AWS CodePipeline console. From the list of pipelines, choose WordPress-test-pipeline. What the Pipeline Does This section explains the pipeline's three stages, using snippets from the sample WordPress pipeline template. Stage 1: Source The first stage of the pipeline is a source stage in which you specify the location of your source code. Every time you push a revision to this location, AWS CodePipeline reruns your pipeline. The source code is located in an S3 bucket and is identified by its filename. You specified these values as input parameter values when you created the pipeline stack. To allow using the source artifact in subsequent stages, the snippet specifies the OutputArtifacts property, with the name TemplateSource. To use this artifact in later stages, you specify TemplateSource as an input artifact. - Name: S3Source API Version 2010-05-15 77 AWS CloudFormation User Guide Step 2: Create the Pipeline Stack Actions: - Name: TemplateSource ActionTypeId: Category: Source Owner: AWS Provider: S3 Version: '1' Configuration: S3Bucket: !Ref 'S3Bucket' S3ObjectKey: !Ref 'SourceS3Key' OutputArtifacts: - Name: TemplateSource Stage 2: TestStage In the TestStage stage, the pipeline creates the test stack, waits for approval, and then deletes the test stack. For the CreateStack action, the pipeline uses the test configuration file and WordPress template to create the test stack. Both files are contained in the TemplateSource input artifact, which is brought in from the source stage. The snippet uses the REPLACE_ON_FAILURE action mode. If stack creation fails, the pipeline replaces it so that you don't need to clean up or troubleshoot the stack before you can rerun the pipeline. The action mode is useful for quickly iterating on test stacks. For the RoleArn property, the value is an AWS CloudFormation service role that is declared elsewhere in the template. The ApproveTestStack action pauses the pipeline and sends a notification to the email address that you specified when you created the pipeline stack. While the pipeline is paused, you can check the WordPress test stack and its resources. Use AWS CodePipeline to approve or reject this action. The CustomData property includes a description of the action you're approving, which the pipeline adds to the notification email. After you approve this action, AWS CodePipeline moves to the DeleteTestStack action and deletes the test WordPress stack and its resources. - Name: TestStage Actions: - Name: CreateStack ActionTypeId: Category: Deploy Owner: AWS Provider: CloudFormation Version: '1' InputArtifacts: - Name: TemplateSource Configuration: ActionMode: REPLACE_ON_FAILURE RoleArn: !GetAtt [CFNRole, Arn] StackName: !Ref TestStackName TemplateConfiguration: !Sub "TemplateSource::${TestStackConfig}" TemplatePath: !Sub "TemplateSource::${TemplateFileName}" RunOrder: '1' - Name: ApproveTestStack ActionTypeId: Category: Approval Owner: AWS Provider: Manual Version: '1' Configuration: NotificationArn: !Ref CodePipelineSNSTopic CustomData: !Sub 'Do you want to create a change set against the production stack and delete the ${TestStackName} stack?' RunOrder: '2' API Version 2010-05-15 78 AWS CloudFormation User Guide Step 2: Create the Pipeline Stack - Name: DeleteTestStack ActionTypeId: Category: Deploy Owner: AWS Provider: CloudFormation Version: '1' Configuration: ActionMode: DELETE_ONLY RoleArn: !GetAtt [CFNRole, Arn] StackName: !Ref TestStackName RunOrder: '3' Stage 3: ProdStage The ProdStage stage of the pipeline creates a change set against the existing production stack, waits for approval, and then executes the change set. A change set provides a preview of all modifications AWS CloudFormation will make to your production stack before implementing them. On your first pipeline run, you won't have a running production stack. The change set shows the actions that AWS CloudFormation performed when creating the test stack. To create the change set, the CreateChangeSet action uses the WordPress sample template and the production template configuration from the TemplateSource input artifact. Similar to the previous stage, the ApproveChangeSet action pauses the pipeline and sends an email notification. While the pipeline is paused, you can view the change set to check all of the proposed modifications to the production WordPress stack. Use AWS CodePipeline to approve or reject this action to continue or stop the pipeline, respectively. After you approve this action, the ExecuteChangeSet action executes the changes set, so that AWS CloudFormation performs all of the actions described in the change set. For the initial run, AWS CloudFormation creates the WordPress production stack. On subsequent runs, AWS CloudFormation updates the stack. - Name: ProdStage Actions: - Name: CreateChangeSet ActionTypeId: Category: Deploy Owner: AWS Provider: CloudFormation Version: '1' InputArtifacts: - Name: TemplateSource Configuration: ActionMode: CHANGE_SET_REPLACE RoleArn: !GetAtt [CFNRole, Arn] StackName: !Ref ProdStackName ChangeSetName: !Ref ChangeSetName TemplateConfiguration: !Sub "TemplateSource::${ProdStackConfig}" TemplatePath: !Sub "TemplateSource::${TemplateFileName}" RunOrder: '1' - Name: ApproveChangeSet ActionTypeId: Category: Approval Owner: AWS Provider: Manual Version: '1' Configuration: NotificationArn: !Ref CodePipelineSNSTopic CustomData: !Sub 'A new change set was created for the ${ProdStackName} stack. Do you want to implement the changes?' RunOrder: '2' API Version 2010-05-15 79 AWS CloudFormation User Guide Step 3: View the WordPress Stack - Name: ExecuteChangeSet ActionTypeId: Category: Deploy Owner: AWS Provider: CloudFormation Version: '1' Configuration: ActionMode: CHANGE_SET_EXECUTE ChangeSetName: !Ref ChangeSetName RoleArn: !GetAtt [CFNRole, Arn] StackName: !Ref ProdStackName RunOrder: '3' Step 3: View the WordPress Stack As AWS CodePipeline runs through the pipeline, it uses AWS CloudFormation to create test and production stacks. To see the status of these stacks and their output, use the AWS CloudFormation console. To view a stack 1. Open the AWS CloudFormation console at https://console.aws.amazon.com/cloudformation/. 2. Depending on whether your pipeline is in the test or production stage, choose the TestMyWordPressSite or the Prod-MyWordPressSite stack. To check the status of your stack, view the stack events (p. 99). 3. If the stack is in a failed state, view the status reason to find the stack error. Fix the error, and then rerun the pipeline. If the stack is in the CREATE_COMPLETE state, view its outputs to get the URL of your WordPress site. You've successfully used AWS CodePipeline to build a continuous delivery workflow for a sample WordPress site. If you submit changes to the S3 bucket, AWS CodePipeline automatically detects a new version, and then reruns your pipeline. This workflow makes it easier to submit and test changes before making changes to your production site. Step 4: Clean Up Resources To make sure that you are not charged for unwanted services, delete your resources. Important Delete the test and production WordPress stacks before deleting the pipeline stack. The pipeline stack contains a service role that's required to delete the WordPress stacks. If you deleted the pipeline stack first, you can associate another service role Amazon Resource Name (ARN) with the WordPress stacks, and then delete them. To delete objects in the artifact store 1. 2. Open the Amazon S3 console at https://console.aws.amazon.com/s3/. Choose the S3 bucket that AWS CodePipeline used as your pipeline's artifact store. 3. The bucket's name follows the format: stackname-artifactstorebucket-id. If you followed this walkthrough, the bucket's name might look similar to the following example: sampleWordPress-pipeline-artifactstorebucket-12345abcd12345. Delete all of the objects in the artifact store S3 bucket. When you delete the pipeline stack in the next step, this bucket must be empty. Otherwise, AWS CloudFormation won't be able to delete the bucket. API Version 2010-05-15 80 AWS CloudFormation User Guide Configuration Properties Reference To delete stacks 1. From the AWS CloudFormation console, choose the stack that you want to delete. If the WordPress stacks that were created by the pipeline are still running, choose them first. By default, the stack names are Test-MyWordPressSite and Prod-MyWordPressSite. 2. If you already deleted the WordPress stacks, choose the sample-WordPress-pipeline stack. Choose Actions, and then choose Delete Stack. 3. In the confirmation message, choose Yes, Delete. AWS CloudFormation deletes the stack all of the stack's resources, such as the EC2 instance, notification topic, service role, and the pipeline. Now that you understand how to build a basic AWS CloudFormation workflow with AWS CodePipeline, you can use the sample template and artifacts as a starting point for building your own. AWS CloudFormation Configuration Properties Reference When you build an AWS CodePipeline pipeline, you add a Deploy action to the pipeline with AWS CloudFormation as a provider. You then must specify which AWS CloudFormation action the pipeline invokes and the action's settings. This topic describes the AWS CloudFormation configuration properties. To specify properties, you can use the AWS CodePipeline console, or you can create a JSON object to use for the AWS CLI, AWS CodePipeline API, or AWS CloudFormation templates. Topics • Configuration Properties (Console) (p. 81) • Configuration Properties (JSON Object) (p. 83) Configuration Properties (Console) The AWS CodePipeline console shows the configuration properties and indicates the properties that are required based on the Action mode that you choose. Note When you create a new pipeline, you can specify only the Create or update a stack or Create or replace a change set action modes. Also, properties in the Advanced section are available only when you edit an existing pipeline. Action mode The AWS CloudFormation action that AWS CodePipeline invokes when processing the associated stage. Choose one of the following action modes: • Create or replace a change set creates the change set if it doesn't exist based on the stack name and template that you submit. If the change set exists, AWS CloudFormation deletes it, and then creates a new one. • Create or update a stack creates the stack if the specified stack doesn't exist. If the stack exists, AWS CloudFormation updates the stack. Use this action to update existing stacks. AWS CodePipeline won't replace the stack. • Delete a stack deletes a stack. If you specify a stack that doesn't exist, the action completes successfully without deleting a stack. API Version 2010-05-15 81 AWS CloudFormation User Guide Configuration Properties (Console) • Execute a change set executes a change set. • Replace a failed stack creates the stack if the specified stack doesn't exist. If the stack exists and is in a failed state (reported as ROLLBACK_COMPLETE, ROLLBACK_FAILED, CREATE_FAILED, DELETE_FAILED, or UPDATE_ROLLBACK_FAILED), AWS CloudFormation deletes the stack and then creates a new stack. If the stack isn't in a failed state, AWS CloudFormation updates it. Use this action to automatically replace failed stacks without recovering or troubleshooting them. You would typically choose this mode for testing. Stack name The name of an existing stack or a stack that you want to create. Change set name The name of an existing change set or a new change set that you want to create for the specified stack. Template The location of an AWS CloudFormation template file, which follows the format ArtifactName::TemplateFileName. Template configuration The location of a template configuration file, which follows the format ArtifactName::TemplateConfigurationFileName. The template configuration file can contain template parameter values and a stack policy. If you include sensitive information, such as passwords, restrict access to this file. For more information, see AWS CloudFormation Artifacts (p. 85). Capabilities For stacks that contain certain resources, explicit acknowledgement that AWS CloudFormation might create or update those resources. For example, you must specify CAPABILITY_IAM if your stack template contains AWS Identity and Access Management (IAM) resources. For more information, see Acknowledging IAM Resources in AWS CloudFormation Templates (p. 15). If you have IAM resources in your stack template, you must specify this property. Role name The name of the IAM service role that AWS CloudFormation assumes when it operates on resources in the specified stack. Output file name In the Advanced section, you can specify an output file name, such as CreateStackOutput.json, that AWS CodePipeline adds to the output artifact after performing the specified action. If you don't specify a name, AWS CodePipeline doesn't generate an output artifact. Parameter overrides In the Advanced section, you can specify a JSON object that overrides template parameter values in the template configuration file. All parameter names must be present in the stack template. Note There is a maximum size limit of 1 kilobyte for the JSON object that can be stored in the ParameterOverrides property. We recommend that you use the template configuration file to specify most of your parameter values. Use parameter overrides to specify only dynamic parameter values (values that are unknown until you run the pipeline). API Version 2010-05-15 82 AWS CloudFormation User Guide Configuration Properties (JSON Object) The following example defines a value for the ParameterName parameter by using a parameter override function. The function retrieves a value from an AWS CodePipeline input artifact. For more information about parameter override functions, see Using Parameter Override Functions with AWS CodePipeline Pipelines (p. 86). { "ParameterName" : { "Fn::GetParam" : ["ArtifactName", "config-file-name.json", "ParamName"]} } Configuration Properties (JSON Object) When you specify CloudFormation as a provider for a stage action, define the following properties within the Configuration property. Use the JSON object for the AWS CLI, AWS CodePipeline API, or AWS CloudFormation templates. For examples, see Walkthrough: Building a Pipeline for Test and Production Stacks (p. 74) ActionMode The AWS CloudFormation action that AWS CodePipeline invokes when processing the associated stage. Specify only one of the following action modes: • CHANGE_SET_EXECUTE executes a change set. • CHANGE_SET_REPLACE creates the change set if it doesn't exist based on the stack name and template that you submit. If the change set exists, AWS CloudFormation deletes it, and then creates a new one. • CREATE_UPDATE creates the stack if the specified stack doesn't exist. If the stack exists, AWS CloudFormation updates the stack. Use this action to update existing stacks. AWS CodePipeline won't replace the stack. • DELETE_ONLY deletes a stack. If you specify a stack that doesn't exist, the action completes successfully without deleting a stack. • REPLACE_ON_FAILURE creates a stack if the specified stack doesn't exist. If the stack exists and is in a failed state (reported as ROLLBACK_COMPLETE, ROLLBACK_FAILED, CREATE_FAILED, DELETE_FAILED, or UPDATE_ROLLBACK_FAILED), AWS CloudFormation deletes the stack and then creates a new stack. If the stack isn't in a failed state, AWS CloudFormation updates it. Use this action to automatically replace failed stacks without recovering or troubleshooting them. You would typically choose this mode for testing. This property is required. Capabilities For stacks that contain certain resources, explicit acknowledgement that AWS CloudFormation might create or update those resources. For example, you must specify CAPABILITY_IAM if your stack template contains AWS Identity and Access Management (IAM) resources. For more information, see Acknowledging IAM Resources in AWS CloudFormation Templates (p. 15). This property is conditional. If you have IAM resources in your stack template, you must specify this property. ChangeSetName The name of an existing change set or a new change set that you want to create for the specified stack. This property is required for the following action modes: CHANGE_SET_REPLACE and CHANGE_SET_EXECUTE. For all other action modes, this property is ignored. API Version 2010-05-15 83 AWS CloudFormation User Guide Configuration Properties (JSON Object) OutputFileName A name for the output file, such as CreateStackOutput.json. AWS CodePipeline adds the file to the output artifact after performing the specified action. This property is optional. If you don't specify a name, AWS CodePipeline doesn't generate an output artifact. ParameterOverrides A JSON object that specifies values for template parameters. If you specify parameters that are also specified in the template configuration file, these values override them. All parameter names must be present in the stack template. Note There is a maximum size limit of 1 kilobyte for the JSON object that can be stored in the ParameterOverrides property. We recommend that you use the template configuration file to specify most of your parameter values. Use parameter overrides to specify only dynamic parameter values (values that are unknown until you run the pipeline). The following example defines a value for the ParameterName parameter by using a parameter override function. The function retrieves a value from an AWS CodePipeline input artifact. For more information about parameter override functions, see Using Parameter Override Functions with AWS CodePipeline Pipelines (p. 86). { "ParameterName" : { "Fn::GetParam" : ["ArtifactName", "config-file-name.json", "ParamName"]} } This property is optional. RoleArn The Amazon Resource Name (ARN) of the IAM service role that AWS CloudFormation assumes when it operates on resources in a stack. This property is required for the following action modes: CREATE_UPDATE, REPLACE_ON_FAILURE, DELETE_ONLY, and CHANGE_SET_REPLACE. Note: RoleArn is not applied when executing a change set. If you do not use CodePipeline to create the change set, you must ensure that the change set or stack has an associated role. StackName The name of an existing stack or a stack that you want to create. This property is required for all action modes. TemplateConfiguration The location of a template configuration file, which follows the format ArtifactName::TemplateConfigurationFileName. The template configuration file can contain template parameter values and a stack policy. Note that if you include sensitive information, such as passwords, restrict access to this file. For more information, see AWS CloudFormation Artifacts (p. 85). This property is optional. TemplatePath The location of an AWS CloudFormation template file, which follows the format ArtifactName::TemplateFileName. API Version 2010-05-15 84 AWS CloudFormation User Guide AWS CloudFormation Artifacts This property is required for the following action modes: CREATE_UPDATE, REPLACE_ON_FAILURE, and CHANGE_SET_REPLACE. For all other action modes, this property is ignored. AWS CloudFormation Artifacts AWS CodePipeline performs tasks on artifacts as AWS CodePipeline runs a pipeline. For AWS CloudFormation, artifacts can include a stack template file, a template configuration file, or both. AWS CodePipeline uses these artifacts to work with AWS CloudFormation stacks and change sets. If you use Amazon Simple Storage Service (Amazon S3) as a source repository, you must zip the template and template configuration files into a single file before you upload them to an S3 bucket. For other repositories, such as GitHub and AWS CodeCommit, upload artifacts without zipping them. For more information, see Create a Pipeline in AWS CodePipeline in the AWS CodePipeline User Guide. You can add as many files as you need to your repository. For example, you might want to include two different configurations for the same template: one for a test configuration and another for a production configuration. This topic describes each artifact type. Topics • Stack Template File (p. 85) • Template Configuration File (p. 85) Stack Template File A stack template file defines the resources that AWS CloudFormation provisions and configures. These files are the same templates files that you use when you create or update stacks using AWS CloudFormation. You can use YAML or JSON-formatted templates. For more information about templates, see Template Anatomy (p. 163). Template Configuration File A template configuration file is a JSON-formatted text file that can specify template parameter values, a stack policy (p. 141), and tags. Use these configuration files to specify parameter values or a stack policy for a stack. All of the parameter values that you specify must be declared in the associated template. If you include sensitive information—such as passwords—in this file, restrict access to it. For example, if you upload your artifact to an S3 bucket, use S3 bucket policies or user policies to restrict access. To create a configuration file, use the following format : { "Parameters" : { "NameOfTemplateParameter" : "ValueOfParameter", ... }, "Tags" : { "TagKey" : "TagValue", ... }, "StackPolicy" : { "Statement" : [ API Version 2010-05-15 85 AWS CloudFormation User Guide Using Parameter Override Functions with AWS CodePipeline Pipelines } } ] StackPolicyStatement The following example specifies TestEC2Key for the KeyName parameter, adds a Department tag whose value is Marketing, and adds a stack policy that allows all update actions except for an update that deletes a resource. { } "Parameters" : { "KeyName" : "TestEC2Key" }, "Tags" : { "Department" : "Marketing" }, "StackPolicy" : { "Statement" : [ { "Effect" : "Allow", "NotAction" : "Update:Delete", "Principal": "*", "Resource" : "*" } ] } Using Parameter Override Functions with AWS CodePipeline Pipelines In an AWS CodePipeline stage, you can specify parameter overrides (p. 81) for AWS CloudFormation actions. Parameter overrides let you specify template parameter values that override values in a template configuration file. AWS CloudFormation provides functions to help you to specify dynamic values (values that are unknown until the pipeline runs). Topics • Fn::GetArtifactAtt (p. 86) • Fn::GetParam (p. 87) Fn::GetArtifactAtt The Fn::GetArtifactAtt function retrieves the value of an attribute from an input artifact, such as the S3 bucket name where the artifact is stored. Use this function to specify attributes of an artifact, such as its filename or S3 bucket name. When you run a pipeline, AWS CodePipeline copies and writes files to the pipeline's artifact store (an S3 bucket). AWS CodePipeline generates the filenames in the artifact store. These filenames are unknown before you run the pipeline. For example, in your pipeline, you might have a source stage where AWS CodePipeline copies your AWS Lambda function source code to the artifact store. In the next stage, you have an AWS CloudFormation template that creates the Lambda function, but AWS CloudFormation requires the filename to create the function. You must use the Fn::GetArtifactAtt function to pass the exact S3 bucket and file names. API Version 2010-05-15 86 AWS CloudFormation User Guide Fn::GetParam Syntax Use the following syntax to retrieve an attribute value of an artifact. { "Fn::GetArtifactAtt" : [ "artifactName", "attributeName" ] } artifactName The name of the input artifact. You must declare this artifact as input for the associated action. attributeName The name of the artifact attribute whose value you want to retrieve. For details about each artifact attribute, see the following Attributes section. Example The following parameter overrides specify the BucketName and ObjectKey parameters by retrieving the S3 bucket name and filename of the LambdaFunctionSource artifact. This example assumes that AWS CodePipeline copied Lambda function source code and saved it as an artifact, for example, as part of a source stage. { } "BucketName" : { "Fn::GetArtifactAtt" : ["LambdaFunctionSource", "BucketName"]}, "ObjectKey" : { "Fn::GetArtifactAtt" : ["LambdaFunctionSource", "ObjectKey"]} Attributes You can retrieve the following attributes for an artifact. BucketName The name of the S3 bucket where the artifact is stored. ObjectKey The name of the .zip file that contains the artifact that is generated by AWS CodePipeline, such as 1ABCyZZ.zip. URL The Amazon Simple Storage Service (Amazon S3) URL of the artifact, such as https:// s3-us-west-2.amazonaws.com/artifactstorebucket-yivczw8jma0c/test/ TemplateSo/1ABCyZZ.zip. Fn::GetParam The Fn::GetParam function returns a value from a key-value pair in a JSON-formatted file. The JSON file must be included in an artifact. Use this function to retrieve output values from an AWS CloudFormation stack and use them as input for another action. For example, if you specify an output filename for an AWS CloudFormation action, AWS CodePipeline saves the output in a JSON file and then adds it to the output artifact's .zip file. Use the Fn::GetParam function to retrieve the output value, and use it as input for another action. API Version 2010-05-15 87 AWS CloudFormation User Guide Fn::GetParam Syntax Use the following syntax to retrieve a value from a key-value pair. { "Fn::GetParam" : [ "artifactName", "JSONFileName", "keyName" ] } artifactName The name of the artifact, which must be included as an input artifact for the associated action. JSONFileName The name of a JSON file that is contained in the artifact. keyName The name of the key whose value you want to retrieve. Examples The following examples demonstrate how to use the Fn::GetParam function in a parameter override. Syntax The following parameter override specifies the WebSiteURL parameter by retrieving the value of the URL key from the stack-output.json file that is in the WebStackOutput artifact. { } "WebSiteURL" : { "Fn::GetParam" : ["WebStackOutput", "stack-output.json", "URL"]} AWS CloudFormation Template Snippets The following AWS CloudFormation template snippets, from an AWS CodePipeline pipeline, demonstrate how to pass stack outputs. These snippets show two stages of pipeline definition. The first stage creates a stack and save its outputs in the TestOutput.json file in the StackAOutput artifact. These values are specified by the OutputFileName and OutputArtifacts properties. Example Create Stack A Stage - Name: CreateTestStackA Actions: - Name: CloudFormationCreate ActionTypeId: Category: Deploy Owner: AWS Provider: CloudFormation Version: '1' Configuration: ActionMode: CREATE_UPDATE Capabilities: CAPABILITY_IAM OutputFileName: TestOutput.json RoleArn: !GetAtt [CFNRole, Arn] StackName: StackA TemplateConfiguration: TemplateSource::test-configuration.json TemplatePath: TemplateSource::teststackA.yaml InputArtifacts: - Name: TemplateSourceA OutputArtifacts: API Version 2010-05-15 88 AWS CloudFormation User Guide Fn::GetParam - Name: StackAOutput RunOrder: '1' In a subsequent stage, stack B uses the outputs from stack A. In the ParameterOverrides property, the example uses the Fn::GetParam function to specify the StackBInputParam parameter. The resulting value is the value associated with the StackAOutputName key. Example Create Stack B Stage - Name: CreateTestStackB Actions: - Name: CloudFormationCreate ActionTypeId: Category: Deploy Owner: AWS Provider: CloudFormation Version: '1' Configuration: ActionMode: CREATE_UPDATE Capabilities: CAPABILITY_IAM RoleArn: !GetAtt [CFNRole, Arn] StackName: StackB TemplateConfiguration: TemplateSource::test-configuration.json TemplatePath: TemplateSource::teststackB.yaml ParameterOverrides: | { "StackBInputParam" : { "Fn::GetParam" : ["StackAOutput", "TestOutput.json", "StackAOutputName"]} } InputArtifacts: - Name: TemplateSourceB - Name: StackAOutput RunOrder: '1' API Version 2010-05-15 89 AWS CloudFormation User Guide Using the Console Working with Stacks A stack is a collection of AWS resources that you can manage as a single unit. In other words, you can create, update, or delete a collection of resources by creating, updating, or deleting stacks. All the resources in a stack are defined by the stack's AWS CloudFormation template. A stack, for instance, can include all the resources required to run a web application, such as a web server, a database, and networking rules. If you no longer require that web application, you can simply delete the stack, and all of its related resources are deleted. AWS CloudFormation ensures all stack resources are created or deleted as appropriate. Because AWS CloudFormation treats the stack resources as a single unit, they must all be created or deleted successfully for the stack to be created or deleted. If a resource cannot be created, AWS CloudFormation rolls the stack back and automatically deletes any resources that were created. If a resource cannot be deleted, any remaining resources are retained until the stack can be successfully deleted. You can work with stacks by using the AWS CloudFormation console, API, or AWS CLI. Note You are charged for the stack resources for the time they were operating (even if you deleted the stack right away). Topics • Using the AWS CloudFormation Console (p. 90) • Using the AWS Command Line Interface (p. 108) • AWS CloudFormation Stacks Updates (p. 118) • Exporting Stack Output Values (p. 153) • Listing Stacks That Import an Exported Output Value (p. 154) • Working with Nested Stacks (p. 155) • Working with Microsoft Windows Stacks on AWS CloudFormation (p. 157) Using the AWS CloudFormation Console The AWS CloudFormation console allows you to create, monitor, update and delete stacks directly from your web browser. This section contains guidance on using the AWS CloudFormation console to perform common actions. In This Section • • • • Logging In to the Console (p. 91) Creating a Stack (p. 92) Creating an EC2 Key Pair (p. 98) Estimating the Cost of Your AWS CloudFormation Stack (p. 99) • • • • • Viewing Stack Data and Resources (p. 99) Monitor and Roll Back Stack Operations (p. 102) Creating Quick-Create Links for Stacks (p. 103) Deleting a Stack (p. 105) Protecting a Stack From Being Deleted (p. 106) • Viewing Deleted Stacks (p. 107) API Version 2010-05-15 90 AWS CloudFormation User Guide Logging In to the Console Logging In to the AWS CloudFormation Console The AWS CloudFormation console allows you to create, monitor, update, and delete your AWS CloudFormation stacks with a web-based interface. It is part of the AWS Management Console. You can access the AWS CloudFormation console in a number of ways: • Open the AWS CloudFormation console directly with the URL https://console.aws.amazon.com/ cloudformation/ . If you are not logged in to the AWS Management Console yet, you need to log in before using the AWS CloudFormation console. • If you are logged into and using the AWS Management Console, you can access the AWS CloudFormation console by opening the Services menu and selecting CloudFormation in one of the following sub-menus: • Deployment and Management • All Services API Version 2010-05-15 91 AWS CloudFormation User Guide Creating a Stack If you don't have any AWS CloudFormation stacks running, you are presented with the option to Create a stack. Otherwise, you see a list of your currently-running stacks. See Also • Creating a Stack (p. 92) Creating a Stack on the AWS CloudFormation Console Before you create a stack, you must have a template that describes what resources AWS CloudFormation will include in your stack. For more information, see Working with AWS CloudFormation Templates (p. 162). Note To preview the configuration of a new stack, you can use a change set (p. 97). Creating a stack on the AWS CloudFormation console is an easy, wizard-driven process that consists of the following steps: 1. Starting the Create Stack wizard (p. 92) 2. Selecting a stack template (p. 93) 3. Specifying stack parameters (p. 94) 4. Setting Stack Options (p. 95) 5. Reviewing your stack (p. 96) After creating a stack, you can monitor the stack's progress, view the stack's resources and outputs, update the stack, and delete it. Information about these actions are provided in their associated topics. Starting the Create Stack Wizard To create a stack on the AWS CloudFormation console 1. Log in to the AWS Management Console and select CloudFormation in the Services menu. 2. Create a new stack by using one of the following options: • Click Create Stack. This is the only option if you have a currently running stack. • Click Create New Stack in the CloudFormation Stacks main window. This option is visible only if you have no running stacks. • Click Launch CloudFormer in the CloudFormation Stacks main window to create a stack from currently running resources. This option is visible only if you have no running stacks. API Version 2010-05-15 92 AWS CloudFormation User Guide Creating a Stack For more information about using CloudFormer to create AWS CloudFormation stacks, see Using CloudFormer to Create Templates (p. 458). Next, you choose a stack template (p. 93). Selecting a Stack Template After starting the Create Stack wizard (p. 92), you specify the template that you want AWS CloudFormation to use to create your stack. AWS CloudFormation templates are JSON- or YAML-formatted files that specify the AWS resources that make up your stack. For more information about AWS CloudFormation templates, see Working with AWS CloudFormation Templates (p. 162). To choose a stack template: 1. On the Select Template page, choose a stack template by using one of the following options: Design a template To create or modify a template, use AWS CloudFormation Designer, a drag-and-drop interface. For more information, see What Is AWS CloudFormation Designer? (p. 202). Choose a template • Select a sample template. Select an AWS CloudFormation template from a list of samples. For descriptions of the templates, see Sample Templates (p. 2342). To create a stack from existing AWS resources by using the CloudFormer tool, select CloudFormer from the list. For more information, see Using CloudFormer to Create Templates (p. 458). • Upload a template to Amazon S3. Select an AWS CloudFormation template on your local computer. Choose Choose File to select the template file that you want to upload. The template can be a maximum size of 460,800 bytes. If you use the CLI or API to create a stack, you can upload a template with a maximum size of 51,200 bytes. Note If you upload a local template file, AWS CloudFormation uploads it to an Amazon Simple Storage Service (Amazon S3) bucket in your AWS account. If you don't already have an S3 bucket that was created by AWS CloudFormation, it creates a unique bucket for each Region in which you upload a template file. If you already have an S3 bucket that was created by AWS CloudFormation in your AWS account, AWS CloudFormation adds the template to that bucket. Considerations to keep in mind about S3 buckets created by AWS CloudFormation • The buckets are accessible to anyone with Amazon S3 permissions in your AWS account. API Version 2010-05-15 93 AWS CloudFormation User Guide Creating a Stack • AWS CloudFormation creates the buckets with server-side encryption enabled by default, thereby encrypting all objects stored in the bucket. You can directly manage encryption options for buckets that AWS CloudFormation has created; for example, using the Amazon S3 console at https:// console.aws.amazon.com/s3/ , or the AWS CLI. For more information, see Amazon S3 Default Encryption for S3 Buckets in the Amazon Simple Storage Service Developer Guide. • You can use your own bucket and manage its permissions by manually uploading templates to Amazon S3. When you create or update a stack, specify the Amazon S3 URL of a template file. • Specify an Amazon S3 template URL. Specify a URL to a template in an S3 bucket. Important If your template includes nested stacks (for example, stacks described in other template documents located in subdirectories), ensure that your S3 bucket contains the necessary files and directories. If you have a template in a versioning-enabled bucket, you can specify a specific version of the template, such as https://s3.amazonaws.com/templates/myTemplate.template? versionId=123ab1cdeKdOW5IH4GAcYbEngcpTJTDW. For more information, see Managing Objects in a Versioning-Enabled Bucket in the Amazon Simple Storage Service Console User Guide. The URL must point to a template with a maximum size of 460,800 bytes that is stored in an S3 bucket that you have read permissions to and that is located in the same region as the stack. The URL can be a maximum of 1024 characters long. 2. To accept your settings, choose Next, and proceed with specifying the stack name and parameters (p. 94). Before creating resources, AWS CloudFormation validates your template to catch syntactic and some semantic errors, such as circular dependencies. During validation, AWS CloudFormation first checks if the template is valid JSON. If it isn't, AWS CloudFormation checks if the template is valid YAML. If both checks fail, AWS CloudFormation returns a template validation error. Specifying Stack Name and Parameters After selecting a stack template, specify the stack name and values for the parameters that were defined in the template. With parameters, you can customize your stack at creation time. Your parameter values can be used in the stack template to modify how resources are configured. That way you don't have to hard code values in multiple templates to specify different settings. For more information about parameters in an AWS CloudFormation template, see Parameters (p. 167). To specify the stack name parameter values 1. On the Specify Details page, type a stack name in the Stack name box. The stack name is an identifier that helps you find a particular stack from a list of stacks. A stack name can contain only alphanumeric characters (case-sensitive) and hyphens. It must start with an alphabetic character and can't be longer than 128 characters. 2. In the Parameters section, specify parameters that are defined in the stack template. You can use or change any parameters with default values. API Version 2010-05-15 94 AWS CloudFormation User Guide Creating a Stack 3. When you are satisfied with the parameter values, click Next to proceed with setting options for your stack (p. 95). AWS-specific Parameter Types When you create stacks that contain AWS-specific parameter types, the AWS CloudFormation console provides drop-down lists of valid values for those parameters. Depending on the parameter type, you can search for values by ID, name, or the value of the Name tag. For example, with the AWS::EC2::VPC::Id parameter type, you can search for a specific VPC ID, such as vpc-b47658d1. If the VPC was tagged with a name, such as Name:TestVPC, you can also search for TestVPC. Currently, you can search only for tag values with the Name key. Note The console doesn't provide a drop-down list or enable you to search for values with the AWS::EC2::Image::Id parameter type; AWS CloudFormation only verifies if the input values are valid Amazon Elastic Compute Cloud image IDs. Group and Sort Parameters The console alphabetically lists input parameters by their logical ID. When you create a template, you can use the AWS::CloudFormation::Interface metadata key to override the default ordering. For more information and an example of the AWS::CloudFormation::Interface metadata key, see AWS::CloudFormation::Interface (p. 691). Setting AWS CloudFormation Stack Options After specifying parameters (p. 167) that are defined in the template, you can set additional options for your stack. You can set the following stack options: Tags Tags are arbitrary key-value pairs that can be used to identify your stack for purposes such as cost allocation. For more information about what tags are and how they can be used, see Tagging Your Resources in the Amazon EC2 User Guide. A Key consists of any alphanumeric characters or spaces. Tag keys can be up to 127 characters long. A Value consists of any alphanumeric characters or spaces. Tag values can be up to 255 characters long. Permissions An existing AWS Identity and Access Management (IAM) service role that AWS CloudFormation can assume. Instead of using your account credentials, AWS CloudFormation uses the role's credentials to create your stack. For more information, see AWS CloudFormation Service Role (p. 17). Notification Options A new or existing Amazon Simple Notification Service topic where notifications about stack events are sent. If you create an Amazon SNS topic, you must specify a name and an email address, where stack event notifications are sent. API Version 2010-05-15 95 AWS CloudFormation User Guide Creating a Stack Timeout Specifies the amount of time, in minutes, that CloudFormation should allot before timing out stack creation operations. If CloudFormation cannot create the entire stack in the time allotted, it fails the stack creation due to timeout and rolls back the stack. By default, there is no timeout for stack creation. However, individual resources may have their own timeouts based on the nature of the service they implement. For example, if an individual resource in your stack times out, stack creation also times out even if the timeout you specified for stack creation has not yet been reached. Rollback on failure Specifies whether the stack should be rolled back if stack creation fails. Typically, you want to accept the default value of Yes. Select No if you want the stack's state retained even if creation fails, such as when you are debugging a stack template. Stack policy Defines the resources that you want to protect from unintentional updates during a stack update. By default, all resources can be updated during a stack update. For more information, see Prevent Updates to Stack Resources (p. 141). Enable termination protection Prevents a stack from being accidently deleted. If a user attempts to delete a stack with termination protection enabled, the deletion fails and the stack--including its status--remains unchanged. For more information, see Protecting a Stack From Being Deleted (p. 106). To set stack options 1. On the Options screen of the Create Stack wizard, you can specify tags or set additional options by expanding the Advanced section. 2. When you have entered all of your stack options, click Next Step to proceed with reviewing your stack (p. 96). Reviewing Your Stack and Estimating Stack Cost on the AWS CloudFormation Console The final step before your stack is launched is to review the values entered while creating the stack. You can also estimate the cost of your stack. 1. On the Review page, review the details of your stack. If you need to change any of the values prior to launching the stack, click Back to go back to the page that has the setting that you want to change. 2. (Optional) You can click the Cost link to estimate the cost of your stack. The AWS Simple Monthly Calculator displays values from your stack template and launch settings. 3. After you review the stack launch settings and the estimated cost of your stack, click Create to launch your stack. Your stack appears in the list of AWS CloudFormation stacks, with a status of CREATE_IN_PROGRESS. While your stack is being created (or afterward), you can use the stack detail pane to view your stack's events, data, or resources (p. 99). AWS CloudFormation automatically refreshes stack events every minute. By viewing stack creation events, you can understand the sequence of events that lead to your stack's creation (or failure, if you are debugging your stack). API Version 2010-05-15 96 AWS CloudFormation User Guide Creating a Stack After your stack has been successfully created, its status changes to CREATE_COMPLETE. You can then select it (if necessary) and click the Outputs tab to view your stack's outputs if you have defined any in the template. Creating Stacks Using Change Sets To preview how a AWS CloudFormation stack will be configured before creating the stack, create a change set. This functionality allows you to examine various configurations and make corrections and changes to your stack before executing the change set. Creating a Change Set for a New Stack To create a change set for a new stack, submit the configuration that you want to use by providing a template, input parameter values, or both. To create a change set (console) 1. In the AWS CloudFormation console, choose Create Stack, and then choose Create Change Set for New Stack. 2. On the Select Template page, specify the location of your template. • For a template stored locally, choose Upload a template to Amazon S3. Choose File to navigate to the file, choose the file, and then choose Next. • For a template stored in an Amazon S3 bucket, choose Specify an Amazon S3 URL. Type or paste the URL for the template, and then choose Next. If your template is stored in a versioning-enabled bucket, you can specify a specific version, for example: https://s3.amazonaws.com/templates/myTemplate.template? versionId=123ab1cdeKdOW5IH4GAcYbEngcpTJTDW For more information, see Managing Objects in a Versioning-Enabled Bucket in the Amazon Simple Storage Service Console User Guide. 3. On the Specify Details page, configure the following items: • Type the Stack name. • (Optional) To identify your change set, type its Name and Description. • If your template contains parameters, type the parameter values in the Parameters section. When you finish, choose Next. 4. (Optional) On the Options page, update the stack's service role, the stack tags, and the stack's Amazon SNS notification topic, and then choose Next. 5. On the Review page, review the proposed configuration. If the template includes AWS Identity and Access Management (IAM) resources, select I acknowledge that this template may create IAM resources to acknowledge that AWS CloudFormation might create IAM resources if you execute this change set. IAM resources can modify permissions in your AWS account. Review these resources to ensure that you allow the API Version 2010-05-15 97 AWS CloudFormation User Guide Creating an EC2 Key Pair correction actions. For more information, see Controlling Access with AWS Identity and Access Management (p. 9). When you finish, choose Create change set. While AWS CloudFormation begins to create the change set, the status of the change set is CREATE_IN_PROGRESS. When AWS CloudFormation completes the creation progress, it sets its status to CREATE_COMPLETE. In the Changes section, AWS CloudFormation lists the proposed configuration of your stack. If AWS CloudFormation fails to create the change set and reports the CREATE_FAILED status, fix the error displayed in the Status field, and then create a new change set. At this stage, you can try various configurations and make corrections and changes to your stack before executing the next change set. 6. To create a new stack using the change set, choose Execute, and then choose Execute again. When you create a change set, AWS CloudFormation launches a stack and reports the REVIEW_IN_PROGRESS status until you execute the change set. Creating an EC2 Key Pair The use of some AWS CloudFormation resources and templates will require you to specify an Amazon EC2 key pair for authentication, such as when you are configuring SSH access to your instances. Amazon EC2 key pairs can be created with the AWS Management Console. For more information, see Amazon EC2 Key Pairs in the Amazon EC2 User Guide for Linux Instances. API Version 2010-05-15 98 AWS CloudFormation User Guide Estimating the Cost of Your Stack Estimating the Cost of Your AWS CloudFormation Stack There is no additional charge for AWS CloudFormation. You pay for AWS resources (e.g. Amazon EC2 instances, Elastic Load Balancing load balancers and so on) created using AWS CloudFormation as if you created them by hand. To estimate the cost of your stack 1. On the Review page of the Create Stack dialog, click the Cost link. This link opens the AWS Simple Monthly Calculator in a new browser page (or tab, depending on how your browser is set up). Note 2. Because you launched the calculator from the AWS CloudFormation console, it is prepopulated with your template configuration and parameter values. There are many additional configurable values that can provide you with a better estimate if you have an idea of how much data transfer you expect to your Amazon EC2 instance. Click the Estimate of your Monthly Bill tab for a monthly estimate of running your stack, along with a categorized display of what factors contributed to the estimate. Viewing AWS CloudFormation Stack Data and Resources on the AWS Management Console Viewing Stack Information After you've created an AWS CloudFormation stack, you can use the AWS Management Console to view its data and resources. You can view the following stack information: Outputs Displays outputs that were declared in the stack's template. Resources Displays the resources that are part of the stack. Events Displays the operations that are tracked when you create, update, or delete the stack. API Version 2010-05-15 99 AWS CloudFormation User Guide Viewing Stack Data and Resources All events that are triggered by a given stack operation are assigned the same client request token, which you can use to track operations. Stack operations that are initiated from the console use the token format Console-StackOperation-ID, which helps you to easily identify the stack operation. For example, if you create a stack using the console, each resulting stack event would be assigned the same token in the following format: Console-CreateStack-7f59c3cf-00d2-40c7-b2ffe75db0987002. Template Displays the stack's template. For stacks that contain transforms, choose View original template to view the user-submitted template, or View processed template to view the template after AWS CloudFormation processes the transforms. AWS CloudFormation uses the processed template to create or update your stack. Parameters Displays the stack's parameters and their values. For stacks that contain SSM parameters, the Resolved Value column displays the values that are used in the stack definition for the SSM parameters. For more information, see SSM Parameter Types (p. 172). Tags Displays any tags that are associated with the stack. Stack Policy Describes the stack resources that are protected against stack updates. For you to be able to update these resources, they must be explicitly allowed during a stack update. To view information about your AWS CloudFormation stack 1. 2. Select your stack in the AWS CloudFormation console. This displays information in the stack detail pane. In the detail pane, click a tab to view the related information about your stack. For example, click Outputs to view the outputs that are associated with your stack. Stack Status Codes The following table describes stack status codes: Stack Status Description CREATE_COMPLETE Successful creation of one or more stacks. API Version 2010-05-15 100 AWS CloudFormation User Guide Viewing Stack Data and Resources Stack Status Description CREATE_IN_PROGRESS Ongoing creation of one or more stacks. CREATE_FAILED Unsuccessful creation of one or more stacks. View the stack events to see any associated error messages. Possible reasons for a failed creation include insufficient permissions to work with all resources in the stack, parameter values rejected by an AWS service, or a timeout during resource creation. DELETE_COMPLETE Successful deletion of one or more stacks. Deleted stacks are retained and viewable for 90 days. DELETE_FAILED Unsuccessful deletion of one or more stacks. Because the delete failed, you might have some resources that are still running; however, you cannot work with or update the stack. Delete the stack again or view the stack events to see any associated error messages. DELETE_IN_PROGRESS Ongoing removal of one or more stacks. REVIEW_IN_PROGRESS Ongoing creation of one or more stacks with an expected StackId but without any templates or resources. Important A stack with this status code counts against the maximum possible number of stacks (p. 21). ROLLBACK_COMPLETE Successful removal of one or more stacks after a failed stack creation or after an explicitly canceled stack creation. Any resources that were created during the create stack action are deleted. This status exists only after a failed stack creation. It signifies that all operations from the partially created stack have been appropriately cleaned up. When in this state, only a delete operation can be performed. ROLLBACK_FAILED Unsuccessful removal of one or more stacks after a failed stack creation or after an explicitly canceled stack creation. Delete the stack or view the stack events to see any associated error messages. ROLLBACK_IN_PROGRESS Ongoing removal of one or more stacks after a failed stack creation or after an explicitly cancelled stack creation. UPDATE_COMPLETE Successful update of one or more stacks. UPDATE_COMPLETE_CLEANUP_IN_PROGRESS Ongoing removal of old resources for one or more stacks after a successful stack update. For stack updates that require resources to be replaced, AWS CloudFormation creates the new resources first and then deletes the old resources to help reduce any interruptions with your stack. In this state, the stack has been updated and is usable, but AWS CloudFormation is still deleting the old resources. UPDATE_IN_PROGRESS Ongoing update of one or more stacks. UPDATE_ROLLBACK_COMPLETE Successful return of one or more stacks to a previous working state after a failed stack update. API Version 2010-05-15 101 AWS CloudFormation User Guide Monitor and Roll Back Stack Operations Stack Status Description UPDATE_ROLLBACK_COMPLETE_CLEANUP_IN_PROGRESS Ongoing removal of new resources for one or more stacks after a failed stack update. In this state, the stack has been rolled back to its previous working state and is usable, but AWS CloudFormation is still deleting any new resources it created during the stack update. UPDATE_ROLLBACK_FAILED Unsuccessful return of one or more stacks to a previous working state after a failed stack update. When in this state, you can delete the stack or continue rollback (p. 150). You might need to fix errors before your stack can return to a working state. Or, you can contact customer support to restore the stack to a usable state. UPDATE_ROLLBACK_IN_PROGRESS Ongoing return of one or more stacks to the previous working state after failed stack update. Monitor and Roll Back Stack Operations Rollback triggers enable you to have AWS CloudFormation monitor the state of your application during stack creation and updating, and to roll back that operation if the application breaches the threshold of any of the alarms you've specified. For each rollback trigger you create, you specify the Cloudwatch alarm that AWS CloudFormation should monitor. AWS CloudFormation monitors the specified alarms during the stack create or update operation, and for the specified amount of time after all resources have been deployed. If any of the alarms goes to ALARM state during the stack operation or the monitoring period, AWS CloudFormation rolls back the entire stack operation. You can set a monitoring time from the default of 0 up to 180 minutes. During this time, AWS CloudFormation monitors all the rollback triggers after the stack creation or update operation deploys all necessary resources. If any of the alarms goes to ALARM state during the stack operation or this monitoring period, AWS CloudFormation rolls back the entire stack operation. Then, for update operations, if the monitoring period expires without any alarms going to ALARM state, CloudFormation proceeds to dispose of old resources as usual. If you set a monitoring time but do not specify any rollback triggers, AWS CloudFormation still waits the specified period of time before cleaning up old resources for update operations. You can use this monitoring period to perform any manual stack validation desired, and manually cancel the stack creation or update as necessary. If you set a monitoring time of 0 minutes, AWS CloudFormation still monitors the rollback triggers during stack creation and update operations and rolls back the operation if an alarm goes to ALARM state. Then, for update operations with no breaching alarms, it begins disposing of old resources immediately once the operation completes. By default, CloudFormation only rolls back stack operations if an alarm goes to ALARM state, not INSUFFICIENT_DATA state. To have AWS CloudFormation roll back the stack operation if an alarm goes to INSUFFICIENT_DATA state as well, edit the CloudWatch alarm to treat missing data as breaching. For more information, see Configuring How CloudWatch Alarms Treats Missing Data in Amazon CloudWatch User Guide. AWS CloudFormation does not monitor rollback triggers when it rolls back a stack during an update operation. You can add a maximum of five rollback triggers. To add a rollback trigger, you specify the ARN (Amazon Resource Name) of the CloudWatch alarm. Currently, only AWS::CloudWatch::Alarm types can be used as rollback triggers. If a given Cloudwatch alarm is missing, the entire stack operation fails and is rolled back. API Version 2010-05-15 102 AWS CloudFormation User Guide Creating Quick-Create Links for Stacks Be aware that access to Amazon CloudWatch requires credentials. Those credentials must have permissions to access AWS resources, such as retrieving CloudWatch metric data about your cloud resources. For more information, see Authentication and Access Control for Amazon CloudWatch in Amazon CloudWatch User Guide. To add rollback triggers during stack creation or updating 1. During creating or updating a stack, on the Options page, go to Rollback Triggers. 2. Specify a monitoring time between 0 and 180 minutes. The default is 0. 3. Enter the ARN of the Cloudwatch alarm you want to use as a rollback trigger, and click the plus icon. You can add a maximum of five rollback triggers. To add rollback triggers to a change set 1. During creating or updating a change set, on the Options page, go to Rollback Triggers. 2. Specify a monitoring time between 0 and 180 minutes. The default is 0. 3. Enter the ARN of the Cloudwatch alarm you want to use as a rollback trigger, and click the plus icon. You can add a maximum of five rollback triggers. To view rollback triggers for a stack • There are two ways to view rollback triggers for a given stack: • On the Stacks page, select the checkbox for the stack you wish to view, and then select the Rollback Triggers tab in the detail section. • On the Stack Detail page, go to the Rollback Triggers section. Creating Quick-Create Links for Stacks Use quick-create links to get stacks up and running quickly from the AWS CloudFormation console. You can specify the template URL, stack name, and template parameters in URL query parameters to prepopulate a single Create Stack Wizard page. This simplifies the process of creating stacks by reducing the number of wizard pages and the amount of user input that's required. It also optimizes template reuse because you can create multiple URLs that specify different values for the same template. Supported Parameters AWS CloudFormation supports the following URL query parameters: templateURL Required. Specifies the URL of the stack template. URL encoding is supported, but it isn't required. stackName Optional. Specifies the stack name.A stack name can contain only alphanumeric characters (casesensitive) and hyphens. It must start with an alphabetic character and can't be longer than 128 characters. Any parameter in the stack template that isn't a NoEcho parameter type Optional. Use the format param_parameterName to specify template parameters in the URL query string. The URL parameter must include the param_ prefix, and the parameter name segment must exactly match the parameter name in the template. For example: param_DBName. API Version 2010-05-15 103 AWS CloudFormation User Guide Creating Quick-Create Links for Stacks AWS CloudFormation ignores parameters that don't exist in the template and NoEcho parameter types (typically, user names and passwords). URL parameters override default values that are specified in the template. You can include as many parameters as needed. For more information about NoEcho parameter types, see Parameters (p. 167). All query parameter names are case sensitive. Users can overwrite these values in the console before creating the stack. Example The following example is based on the WordPress basic single instance sample template. The query string includes the required templateURL parameter and the stackName, DBName, InstanceType, and KeyName parameters. The following URL has line breaks added for clarity. https://eu-central-1.console.aws.amazon.com/cloudformation/home?region=eu-central-1#/ stacks/create/review ?templateURL=https://s3-eu-central-1.amazonaws.com/cloudformation-templates-eucentral-1/WordPress_Single_Instance.template &stackName=MyWPBlog ¶m_DBName=mywpblog ¶m_InstanceType=t2.medium ¶m_KeyName=MyKeyPair The following URL includes the same parameters as the previous example, but the line breaks are removed. This is the actual URL format. https://eu-central-1.console.aws.amazon.com/cloudformation/home? region=eu-central-1#/stacks/create/review?templateURL=https://s3eu-central-1.amazonaws.com/cloudformation-templates-eu-central-1/ WordPress_Single_Instance.template&stackName=MyWPBlog¶m_DBName=mywpblog¶m_InstanceType=t2.mediu The example URL opens the Create Stack Wizard in the console, with the supplied values automatically used for the parameters. API Version 2010-05-15 104 AWS CloudFormation User Guide Deleting a Stack Deleting a Stack on the AWS CloudFormation Console To delete a stack 1. From the list of stacks in the AWS CloudFormation console, select the stack that you want to delete (it must be currently running). 2. Choose Actions and then Delete Stack. 3. Click Yes, Delete when prompted. Note After stack deletion has begun, you cannot abort it. The stack proceeds to the DELETE_IN_PROGRESS state. After the stack deletion is complete, the stack will be in the DELETE_COMPLETE state. Stacks in the DELETE_COMPLETE state are not displayed in the AWS CloudFormation console by default. API Version 2010-05-15 105 AWS CloudFormation User Guide Protecting a Stack From Being Deleted To display deleted stacks, you must change the stack view setting as described in Viewing Deleted Stacks (p. 107). If the delete failed, the stack will be in the DELETE_FAILED state. For solutions, see the Delete Stack Fails (p. 2344) troubleshooting topic. For information on protecting stacks from being accidently deleted see Protecting a Stack From Being Deleted (p. 106). Protecting a Stack From Being Deleted You can prevent a stack from being accidently deleted by enabling termination protection on the stack. If a user attempts to delete a stack with termination protection enabled, the deletion fails and the stack-including its status--remains unchanged. You can enable termination protection on a stack when you create it. Termination protection on stacks is disabled by default. You can set termination protection on a stack with any status except DELETE_IN_PROGRESS or DELETE_COMPLETE. Enabling or disabling termination protection on a stack sets it for any nested stacks belonging to that stack as well. You cannot enable or disable termination protection directly on a nested stack. If a user attempts to directly delete a nested stack belonging with a stack that has termination protection enabled, the operation fails and the nested stack remains unchanged. However, if a user performs a stack update that would delete the nested stack, AWS CloudFormation deletes the nested stack accordingly. Termination protection is different than disabling rollback. Termination protection applies only to attempts to delete stacks, while disabling rollback applies to auto rollback when stack creation fails. To enable termination protection when creating a stack • Select Enable Termination Protection when you are creating your stack. For more information, see Setting Stack Options (p. 95) in Creating a Stack (p. 92). To enable or disable termination protection on an existing stack 1. Sign in to the AWS Management Console and open the AWS CloudFormation console at https:// console.aws.amazon.com/cloudformation/. Select the stack that you want. Note If NESTED is displayed next to the stack name, the stack is a nested stack. You can only change termination protection on the root stack to which the nested stack belongs. 2. Choose Actions and then Change Termination Protection. CloudFormation displays Enable Termination Protection or Disable Termination Protection, based on the current termination protection setting for the stack. 3. Choose Yes, Enable or Yes, Disable. To enable or disable termination protection on a nested stack If NESTED is displayed next to the stack name, the stack is a nested stack. You can only change termination protection on the root stack to which the nested stack belongs. To change termination protection on the root stack: 1. Sign in to the AWS Management Console and open the AWS CloudFormation console at https:// console.aws.amazon.com/cloudformation/. Select the nested stack that you want. API Version 2010-05-15 106 AWS CloudFormation User Guide Viewing Deleted Stacks 2. 3. On the Overview tab, click the stack name listed as Root stack. Choose Other Actions and then choose Change Termination Protection. CloudFormation displays Enable Termination Protection or Disable Termination Protection, based on the current termination protection setting for the stack. 4. Choose Yes, Enable or Yes, Disable. To enable or disable termination protection using the command line • Use the update-termination-protection command. Controlling Who Can Change Termination Protection on Stacks To enable or disable termination protection on stacks, a user requires permission to the cloudformation:UpdateTerminationProtection action. For example, the policy below allows users to enable or disable termination protection on stacks. For more information on specifying permissions in AWS CloudFormation, see Controlling Access with AWS Identity and Access Management (p. 9). Example A sample policy that grants permissions to change stack termination protection { } "Version":"2012-10-17", "Statement":[{ "Effect":"Allow", "Action":[ "cloudformation:UpdateTerminationProtection" ], "Resource":"*" }] Viewing Deleted Stacks on the AWS CloudFormation Console By default, the AWS CloudFormation console does not display stacks in the DELETE_COMPLETE state. To display information about deleted stacks, you must change the stack view. To view deleted stacks • In the AWS CloudFormation console, select Deleted from the Filter list. AWS CloudFormation lists all of your deleted stacks (stacks with DELETE_COMPLETE status). API Version 2010-05-15 107 AWS CloudFormation User Guide Related Topics See Also • Deleting a Stack (p. 105) • Viewing Stack Data and Resources (p. 99) Related Topics • Using the AWS CLI (p. 108) Using the AWS Command Line Interface With the AWS Command Line Interface (CLI), you can create, monitor, update and delete stacks from your system's terminal. You can also use the AWS CLI to automate actions through scripts. For more information about the AWS CLI, see the AWS Command Line Interface User Guide. If you use Windows PowerShell, AWS also offers the AWS Tools for Windows PowerShell. Note The prior AWS CloudFormation CLI tools are still available, but not recommended. If you need information about the prior AWS CloudFormation CLI tools, see the AWS CloudFormation CLI Reference in the documentation archive. Topics • Creating a Stack (p. 108) • Describing and Listing Your Stacks (p. 109) • Viewing Stack Event History (p. 112) • Listing Resources (p. 114) • Retrieving a Template (p. 114) • Validating a Template (p. 115) • Uploading Local Artifacts to an S3 Bucket (p. 116) • Quickly Deploying Templates with Transforms (p. 117) • Deleting a Stack (p. 117) Creating a Stack To create a stack you run the aws cloudformation create-stack command. You must provide the stack name, the location of a valid template, and any input parameters. Parameters are separated with a space and the key names are case sensitive. If you mistype a parameter key name when you run aws cloudformation create-stack, AWS CloudFormation doesn't create the stack and reports that the template doesn't contain that parameter. Note If you specify a local template file, AWS CloudFormation uploads it to an Amazon S3 bucket in your AWS account. AWS CloudFormation creates a unique bucket for each region in which you upload a template file. The buckets are accessible to anyone with Amazon S3 permissions in your AWS account. If an AWS CloudFormation-created bucket already exists, the template is added to that bucket. You can use your own bucket and manage its permissions by manually uploading templates to Amazon S3. Then whenever you create or update a stack, specify the Amazon S3 URL of a template file. API Version 2010-05-15 108 AWS CloudFormation User Guide Describing and Listing Your Stacks By default, aws cloudformation describe-stacks returns parameter values. To prevent sensitive parameter values such as passwords from being returned, include a NoEcho property set to TRUE in your AWS CloudFormation template. The following example creates the myteststack stack: PROMPT> aws cloudformation create-stack --stack-name myteststack --template-body file:/// home/testuser/mytemplate.json --parameters ParameterKey=Parm1,ParameterValue=test1 ParameterKey=Parm2,ParameterValue=test2 { "StackId" : "arn:aws:cloudformation:us-west-2:123456789012:stack/ myteststack/330b0120-1771-11e4-af37-50ba1b98bea6" } Describing and Listing Your Stacks You can use two AWS CLI commands to get information about your AWS CloudFormation stacks: aws cloudformation list-stacks and aws cloudformation describe-stacks. Note See the section called “AWS CloudFormation Resources” (p. 11) for a discussion of how IAM policies may limit what a user can do with these two AWS CLI commands. aws cloudformation list-stacks The aws cloudformation list-stacks command enables you to get a list of any of the stacks you have created (even those which have been deleted up to 90 days). You can use an option to filter results by stack status, such as CREATE_COMPLETE and DELETE_COMPLETE. The aws cloudformation list-stacks command returns summary information about any of your running or deleted stacks, including the name, stack identifier, template, and status. Note The aws cloudformation list-stacks command returns information on deleted stacks for 90 days after they have been deleted. The following example shows a summary of all stacks that have a status of CREATE_COMPLETE: PROMPT> aws cloudformation list-stacks --stack-status-filter CREATE_COMPLETE [ { "StackId": "arn:aws:cloudformation:us-east-2:123456789012:stack/myteststack/ 644df8e0-0dff-11e3-8e2f-5088487c4896", "TemplateDescription": "AWS CloudFormation Sample Template S3_Bucket: Sample template showing how to create a publicly accessible S3 bucket. **WARNING** This template creates an S3 bucket. You will be billed for the AWS resources used if you create a stack from this template.", "StackStatusReason": null, "CreationTime": "2013-08-26T03:27:10.190Z", "StackName": "myteststack", "StackStatus": "CREATE_COMPLETE" } ] aws cloudformation describe-stacks The aws cloudformation describe-stacks command provides information on your running stacks. You can use an option to filter results on a stack name. This command returns information about the stack, including the name, stack identifier, and status. API Version 2010-05-15 109 AWS CloudFormation User Guide Describing and Listing Your Stacks The following example shows summary information for the myteststack stack: PROMPT> aws cloudformation describe-stacks --stack-name myteststack { "Stacks": [ { "StackId": "arn:aws:cloudformation:us-east-2:123456789012:stack/myteststack/ a69442d0-0b8f-11e3-8b8a-500150b352e0", "Description": "AWS CloudFormation Sample Template S3_Bucket: Sample template showing how to create a publicly accessible S3 bucket. **WARNING** This template creates an S3 bucket. You will be billed for the AWS resources used if you create a stack from this template.", "Tags": [], "Outputs": [ { "Description": "Name of S3 bucket to hold website content", "OutputKey": "BucketName", "OutputValue": "myteststack-s3bucket-jssofi1zie2w" } ], "StackStatusReason": null, "CreationTime": "2013-08-23T01:02:15.422Z", "Capabilities": [], "StackName": "myteststack", "StackStatus": "CREATE_COMPLETE", "DisableRollback": false } ] } If you don't use the --stack-name option to limit the output to one stack, information on all your running stacks is returned. Stack Status Codes You can specify one or more stack status codes to list only stacks with the specified status codes. The following table describes each stack status code: Stack Status Description CREATE_COMPLETE Successful creation of one or more stacks. CREATE_IN_PROGRESS Ongoing creation of one or more stacks. CREATE_FAILED Unsuccessful creation of one or more stacks. View the stack events to see any associated error messages. Possible reasons for a failed creation include insufficient permissions to work with all resources in the stack, parameter values rejected by an AWS service, or a timeout during resource creation. DELETE_COMPLETE Successful deletion of one or more stacks. Deleted stacks are retained and viewable for 90 days. DELETE_FAILED Unsuccessful deletion of one or more stacks. Because the delete failed, you might have some resources that are still running; however, you cannot work with or update the stack. Delete the stack again or view the stack events to see any associated error messages. DELETE_IN_PROGRESS Ongoing removal of one or more stacks. API Version 2010-05-15 110 AWS CloudFormation User Guide Describing and Listing Your Stacks Stack Status Description REVIEW_IN_PROGRESS Ongoing creation of one or more stacks with an expected StackId but without any templates or resources. Important A stack with this status code counts against the maximum possible number of stacks (p. 21). ROLLBACK_COMPLETE Successful removal of one or more stacks after a failed stack creation or after an explicitly canceled stack creation. Any resources that were created during the create stack action are deleted. This status exists only after a failed stack creation. It signifies that all operations from the partially created stack have been appropriately cleaned up. When in this state, only a delete operation can be performed. ROLLBACK_FAILED Unsuccessful removal of one or more stacks after a failed stack creation or after an explicitly canceled stack creation. Delete the stack or view the stack events to see any associated error messages. ROLLBACK_IN_PROGRESS Ongoing removal of one or more stacks after a failed stack creation or after an explicitly cancelled stack creation. UPDATE_COMPLETE Successful update of one or more stacks. UPDATE_COMPLETE_CLEANUP_IN_PROGRESS Ongoing removal of old resources for one or more stacks after a successful stack update. For stack updates that require resources to be replaced, AWS CloudFormation creates the new resources first and then deletes the old resources to help reduce any interruptions with your stack. In this state, the stack has been updated and is usable, but AWS CloudFormation is still deleting the old resources. UPDATE_IN_PROGRESS Ongoing update of one or more stacks. UPDATE_ROLLBACK_COMPLETE Successful return of one or more stacks to a previous working state after a failed stack update. UPDATE_ROLLBACK_COMPLETE_CLEANUP_IN_PROGRESS Ongoing removal of new resources for one or more stacks after a failed stack update. In this state, the stack has been rolled back to its previous working state and is usable, but AWS CloudFormation is still deleting any new resources it created during the stack update. UPDATE_ROLLBACK_FAILED Unsuccessful return of one or more stacks to a previous working state after a failed stack update. When in this state, you can delete the stack or continue rollback (p. 150). You might need to fix errors before your stack can return to a working state. Or, you can contact customer support to restore the stack to a usable state. UPDATE_ROLLBACK_IN_PROGRESS Ongoing return of one or more stacks to the previous working state after failed stack update. API Version 2010-05-15 111 AWS CloudFormation User Guide Viewing Stack Event History Viewing Stack Event History You can track the status of the resources AWS CloudFormation is creating and deleting with the aws cloudformation describe-stack-events command. The amount of time to create or delete a stack depends on the complexity of your stack. In the following example, a sample stack is created from a template file by using the aws cloudformation create-stack command. After the stack is created, the events that were reported during stack creation are shown by using the aws cloudformation describe-stack-events command. The following example creates a stack with the name myteststack using the sampletemplate.json template file: PROMPT> aws cloudformation create-stack --stack-name myteststack --template-body file:/// home/local/test/sampletemplate.json [ { "StackId": "arn:aws:cloudformation:us-east-2:123456789012:stack/ myteststack/466df9e0-0dff-08e3-8e2f-5088487c4896", "Description": "AWS CloudFormation Sample Template S3_Bucket: Sample template showing how to create a publicly accessible S3 bucket. **WARNING** This template creates an S3 bucket. You will be billed for the AWS resources used if you create a stack from this template.", "Tags": [], "Outputs": [ { "Description": "Name of S3 bucket to hold website content", "OutputKey": "BucketName", "OutputValue": "myteststack-s3bucket-jssofi1zie2w" } ], "StackStatusReason": null, "CreationTime": "2013-08-23T01:02:15.422Z", "Capabilities": [], "StackName": "myteststack", "StackStatus": "CREATE_COMPLETE", "DisableRollback": false } ] The following example describes the myteststack stack: PROMPT> aws cloudformation describe-stack-events --stack-name myteststack { "StackEvents": [ { "StackId": "arn:aws:cloudformation:us-east-2:123456789012:stack/ myteststack/466df9e0-0dff-08e3-8e2f-5088487c4896", "EventId": "af67ef60-0b8f-11e3-8b8a-500150b352e0", "ResourceStatus": "CREATE_COMPLETE", "ResourceType": "AWS::CloudFormation::Stack", "Timestamp": "2013-08-23T01:02:30.070Z", "StackName": "myteststack", "PhysicalResourceId": "arn:aws:cloudformation:us-east-2:123456789012:stack/ myteststack/a69442d0-0b8f-11e3-8b8a-500150b352e0", "LogicalResourceId": "myteststack" }, { "StackId": "arn:aws:cloudformation:us-east-2:123456789012:stack/ myteststack/466df9e0-0dff-08e3-8e2f-5088487c4896", "EventId": "S3Bucket-CREATE_COMPLETE-1377219748025", API Version 2010-05-15 112 AWS CloudFormation User Guide Viewing Stack Event History }, { "ResourceStatus": "CREATE_COMPLETE", "ResourceType": "AWS::S3::Bucket", "Timestamp": "2013-08-23T01:02:28.025Z", "StackName": "myteststack", "ResourceProperties": "{\"AccessControl\":\"PublicRead\"}", "PhysicalResourceId": "myteststack-s3bucket-jssofi1zie2w", "LogicalResourceId": "S3Bucket" "StackId": "arn:aws:cloudformation:us-east-2:123456789012:stack/ myteststack/466df9e0-0dff-08e3-8e2f-5088487c4896", "EventId": "S3Bucket-CREATE_IN_PROGRESS-1377219746688", "ResourceStatus": "CREATE_IN_PROGRESS", "ResourceType": "AWS::S3::Bucket", "Timestamp": "2013-08-23T01:02:26.688Z", "ResourceStatusReason": "Resource creation Initiated", "StackName": "myteststack", "ResourceProperties": "{\"AccessControl\":\"PublicRead\"}", "PhysicalResourceId": "myteststack-s3bucket-jssofi1zie2w", "LogicalResourceId": "S3Bucket" }, { "StackId": "arn:aws:cloudformation:us-east-2:123456789012:stack/ myteststack/466df9e0-0dff-08e3-8e2f-5088487c4896", "EventId": "S3Bucket-CREATE_IN_PROGRESS-1377219743862", "ResourceStatus": "CREATE_IN_PROGRESS", "ResourceType": "AWS::S3::Bucket", "Timestamp": "2013-08-23T01:02:23.862Z", "StackName": "myteststack", "ResourceProperties": "{\"AccessControl\":\"PublicRead\"}", "PhysicalResourceId": null, "LogicalResourceId": "S3Bucket" }, { "StackId": "arn:aws:cloudformation:us-east-2:123456789012:stack/ myteststack/466df9e0-0dff-08e3-8e2f-5088487c4896", "EventId": "a69469e0-0b8f-11e3-8b8a-500150b352e0", "ResourceStatus": "CREATE_IN_PROGRESS", "ResourceType": "AWS::CloudFormation::Stack", "Timestamp": "2013-08-23T01:02:15.422Z", "ResourceStatusReason": "User Initiated", "StackName": "myteststack", "PhysicalResourceId": "arn:aws:cloudformation:us-east-2:123456789012:stack/ myteststack/a69442d0-0b8f-11e3-8b8a-500150b352e0", "LogicalResourceId": "myteststack" } ] } Note You can run the aws cloudformation describe-stack-events command while the stack is being created to view events as they are reported. The most recent events are reported first. The following table describe the fields returned by the aws cloudformation describe-stack-events command: Field Description EventId Event identifier StackName Name of the stack that the event corresponds to StackId Identifier of the stack that the event corresponds to API Version 2010-05-15 113 AWS CloudFormation User Guide Listing Resources Field Description LogicalResourceId Logical identifier of the resource PhysicalResourceId Physical identifier of the resource ResourceProperties Properties of the resource ResourceType Type of the resource Timestamp Time when the event occurred ResourceStatus The status of the resource, which can be one of the following status codes: CREATE_COMPLETE | CREATE_FAILED | CREATE_IN_PROGRESS | DELETE_COMPLETE | DELETE_FAILED | DELETE_IN_PROGRESS | DELETE_SKIPPED | UPDATE_COMPLETE | UPDATE_FAILED | UPDATE_IN_PROGRESS. The DELETE_SKIPPED status applies to resources with a deletion policy attribute of retain. ResourceStatusReason More information on the status Listing Resources Immediately after you run the aws cloudformation create-stack command, you can list its resources using the aws cloudformation list-stack-resources command. This command lists a summary of each resource in the stack that you specify with the --stack-name parameter. The report includes a summary of the stack, including the creation or deletion status. The following example shows the resources for the myteststack stack: PROMPT> aws cloudformation list-stack-resources --stack-name myteststack { "StackResourceSummaries": [ { "ResourceStatus": "CREATE_COMPLETE", "ResourceType": "AWS::S3::Bucket", "ResourceStatusReason": null, "LastUpdatedTimestamp": "2013-08-23T01:02:28.025Z", "PhysicalResourceId": "myteststack-s3bucket-sample", "LogicalResourceId": "S3Bucket" } ] } AWS CloudFormation reports resource details on any running or deleted stack. If you specify the name of a stack whose status is CREATE_IN_PROCESS, AWS CloudFormation reports only those resources whose status is CREATE_COMPLETE. Note The aws cloudformation describe-stack-resources command returns information on deleted stacks for 90 days after they have been deleted. Retrieving a Template AWS CloudFormation stores the template you use to create your stack as part of the stack. You can retrieve the template from AWS CloudFormation using the aws cloudformation get-template command. API Version 2010-05-15 114 AWS CloudFormation User Guide Validating a Template Note The aws cloudformation get-template command returns the deleted stacks templates for up to 90 days after the stack has been deleted. The following example shows the template for the myteststack stack: PROMPT> aws cloudformation get-template --stack-name myteststack { "TemplateBody": { "AWSTemplateFormatVersion": "2010-09-09", "Outputs": { "BucketName": { "Description": "Name of S3 bucket to hold website content", "Value": { "Ref": "S3Bucket" } } }, "Description": "AWS CloudFormation Sample Template S3_Bucket: Sample template showing how to create a publicly accessible S3 bucket. **WARNING** This template creates an S3 bucket. You will be billed for the AWS resources used if you create a stack from this template.", "Resources": { "S3Bucket": { "Type": "AWS::S3::Bucket", "Properties": { "AccessControl": "PublicRead" } } } } } The output contains the entire template body, enclosed in quotation marks. Validating a Template To check your template file for syntax errors, you can use the aws cloudformation validatetemplate command. Note The aws cloudformation validate-template command is designed to check only the syntax of your template. It does not ensure that the property values that you have specified for a resource are valid for that resource. Nor does it determine the number of resources that will exist when the stack is created. To check the operational validity, you need to attempt to create the stack. There is no sandbox or test area for AWS CloudFormation stacks, so you are charged for the resources you create during testing. During validation, AWS CloudFormation first checks if the template is valid JSON. If it isn't, AWS CloudFormation checks if the template is valid YAML. If both checks fail, AWS CloudFormation returns a template validation error. You can validate templates locally by using the --template-body parameter, or remotely with the --template-url parameter. The following example validates a template in a remote location: PROMPT> aws cloudformation validate-template --template-url https://s3.amazonaws.com/ cloudformation-templates-us-east-1/S3_Bucket.template { "Description": "AWS CloudFormation Sample Template S3_Bucket: Sample template showing how to create a publicly accessible S3 bucket. **WARNING** This template creates an S3 bucket. API Version 2010-05-15 115 AWS CloudFormation User Guide Uploading Local Artifacts to an S3 Bucket You will be billed for the AWS resources used if you create a stack from this template.", "Parameters": [], "Capabilities": [] } The expected result is no error message, with information about all parameters listed. The following example shows an error with a local template file: PROMPT> aws cloudformation validate-template --template-body file:///home/local/test/ sampletemplate.json { "ResponseMetadata": { "RequestId": "4ae33ec0-1988-11e3-818b-e15a6df955cd" }, "Errors": [ { "Message": "Template format error: JSON not well-formed. (line 11, column 8)", "Code": "ValidationError", "Type": "Sender" } ], "Capabilities": [], "Parameters": [] } A client error (ValidationError) occurred: Template format error: JSON not well-formed. (line 11, column 8) Uploading Local Artifacts to an S3 Bucket For some resource properties that require an Amazon S3 location (a bucket name and filename), you can specify local references instead. For example, you might specify the S3 location of your AWS Lambda function's source code or an Amazon API Gateway REST API's OpenAPI (formerly Swagger) file. Instead of manually uploading the files to an S3 bucket and then adding the location to your template, you can specify local references, called local artifacts, in your template and then use the package command to quickly upload them. A local artifact is a path to a file or folder that the package command uploads to Amazon S3. For example, an artifact can be a local path to your AWS Lambda function's source code or an Amazon API Gateway REST API's OpenAPI file. If you specify a file, the command directly uploads it to the S3 bucket. After uploading the artifacts, the command returns a copy of your template, replacing references to local artifacts with the S3 location where the command uploaded the artifacts. Then, you can use the returned template to create or update a stack. If you specify a folder, the command creates a .zip file for the folder, and then uploads the .zip file. If you don’t specify a path, the command creates a .zip file for the working directory, and uploads it. You can specify an absolute or relative path, where the relative path is relative to your template’s location. You can use local artifacts only for resource properties that the package command supports. For more information about this command and a list of the supported resource properties, see the aws cloudformation package command in the AWS CLI Command Reference. The following template specifies the local artifact for a Lambda function's source code. The source code is stored in the user's /home/user/code/lambdafunction folder. Original Template AWSTemplateFormatVersion: '2010-09-09' Transform: 'AWS::Serverless-2016-10-31' API Version 2010-05-15 116 AWS CloudFormation User Guide Quickly Deploying Templates with Transforms Resources: MyFunction: Type: 'AWS::Serverless::Function' Properties: Handler: index.handler Runtime: nodejs4.3 CodeUri: /home/user/code/lambdafunction The following command creates a .zip file containing the function's source code folder, and then uploads the .zip file to the root folder of the my-bucket bucket. Package Command aws cloudformation package --template /path_to_template/template.json --s3-bucket mybucket --output json > packaged-template.json The command saves the template that it generates to the path specified by the --output option. The command replaces the artifact with the S3 location, as shown in the following example: Resulting Template AWSTemplateFormatVersion: '2010-09-09' Transform: 'AWS::Serverless-2016-10-31' Resources: MyFunction: Type: 'AWS::Serverless::Function' Properties: Handler: index.handler Runtime: nodejs4.3 CodeUri: s3://mybucket/lambdafunction.zip Quickly Deploying Templates with Transforms AWS CloudFormation requires you to use a change set to create a template that includes transforms. Instead of independently creating and then executing a change set, use the aws cloudformation deploy command. When you run this command, it creates a change set, executes the change set, and then terminates. This command reduces the numbers of required steps when you create or update a stack that includes transforms. The following command creates a new stack by using the my-template.json template. aws cloudformation deploy --template /path_to_template/my-template.json --stack-name mynew-stack --parameter-overrides Key1=Value1 Key2=Value2 For more information, see the aws cloudformation deploy command in the AWS CLI Command Reference Deleting a Stack To delete a stack, you run the aws cloudformation delete-stack command. You must specify the name of the stack that you want to delete. When you delete a stack, you delete the stack and all of its resources. The following example deletes the myteststack stack: PROMPT> aws cloudformation delete-stack --stack-name myteststack API Version 2010-05-15 117 AWS CloudFormation User Guide Stack Updates Note You cannot delete a stack that has termination protection enabled. For more information, see Protecting a Stack From Being Deleted (p. 106) AWS CloudFormation Stacks Updates When you need to make changes to a stack's settings or change its resources, you update the stack instead of deleting it and creating a new stack. For example, if you have a stack with an EC2 instance, you can update the stack to change the instance's AMI ID. When you update a stack, you submit changes, such as new input parameter values or an updated template. AWS CloudFormation compares the changes you submit with the current state of your stack and updates only the changed resources. For a summary of the update workflow, see How Does AWS CloudFormation Work? (p. 5). Note When updating a stack, AWS CloudFormation might interrupt resources or replace updated resources, depending on which properties you update. For more information about resource update behaviors, see Update Behaviors of Stack Resources (p. 118). Update Methods AWS CloudFormation provides two methods for updating stacks: direct update or creating and executing change sets. When you directly update a stack, you submit changes and AWS CloudFormation immediately deploys them. Use direct updates when you want to quickly deploy your updates. With change sets, you can preview the changes AWS CloudFormation will make to your stack, and then decide whether to apply those changes. Change sets are JSON-formatted documents that summarize the changes AWS CloudFormation will make to a stack. Use change sets when you want to ensure that AWS CloudFormation doesn't make unintentional changes or when you want to consider several options. For example, you can use a change set to verify that AWS CloudFormation won't replace your stack's database instances during an update. Topics • Update Behaviors of Stack Resources (p. 118) • Modifying a Stack Template (p. 119) • Updating Stacks Using Change Sets (p. 122) • Updating Stacks Directly (p. 136) • Monitoring the Progress of a Stack Update (p. 139) • Canceling a Stack Update (p. 140) • Prevent Updates to Stack Resources (p. 141) • Continue Rolling Back an Update (p. 150) Update Behaviors of Stack Resources When you submit an update, AWS CloudFormation updates resources based on differences between what you submit and the stack's current template. Resources that have not changed run without disruption during the update process. For updated resources, AWS CloudFormation uses one of the following update behaviors: Update with No Interruption AWS CloudFormation updates the resource without disrupting operation of that resource and without changing the resource's physical ID. For example, if you update any property on an AWS::CloudTrail::Trail (p. 708) resource, AWS CloudFormation updates the trail without disruption. API Version 2010-05-15 118 AWS CloudFormation User Guide Modifying a Stack Template Updates with Some Interruption AWS CloudFormation updates the resource with some interruption and retains the physical ID. For example, if you update certain properties on an AWS::EC2::Instance (p. 879) resource, the instance might have some interruption while AWS CloudFormation and Amazon EC2 reconfigure the instance. Replacement AWS CloudFormation recreates the resource during an update, which also generates a new physical ID. AWS CloudFormation creates the replacement resource first, changes references from other dependent resources to point to the replacement resource, and then deletes the old resource. For example, if you update the Engine property of an AWS::RDS::DBInstance (p. 1341) resource type, AWS CloudFormation creates a new resource and replaces the current DB instance resource with the new one. The method AWS CloudFormation uses depends on which property you update for a given resource type. The update behavior for each property is described in the AWS Resource Types Reference (p. 499). Depending on the update behavior, you can decide when to modify resources to reduce the impact of these changes on your application. In particular, you can plan when resources must be replaced during an update. For example, if you update the Port property of an AWS::RDS::DBInstance (p. 1341) resource type, AWS CloudFormation replaces the DB instance by creating a new DB instance with the updated port setting and deletes the old DB instance. Before the update, you might plan to do the following to prepare for the database replacement: • Take a snapshot of the current databases. • Prepare a strategy for how applications that use that DB instance will handle an interruption while the DB instance is being replaced. • Ensure that the applications that use that DB instance take into account the updated port setting and any other updates you have made. • Use the DB snapshot to restore the databases on the new DB instance. This example is not exhaustive; it's meant to give you an idea of the things to plan for when a resource is replaced during an update. Note If the template includes one or more nested stacks (p. 694), AWS CloudFormation also initiates an update for every nested stack. This is necessary to determine whether the nested stacks have been modified. AWS CloudFormation updates only those resources in the nested stacks that have changes specified in corresponding templates. Modifying a Stack Template If you want to modify resources and properties that are declared in a stack template, you must modify the stack's template. To ensure that you update only the resources that you intend to update, use the template for the existing stack as a starting point and make your updates to that template. If you are managing your template in a source control system, use a copy of that template as a starting point. Otherwise, you can get a copy of a stack template from AWS CloudFormation. If you want to modify just the parameters or settings of a stack (like a stack's Amazon SNS topic), you can reuse the existing stack template. You don't need to get a copy of the stack template or make modifications to the stack template. Note If your template includes an unsupported change, AWS CloudFormation returns a message saying that the change is not permitted. This message might occur asynchronously, however, because resources are created and updated by AWS CloudFormation in a non-deterministic order by default. API Version 2010-05-15 119 AWS CloudFormation User Guide Modifying a Stack Template Topics • Update a Stack's Template (Console) (p. 120) • Get and Update a Template for a Stack (CLI) (p. 121) Update a Stack's Template (Console) 1. In the AWS CloudFormation console, select the stack that you want to update and then choose the Actions and then View in Designer. AWS CloudFormation opens a copy of the stack's template in AWS CloudFormation Designer. 2. Modify the template. You can use the AWS CloudFormation Designer drag-and-drop interface or the integrated JSON and YAML editor to modify the template. For more information about using AWS CloudFormation Designer, see What Is AWS CloudFormation Designer? (p. 202). Modify only the resources that you want to update. Use the same values as the current stack configuration for resources and properties that you aren't updating. You can modify the template by completing any of the following actions: • Add new resources, or remove existing resources. For most resources, changing the logical name of a resource is equivalent to deleting that resource and replacing it with a new one. Any other resources that depend on the renamed resource also need to be updated and might cause them to be replaced. Other resources require you to update a property (not just the logical name) in order to trigger an update. • Add, modify, or delete properties of existing resources. Consult the AWS Resource Types Reference (p. 499) for information about the effects of updating particular resource properties. For each property, the effects of an update will be one of the following: • Update requires: No interruption (p. 118) • Update requires: Some interruptions (p. 119) • Update requires: Replacement (p. 119) • Add, modify, or delete attributes for resources (Metadata, DependsOn, CreationPolicy, UpdatePolicy, and DeletionPolicy). Important You cannot update the CreationPolicy, DeletionPolicy. or UpdatePolicy attribute by itself. You can update them only when you include changes that add, modify, or delete resources. For example, you can add or modify a metadata attribute of a resource. API Version 2010-05-15 120 AWS CloudFormation User Guide Modifying a Stack Template • Add, modify, or delete parameter declarations. However, you cannot add, modify, or delete a parameter that is used by a resource that does not support updates. • Add, modify, or delete mapping declarations. Important If the values in a mapping are not being used by your stack, you can't update the mapping by itself. You need to include changes that add, modify, or delete resources. For example, you can add or modify a metadata attribute of a resource. If you update a mapping value that your stack is using, you don't need to make any other changes to trigger an update. • Add, modify, or delete condition declarations. Important You cannot update conditions by themselves. You can update conditions only when you include changes that add, modify, or delete resources. For example, you can add or modify a metadata attribute of a resource. • Add, modify, or delete output value declarations. Some resources or properties may have constraints on property values or changes to those values. For example, changes to the AllocatedStorage property of an AWS::RDS::DBInstance (p. 1341) resource must be greater than the current setting. If the value specified for the update does not meet those constraints, the update for that resource fails. For the specific constraints on AllocatedStorage changes, see ModifyDBInstance. Updates to a resource can affect the properties of other resources. If you used the Ref function (p. 2311) or the Fn::GetAtt function (p. 2285) to specify an attribute from an updated resource as part of a property value in another resource in the template, AWS CloudFormation also updates the resource that contains the reference to the property that has changed. For example, if you updated the MasterUsername property of an AWS::RDS::DBInstance resource and you had an AWS::AutoScaling::LaunchConfiguration resource that had a UserData property that contained a reference to the DB instance name using the Ref function, AWS CloudFormation would recreate the DB instance with a new name and also update the LaunchConfiguration resource. 3. To check for syntax errors in your template, from the AWS CloudFormation Designer toolbar, choose Validate template ( ). View and fix any errors in the Messages pane, and then validate the template again. If you don't see any errors, your template is syntactically valid. 4. From the AWS CloudFormation Designer toolbar, choose the File menu ( the template in an S3 bucket or locally. ) and then Save to save Get and Update a Template for a Stack (CLI) 1. To get the template for the stack you want to update, use the command aws cloudformation get-template. 2. Copy the template, paste it into a text file, modify it, and save it. Copy only the template. The command encloses the template in quotation marks, but do not copy the quotation marks surrounding the template. The template itself starts with an open brace and ends with the final close brace. Specify changes to the stack's resources in this file. API Version 2010-05-15 121 AWS CloudFormation User Guide Updating Stacks Using Change Sets Updating Stacks Using Change Sets When you need to update a stack, understanding how your changes will affect running resources before you implement them can help you update stacks with confidence. Change sets allow you to preview how proposed changes to a stack might impact your running resources, for example, whether your changes will delete or replace any critical resources, AWS CloudFormation makes the changes to your stack only when you decide to execute the change set, allowing you to decide whether to proceed with your proposed changes or explore other changes by creating another change set. You can create and manage change sets using the AWS CloudFormation console, AWS CLI, or AWS CloudFormation API. Topics • Creating a Change Set (p. 123) • Viewing a Change Set (p. 125) • Executing a Change Set (p. 127) • Deleting a Change Set (p. 129) • Example Change Sets (p. 129) Important Change sets don't indicate whether AWS CloudFormation will successfully update a stack. For example, a change set doesn't check if you will surpass an account limit (p. 21), if you're updating a resource (p. 499) that doesn't support updates, or if you have insufficient permissions (p. 9) to modify a resource, all of which can cause a stack update to fail. If an update fails, AWS CloudFormation attempts to roll back your resources to their original state. Change Set Overview The following diagram summarizes how you use change sets to update a stack: 1. Create a change set by submitting changes for the stack that you want to update. You can submit a modified stack template or modified input parameter values. AWS CloudFormation compares your stack with the changes that you submitted to generate the change set; it doesn't make changes to your stack at this point. 2. View the change set to see which stack settings and resources will change. For example, you can see which resources AWS CloudFormation will add, modify, or delete. 3. Optional: If you want to consider other changes before you decide which changes to make, create additional change sets. Creating multiple change sets helps you understand and evaluate how different changes will affect your resources. You can create as many change sets as you need. 4. Execute the change set that contains the changes that you want to apply to your stack. AWS CloudFormation updates your stack with those changes. Note After you execute a change, AWS CloudFormation removes all change sets that are associated with the stack because they aren't applicable to the updated stack. You can also delete change sets to prevent executing a change set that shouldn't be applied. API Version 2010-05-15 122 AWS CloudFormation User Guide Updating Stacks Using Change Sets Creating a Change Set To create a change set for a running stack, submit the changes that you want to make by providing a modified template, new input parameter values, or both. AWS CloudFormation generates a change set by comparing your stack with the changes you submitted. To modify a template, for example to add a new resource to your stack, modify a copy of the current template before creating the change set. For more information, see Modifying a Stack Template (p. 119). To create a change set (console) 1. In the AWS CloudFormation console, from the list of stacks, select the running stack for which you want to create a change set. 2. Choose Actions, and then choose Create Change Set. 3. If you modified the stack template, specify the location of the updated template. If not, select Use current template. • For a template stored locally on your computer, select Upload a template to Amazon S3. Choose Choose File to navigate to the file and select it, and then click Next. • For a template stored in an Amazon S3 bucket, select Specify an Amazon S3 URL. Enter or paste the URL for the template, and then click Next. If you have a template in a versioning-enabled bucket, you can specify a specific version of the template, such as https://s3.amazonaws.com/templates/myTemplate.template? versionId=123ab1cdeKdOW5IH4GAcYbEngcpTJTDW. For more information, see Managing Objects in a Versioning-Enabled Bucket in the Amazon Simple Storage Service Console User Guide. 4. On the Specify Details page, type information about the change set and, if necessary, modify the parameter values that you want to change, and then choose Next. In the Specify Details section, specify a name for the change set. You can also specify a description of the change set to identify its purpose. If your template contains parameters, in the Parameters section, change applicable parameter values. If you're reusing the stack's template, AWS CloudFormation populates each parameter with the current value in the stack,with the exception of parameters declared with the NoEcho attribute. To use existing values for those parameters, select Use existing value. 5. On the Options page, you can update the stack's service role, the stack tags, or the stack's Amazon SNS notification topic, as applicable, and then choose Next. 6. Review the changes for this change set. If the template includes AWS Identity and Access Management (IAM) resources, select I acknowledge that this template may create IAM resources to acknowledge that AWS CloudFormation might create IAM resources if you execute this change set. IAM resources can modify permissions in your AWS account; review these resources to ensure that you're permitting only the actions that you intend. For more information, see Controlling Access with AWS Identity and Access Management (p. 9). API Version 2010-05-15 123 AWS CloudFormation User Guide Updating Stacks Using Change Sets 7. Choose Create change set. You're redirected to the change set's detail page. While AWS CloudFormation generates the change set, the status of the change set is CREATE_IN_PROGRESS. After it has created the change set, AWS CloudFormation sets the status to CREATE_COMPLETE. In the Changes section, AWS CloudFormation lists all of the changes that it will make to your stack. For more information, see Viewing a Change Set (p. 125). If AWS CloudFormation fails to create the change set (reports FAILED status), fix the error displayed in the Status field, and recreate the change set. To create a change set (AWS CLI) • Run the aws cloudformation create-change-set command. You submit your changes as command options. You can specify new parameter values, a modified template, or both. For example, the following command creates a change set named SampleChangeSet for the SampleStack stack. The change set uses the current stack's template, but with a different value for the Purpose parameter: aws cloudformation create-change-set --stack-name arn:aws:cloudformation:useast-1:123456789012:stack/SampleStack/1a2345b6-0000-00a0-a123-00abc0abc000 --change-set-name SampleChangeSet --use-previous-template -parameters ParameterKey="InstanceType",UsePreviousValue=true API Version 2010-05-15 124 AWS CloudFormation User Guide Updating Stacks Using Change Sets ParameterKey="KeyPairName",UsePreviousValue=true ParameterKey="Purpose",ParameterValue="production" Viewing a Change Set After you create a change set, you can view the proposed changes before executing them. You can use the AWS CloudFormation console, AWS CLI, or AWS CloudFormation API to view change sets. The AWS CloudFormation console provides a summary of the changes and a detailed list of changes in JSON format. The AWS CLI and AWS CloudFormation API return a detailed list of changes in JSON format. To view a change (console) 1. In the AWS CloudFormation console, choose the stack that has the change set that you want to view. 2. In the stack detail pane, choose Change Sets to view a list of the stack's change sets. 3. Choose the change set that you want view. The AWS CloudFormation console directs you to the change set's detail page, where you can see the time the change set was created, its status, the input used to generate the change set, and a summary of changes. In the Changes section, each line represents a resource that AWS CloudFormation will add, delete, or modify. AWS CloudFormation adds a resource when you add a resource to the stack's template. AWS CloudFormation deletes a resource when you delete an existing resource from the stack's template. AWS CloudFormation modifies a resource when you change the properties of a resource. Note that a modification can cause the resource to be interrupted or replaced (recreated). For more information about resource update behaviors, see Update Behaviors of Stack Resources (p. 118). To focus on specific changes, use the filter view. For example, filter for a specific resource type, such as AWS::EC2::Instance. To filter for a specific resource, specify its logical or physical ID, such as myWebServer or i-123abcd4. If you want to consider other changes before you decide which changes to make, create additional change sets. To view a change set (AWS CLI) 1. To get the ID of the change set, run the aws cloudformation list-change-sets command. Specify the stack ID of the stack that has the change set that you want to view, as shown in the following example: API Version 2010-05-15 125 AWS CloudFormation User Guide Updating Stacks Using Change Sets aws cloudformation list-change-sets --stack-name arn:aws:cloudformation:useast-1:123456789012:stack/SampleStack/1a2345b6-0000-00a0-a123-00abc0abc000 AWS CloudFormation returns a list of change sets, similar to the following: { "Summaries": [ { "StackId": "arn:aws:cloudformation:us-east-1:123456789012:stack/ SampleStack/1a2345b6-0000-00a0-a123-00abc0abc000", "Status": "CREATE_COMPLETE", "ChangeSetName": "SampleChangeSet", "CreationTime": "2016-03-16T20:44:05.889Z", "StackName": "SampleStack", "ChangeSetId": "arn:aws:cloudformation:us-east-1:123456789012:changeSet/ SampleChangeSet/1a2345b6-0000-00a0-a123-00abc0abc000" }, { "StackId": "arn:aws:cloudformation:us-east-1:123456789012:stack/ SampleStack/1a2345b6-0000-00a0-a123-00abc0abc000", "Status": "CREATE_COMPLETE", "ChangeSetName": "SampleChangeSet-conditional", "CreationTime": "2016-03-16T21:15:56.398Z", "StackName": "SampleStack", "ChangeSetId": "arn:aws:cloudformation:us-east-1:123456789012:changeSet/ SampleChangeSet-conditional/1a2345b6-0000-00a0-a123-00abc0abc000" }, { "StackId": "arn:aws:cloudformation:us-east-1:123456789012:stack/ SampleStack/1a2345b6-0000-00a0-a123-00abc0abc000", "Status": "CREATE_COMPLETE", "ChangeSetName": "SampleChangeSet-replacement", "CreationTime": "2016-03-16T21:03:37.706Z", "StackName": "SampleStack", "ChangeSetId": "arn:aws:cloudformation:us-east-1:123456789012:changeSet/ SampleChangeSet-replacement/1a2345b6-0000-00a0-a123-00abc0abc000" } ] } 2. Run the aws cloudformation describe-change-set command, specifying the ID of the change set that you want to view. For example: aws cloudformation describe-change-set --change-set-name arn:aws:cloudformation:useast-1:123456789012:changeSet/SampleChangeSet/1a2345b6-0000-00a0-a123-00abc0abc000 AWS CloudFormation returns information about the specified change set: { "StackId": "arn:aws:cloudformation:us-east-1:123456789012:stack/ SampleStack/1a2345b6-0000-00a0-a123-00abc0abc000", "Status": "CREATE_COMPLETE", "ChangeSetName": "SampleChangeSet-direct", "Parameters": [ { "ParameterValue": "testing", "ParameterKey": "Purpose" }, { "ParameterValue": "ellioty-useast1", "ParameterKey": "KeyPairName" API Version 2010-05-15 126 AWS CloudFormation User Guide Updating Stacks Using Change Sets }, { "ParameterValue": "t2.micro", "ParameterKey": "InstanceType" } ], "Changes": [ { "ResourceChange": { "ResourceType": "AWS::EC2::Instance", "PhysicalResourceId": "i-1abc23d4", "Details": [ { "ChangeSource": "DirectModification", "Evaluation": "Static", "Target": { "Attribute": "Tags", "RequiresRecreation": "Never" } } ], "Action": "Modify", "Scope": [ "Tags" ], "LogicalResourceId": "MyEC2Instance", "Replacement": "False" }, "Type": "Resource" } ], "CreationTime": "2016-03-17T23:35:25.813Z", "Capabilities": [], "StackName": "SampleStack", "NotificationARNs": [], "ChangeSetId": "arn:aws:cloudformation:us-east-1:123456789012:changeSet/ SampleChangeSet-direct/9edde307-960d-4e6e-ad66-b09ea2f20255" } The Changes key lists changes to resources. If you were to execute this change set, AWS CloudFormation would update the tags of the i-1abc23d4 EC2 instance. For a description of each field, see the Change data type in the AWS CloudFormation API Reference. For additional examples of change sets, see Example Change Sets (p. 129). Executing a Change Set To make the changes described in a change set to your stack, execute the change set. Important After you execute a change set, AWS CloudFormation deletes all change sets that are associated with the stack because they aren't valid for the updated stack. If an update fails, you need to create a new change set. Stack Policies and Executing a Change Set If you execute a change set on a stack that has a stack policy associated with it, AWS CloudFormation enforces the policy when it updates the stack. You can't specify a temporary stack policy that overrides the existing policy when you execute a change set. To update a protected resource, you must update the stack policy or use the direct update (p. 136) method. API Version 2010-05-15 127 AWS CloudFormation User Guide Updating Stacks Using Change Sets To execute a change set (console) 1. In the AWS CloudFormation console, choose the stack that you want to update. 2. In the stack detail pane, choose Change Sets to view a list of the stack's change sets. 3. Choose the change set that you want execute. The AWS CloudFormation console directs you to the detail page of the change set. 4. Choose Execute. 5. Confirm that this is the change set you want to execute, and then choose Execute. AWS CloudFormation immediately starts updating the stack. You can monitor the progress of the update by viewing the Events (p. 99) tab. To execute a change set (AWS CLI) • Run the aws cloudformation execute-change-set command. Specify the change set ID of the change set that you want to execute, as shown in the following example: aws cloudformation execute-change-set --change-set-name arn:aws:cloudformation:useast-1:123456789012:changeSet/SampleChangeSet/1a2345b6-0000-00a0-a123-00abc0abc000 The command in the example executes a change set with the ID arn:aws:cloudformation:useast-1:123456789012:changeSet/SampleChangeSet/1a2345b6-0000-00a0a123-00abc0abc000. After you run the command, AWS CloudFormation starts updating the stack. To view the stack's progress, use the aws cloudformation describe-stacks (p. 109) command. API Version 2010-05-15 128 AWS CloudFormation User Guide Updating Stacks Using Change Sets Deleting a Change Set Deleting a change set removes it from the list of change sets for the stack. Deleting a change set prevents you or another user from accidentally executing a change set that shouldn't be applied. AWS CloudFormation retains all change sets until you update the stack unless you delete them. To delete a change set (console) 1. In the AWS CloudFormation console, choose the stack that contains the change set that you want to delete. 2. 3. In the stack detail pane, choose Change Sets to view a list of the stack's change sets. Choose the change set that you want delete. The AWS CloudFormation console directs you to the detail page for the change set. 4. Choose Other Actions, and then choose Delete. 5. Confirm that this is the change set you want to delete, and then choose Delete. AWS CloudFormation deletes the change set from the stack's list of change sets. To delete a change set (AWS CLI) • Run the aws cloudformation delete-change-set command, specifying the ID of the change set that you want to delete, as shown in the following example: aws cloudformation delete-change-set --change-set-name arn:aws:cloudformation:useast-1:123456789012:changeSet/SampleChangeSet/1a2345b6-0000-00a0-a123-00abc0abc000 Example Change Sets This section provides examples of the change sets that AWS CloudFormation would create for common stack changes. They show how to edit a template directly; modify a single input parameter; plan for resource recreation (replacements), which prevents you from losing data that wasn't backed up or interrupting applications that are running in your stack; and add and remove resources. To illustrate how change sets work, we'll walk through the changes that were submitted and discuss the resulting change set. Because each example builds on and assumes that you understand the previous example, we recommend that you read them in order. For a description of each field in a change set, see the Change data type in the AWS CloudFormation API Reference. You can use the console (p. 125), AWS CLI, or AWS CloudFormation API to view change set details. We generated each of the following change sets from a stack with the following sample template: { "AWSTemplateFormatVersion" : "2010-09-09", "Description" : "A sample EC2 instance template for testing change sets.", "Parameters" : { "Purpose" : { API Version 2010-05-15 129 AWS CloudFormation User Guide Updating Stacks Using Change Sets "Type" : "String", "Default" : "testing", "AllowedValues" : ["testing", "production"], "Description" : "The purpose of this instance." }, "KeyPairName" : { "Type": "AWS::EC2::KeyPair::KeyName", "Description" : "Name of an existing EC2 KeyPair to enable SSH access to the instance" }, "InstanceType" : { "Type" : "String", "Default" : "t2.micro", "AllowedValues" : ["t2.micro", "t2.small", "t2.medium"], "Description" : "The EC2 instance type." } }, "Resources" : { "MyEC2Instance" : { "Type" : "AWS::EC2::Instance", "Properties" : { "KeyName" : { "Ref" : "KeyPairName" }, "InstanceType" : { "Ref" : "InstanceType" }, "ImageId" : "ami-8fcee4e5", "Tags" : [ { "Key" : "Purpose", "Value" : { "Ref" : "Purpose" } } ] } } } } Directly Editing a Template When you directly modify resources in the stack's template to generate a change set, AWS CloudFormation classifies the change as a direct modification, as opposed to changes trigged by an updated parameter value. The following change set, which added a new tag to the i-1abc23d4 instance, is an example of a direct modification. All other input values, such as the parameter values and capabilities, are unchanged, so we'll focus on the Changes structure. { "StackId": "arn:aws:cloudformation:us-east-1:123456789012:stack/ SampleStack/1a2345b6-0000-00a0-a123-00abc0abc000", "Status": "CREATE_COMPLETE", "ChangeSetName": "SampleChangeSet-direct", "Parameters": [ { "ParameterValue": "testing", "ParameterKey": "Purpose" }, { "ParameterValue": "MyKeyName", "ParameterKey": "KeyPairName" }, { "ParameterValue": "t2.micro", "ParameterKey": "InstanceType" } ], "Changes": [ { API Version 2010-05-15 130 AWS CloudFormation User Guide Updating Stacks Using Change Sets "ResourceChange": { "ResourceType": "AWS::EC2::Instance", "PhysicalResourceId": "i-1abc23d4", "Details": [ { "ChangeSource": "DirectModification", "Evaluation": "Static", "Target": { "Attribute": "Tags", "RequiresRecreation": "Never" } } ], "Action": "Modify", "Scope": [ "Tags" ], "LogicalResourceId": "MyEC2Instance", "Replacement": "False" }, "Type": "Resource" } ], "CreationTime": "2016-03-17T23:35:25.813Z", "Capabilities": [], "StackName": "SampleStack", "NotificationARNs": [], "ChangeSetId": "arn:aws:cloudformation:us-east-1:123456789012:changeSet/ SampleChangeSet-direct/1a2345b6-0000-00a0-a123-00abc0abc000" } In the Changes structure, there's only one ResourceChange structure. This structure describes information such as the type of resource AWS CloudFormation will change, the action AWS CloudFormation will take, the ID of the resource, the scope of the change, and whether the change requires a replacement (where AWS CloudFormation creates a new resource and then deletes the old one). In the example, the change set indicates that AWS CloudFormation will modify the Tags attribute of the i-1abc23d4 EC2 instance, and doesn't require the instance to be replaced. In the Details structure, AWS CloudFormation labels this change as a direct modification that will never require the instance to be recreated (replaced). You can confidently execute this change, knowing that AWS CloudFormation won't replace the instance. AWS CloudFormation shows this change as a Static evaluation. A static evaluation means that AWS CloudFormation can determine the tag's value before executing the change set. In some cases, AWS CloudFormation can determine a value only after you execute a change set. AWS CloudFormation labels those changes as Dynamic evaluations. For example, if you reference an updated resource that is conditionally replaced, AWS CloudFormation can't determine whether the reference to the updated resource will change. Modifying an Input Parameter Value When you modify an input parameter value, AWS CloudFormation generates two changes for each resource that uses the updated parameter value. In this example, we want to highlight what those changes look like and which information you should focus on. The following example was generated by changing the value of the Purpose input parameter only. The Purpose parameter specifies a tag key value for the EC2 instance. In the example, the parameter value was changed from testing to production. The new value is shown in the Parameters structure. { API Version 2010-05-15 131 AWS CloudFormation User Guide Updating Stacks Using Change Sets "StackId": "arn:aws:cloudformation:us-east-1:123456789012:stack/ SampleStack/1a2345b6-0000-00a0-a123-00abc0abc000", "Status": "CREATE_COMPLETE", "ChangeSetName": "SampleChangeSet", "Parameters": [ { "ParameterValue": "production", "ParameterKey": "Purpose" }, { "ParameterValue": "MyKeyName", "ParameterKey": "KeyPairName" }, { "ParameterValue": "t2.micro", "ParameterKey": "InstanceType" } ], "Changes": [ { "ResourceChange": { "ResourceType": "AWS::EC2::Instance", "PhysicalResourceId": "i-1abc23d4", "Details": [ { "ChangeSource": "DirectModification", "Evaluation": "Dynamic", "Target": { "Attribute": "Tags", "RequiresRecreation": "Never" } }, { "CausingEntity": "Purpose", "ChangeSource": "ParameterReference", "Evaluation": "Static", "Target": { "Attribute": "Tags", "RequiresRecreation": "Never" } } ], "Action": "Modify", "Scope": [ "Tags" ], "LogicalResourceId": "MyEC2Instance", "Replacement": "False" }, "Type": "Resource" } ], "CreationTime": "2016-03-16T23:59:18.447Z", "Capabilities": [], "StackName": "SampleStack", "NotificationARNs": [], "ChangeSetId": "arn:aws:cloudformation:us-east-1:123456789012:changeSet/ SampleChangeSet/1a2345b6-0000-00a0-a123-00abc0abc000" } The Changes structure functions similar to way it does in the Directly Editing a Template (p. 130) example. There's only one ResourceChange structure; it describes a change to the Tags attribute of the i-1abc23d4 EC2 instance. API Version 2010-05-15 132 AWS CloudFormation User Guide Updating Stacks Using Change Sets However, in the Details structure, the change set shows two changes for the Tags attribute, even though only a single parameter value was changed. Resources that reference a changed parameter value (using the Ref intrinsic function) always result in two changes: one with a Dynamic evaluation and another with a Static evaluation. You can see these types of changes by viewing the following fields: • For the Static evaluation change, view the ChangeSource field. In this example, the ChangeSource field equals ParameterReference, meaning that this change is a result of an updated parameter reference value. The change set must contain a similar Dynamic evaluation change. • You can find the matching Dynamic evaluation change by comparing the Target structure for both changes, which will contain the same information. In this example, the Target structures for both changes contain the same values for the Attribute and RequireRecreation fields. For these types of changes, focus on the static evaluation, which gives you the most detailed information about the change. In this example, the static evaluation shows that the change is the result of a change in a parameter reference value (ParameterReference). The exact parameter that was changed is indicated by the CauseEntity field (the Purpose parameter). Determining the Value of the Replacement Field The Replacement field in a ResourceChange structure indicates whether AWS CloudFormation will recreate the resource. Planning for resource recreation (replacements) prevents you from losing data that wasn't backed up or interrupting applications that are running in your stack. The value in the Replacement field depends on whether a change requires a replacement, indicated by the RequiresRecreation field in a change's Target structure. For example, if the RequiresRecreation field is Never, the Replacement field is False. However, if there are multiple changes on a single resource and each change has a different value for the RequiresRecreation field, AWS CloudFormation updates the resource using the most intrusive behavior. In other words, if only one of the many changes requires a replacement, AWS CloudFormation must replace the resource and, therefore, sets the Replacement field to True. The following change set was generated by changing the values for every parameter (Purpose, InstanceType, and KeyPairName), which are all used by the EC2 instance. With these changes, AWS CloudFormation will be required to be replace the instance because the Replacement field is equal to True. { "StackId": "arn:aws:cloudformation:us-east-1:123456789012:stack/ SampleStack/1a2345b6-0000-00a0-a123-00abc0abc000", "Status": "CREATE_COMPLETE", "ChangeSetName": "SampleChangeSet-multiple", "Parameters": [ { "ParameterValue": "production", "ParameterKey": "Purpose" }, { "ParameterValue": "MyNewKeyName", "ParameterKey": "KeyPairName" }, { "ParameterValue": "t2.small", "ParameterKey": "InstanceType" } ], "Changes": [ { "ResourceChange": { "ResourceType": "AWS::EC2::Instance", API Version 2010-05-15 133 AWS CloudFormation User Guide Updating Stacks Using Change Sets }, "PhysicalResourceId": "i-7bef86f8", "Details": [ { "ChangeSource": "DirectModification", "Evaluation": "Dynamic", "Target": { "Attribute": "Properties", "Name": "KeyName", "RequiresRecreation": "Always" } }, { "ChangeSource": "DirectModification", "Evaluation": "Dynamic", "Target": { "Attribute": "Properties", "Name": "InstanceType", "RequiresRecreation": "Conditionally" } }, { "ChangeSource": "DirectModification", "Evaluation": "Dynamic", "Target": { "Attribute": "Tags", "RequiresRecreation": "Never" } }, { "CausingEntity": "KeyPairName", "ChangeSource": "ParameterReference", "Evaluation": "Static", "Target": { "Attribute": "Properties", "Name": "KeyName", "RequiresRecreation": "Always" } }, { "CausingEntity": "InstanceType", "ChangeSource": "ParameterReference", "Evaluation": "Static", "Target": { "Attribute": "Properties", "Name": "InstanceType", "RequiresRecreation": "Conditionally" } }, { "CausingEntity": "Purpose", "ChangeSource": "ParameterReference", "Evaluation": "Static", "Target": { "Attribute": "Tags", "RequiresRecreation": "Never" } } ], "Action": "Modify", "Scope": [ "Tags", "Properties" ], "LogicalResourceId": "MyEC2Instance", "Replacement": "True" API Version 2010-05-15 134 AWS CloudFormation User Guide Updating Stacks Using Change Sets } "Type": "Resource" ], "CreationTime": "2016-03-17T00:39:35.974Z", "Capabilities": [], "StackName": "SampleStack", "NotificationARNs": [], "ChangeSetId": "arn:aws:cloudformation:us-east-1:123456789012:changeSet/ SampleChangeSet-multiple/1a2345b6-0000-00a0-a123-00abc0abc000" } Identify the change that requires the resource to be replaced by viewing each change (the static evaluations in the Details structure). In this example, each change has a different value for the RequireRecreation field, but the change to the KeyName property has the most intrusive update behavior, always requiring a recreation. AWS CloudFormation will replace the instance because the key name was changed. If the key name were unchanged, the change to the InstanceType property would have the most intrusive update behavior (Conditionally), so the Replacement field would be Conditionally. To find the conditions in which AWS CloudFormation replaces the instance, view the update behavior for the InstanceType property. Adding and Removing Resources The following example was generated by submitting a modified template that removes the EC2 instance and adds an Auto Scaling group and launch configuration. { "StackId": "arn:aws:cloudformation:us-east-1:123456789012:stack/ SampleStack/1a2345b6-0000-00a0-a123-00abc0abc000", "Status": "CREATE_COMPLETE", "ChangeSetName": "SampleChangeSet-addremove", "Parameters": [ { "ParameterValue": "testing", "ParameterKey": "Purpose" }, { "ParameterValue": "MyKeyName", "ParameterKey": "KeyPairName" }, { "ParameterValue": "t2.micro", "ParameterKey": "InstanceType" } ], "Changes": [ { "ResourceChange": { "Action": "Add", "ResourceType": "AWS::AutoScaling::AutoScalingGroup", "Scope": [], "Details": [], "LogicalResourceId": "AutoScalingGroup" }, "Type": "Resource" }, { "ResourceChange": { "Action": "Add", "ResourceType": "AWS::AutoScaling::LaunchConfiguration", "Scope": [], API Version 2010-05-15 135 AWS CloudFormation User Guide Updating Stacks Directly "Details": [], "LogicalResourceId": "LaunchConfig" }, { }, "Type": "Resource" "ResourceChange": { "ResourceType": "AWS::EC2::Instance", "PhysicalResourceId": "i-1abc23d4", "Details": [], "Action": "Remove", "Scope": [], "LogicalResourceId": "MyEC2Instance" }, "Type": "Resource" } ], "CreationTime": "2016-03-18T01:44:08.444Z", "Capabilities": [], "StackName": "SampleStack", "NotificationARNs": [], "ChangeSetId": "arn:aws:cloudformation:us-east-1:123456789012:changeSet/ SampleChangeSet-addremove/1a2345b6-0000-00a0-a123-00abc0abc000" } In the Changes structure, there are three ResourceChange structures, one for each resource. For each resource, the Action field indicates whether AWS CloudFormation adds or removes the resource. The Scope and Details fields are empty because they apply only to modified resources. For new resources, AWS CloudFormation can't determine the value of some fields until you execute the change set. For example, AWS CloudFormation doesn't provide the physical IDs of the Auto Scaling group and launch configuration because they don't exist yet. AWS CloudFormation creates the new resources when you execute the change set. Updating Stacks Directly When you want to quickly deploy updates to your stack, perform a direct update. With a direct update, you submit a template or input parameters that specify updates to the resources in the stack, and AWS CloudFormation immediately deploys them. If you want to use a template to make your updates, you can modify the current template and store it locally or in an S3 bucket. For resource properties that don't support updates, you must keep the current values. To preview the changes that AWS CloudFormation will make to your stack before you update it, use change sets. For more information, see Updating Stacks Using Change Sets (p. 122). Note When updating a stack, AWS CloudFormation might interrupt resources or replace updated resources, depending on which properties you update. For more information about resource update behaviors, see Update Behaviors of Stack Resources (p. 118). To update a AWS CloudFormation stack (console) 1. In the AWS CloudFormation console, from the list of stacks, select the running stack that you want to update. 2. Choose Actions and then Update Stack. API Version 2010-05-15 136 AWS CloudFormation User Guide Updating Stacks Directly 3. If you modified the stack template, specify the location of the updated template. If not, select Use current template. • For a template stored locally on your computer, select Upload a template to Amazon S3. Choose Choose File to navigate to the file and select it, and then click Next. Note If you upload a local template file, AWS CloudFormation uploads it to an Amazon Simple Storage Service (Amazon S3) bucket in your AWS account. If you don't already have an S3 bucket that was created by AWS CloudFormation, it creates a unique bucket for each Region in which you upload a template file. If you already have an S3 bucket that was created by AWS CloudFormation in your AWS account, AWS CloudFormation adds the template to that bucket. Considerations to keep in mind about S3 buckets created by AWS CloudFormation • The buckets are accessible to anyone with Amazon S3 permissions in your AWS account. • AWS CloudFormation creates the buckets with server-side encryption enabled by default, thereby encrypting all objects stored in the bucket. You can directly manage encryption options for buckets that AWS CloudFormation has created; for example, using the Amazon S3 console at https:// console.aws.amazon.com/s3/ , or the AWS CLI. For more information, see Amazon S3 Default Encryption for S3 Buckets in the Amazon Simple Storage Service Developer Guide. • You can use your own bucket and manage its permissions by manually uploading templates to Amazon S3. When you create or update a stack, specify the Amazon S3 URL of a template file. • For a template stored in an Amazon S3 bucket, select Specify an Amazon S3 URL. Enter or paste the URL for the template, and then click Next. If you have a template in a versioning-enabled bucket, you can specify a specific version of the template, such as https://s3.amazonaws.com/templates/myTemplate.template? versionId=123ab1cdeKdOW5IH4GAcYbEngcpTJTDW. For more information, see Managing Objects in a Versioning-Enabled Bucket in the Amazon Simple Storage Service Console User Guide. 4. If your template contains parameters, on the Specify Parameters page, enter or modify the parameter values, and then click Next. AWS CloudFormation populates each parameter with the value that is currently set in the stack with the exception of parameters declared with the NoEcho attribute; however, you can still use current values by choosing Use existing value. 5. On the Options page, you can update the stack's service role, enter an overriding stack policy, or update the Amazon SNS notification topic. An overriding stack policy lets you update protected resources. For more information, see Prevent Updates to Stack Resources (p. 141). API Version 2010-05-15 137 AWS CloudFormation User Guide Updating Stacks Directly Click Next. 6. Review the stack information and the changes that you submitted. In the Review section, check that you submitted the correct information, such as the correct parameter values or template URL. If your template contains IAM resources, select I acknowledge that this template may create IAM resources to specify that you want to use IAM resources in the template. For more information about using IAM resources in templates, see Controlling Access with AWS Identity and Access Management (p. 9). In the Preview your changes section, check that AWS CloudFormation will make all the changes that you expect. For example, you can check that AWS CloudFormation adds, removes, and modifies the resources that you intended to add, remove, or modify. AWS CloudFormation generates this preview by creating a change set for the stack. For more information, see Updating Stacks Using Change Sets (p. 122). 7. Click Update. Your stack enters the UPDATE_IN_PROGRESS state. After it has finished updating, the state is set to UPDATE_COMPLETE. If the stack update fails, AWS CloudFormation automatically rolls back changes, and sets the state to UPDATE_ROLLBACK_COMPLETE. Note You can cancel an update while it's in the UPDATE_IN_PROGRESS state. For more information, see Canceling a Stack Update (p. 140). To update a AWS CloudFormation stack (AWS CLI) • Use the aws cloudformation update-stack command to directly update a stack. You specify the stack, and parameter values and capabilities that you want to update, and, if you want use an updated template, the name of the template. The following example updates the template and input parameters for the mystack stack: PROMPT> aws cloudformation update-stack --stack-name mystack --template-url https:// s3.amazonaws.com/sample/updated.template --parameters ParameterKey=VPCID,ParameterValue=SampleVPCID ParameterKey=SubnetIDs,ParameterValue=SampleSubnetID1\\,SampleSubnetID2 The following example updates just the SubnetIDs parameter values for the mystack stack: PROMPT> aws cloudformation update-stack --stack-name mystack --use-previous-template --parameters ParameterKey=VPCID,UsePreviousValue=true ParameterKey=SubnetIDs,ParameterValue=SampleSubnetID1\\,UpdatedSampleSubnetID2 The following example adds two stack notification topics to the mystack stack: PROMPT> aws cloudformation update-stack --stack-name mystack --use-previous-template --notification-arns "arn:aws:sns:us-east-1:12345678912:mytopic" "arn:aws:sns:useast-1:12345678912:mytopic2" The following example removes all stack notification topics from the mystack stack: PROMPT> aws cloudformation update-stack --stack-name mystack --use-previous-template --notification-arns [] API Version 2010-05-15 138 AWS CloudFormation User Guide Monitoring Progress Monitoring the Progress of a Stack Update You can monitor the progress of a stack update by viewing the stack's events. The console's Events tab displays each major step in the creation and update of the stack sorted by the time of each event with latest events on top. The start of the stack update process is marked with an UPDATE_IN_PROGRESS event for the stack: 2011-09-30 09:35 PDT AWS::CloudFormation::Stack MyStack UPDATE_IN_PROGRESS Next are events that mark the beginning and completion of the update of each resource that was changed in the update template. For example, updating an AWS::RDS::DBInstance (p. 1341) resource named MyDB would result in the following entries: 2011-09-30 09:35 PDT AWS::RDS::DBInstance MyDB UPDATE_COMPLETE 2011-09-30 09:35 PDT AWS::RDS::DBInstance MyDB UPDATE_IN_PROGRESS The UPDATE_IN_PROGRESS event is logged when AWS CloudFormation reports that it has begun to update the resource. The UPDATE_COMPLETE event is logged when the resource is successfully created. When AWS CloudFormation has successfully updated the stack, you will see the following event: 2011-09-30 09:35 PDT AWS::CloudFormation::Stack MyStack UPDATE_COMPLETE If an update of a resource fails, AWS CloudFormation reports an UPDATE_FAILED event that includes a reason for the failure. For example, if your update template specified a property change that is not supported by the resource such as reducing the size of AllocatedStorage for an AWS::RDS::DBInstance (p. 1341) resource, you would see events like these: 2011-09-30 09:36 PDT AWS::RDS::DBInstance MyDB UPDATE_FAILED Size cannot be less than current size; requested: 5; current: 10 2011-09-30 09:35 PDT AWS::RDS::DBInstance MyDB UPDATE_IN_PROGRESS If a resource update fails, AWS CloudFormation rolls back any resources that it has updated during the upgrade to their configurations before the update. Here is an example of the events you would see during an update rollback: 2011-09-30 2011-09-30 2011-09-30 2011-09-30 following 09:38 PDT AWS::CloudFormation::Stack MyStack UPDATE_ROLLBACK_COMPLETE 09:38 PDT AWS::RDS::DBInstance MyDB UPDATE_COMPLETE 09:37 PDT AWS::RDS::DBInstance MyDB UPDATE_IN_PROGRESS 09:37 PDT AWS::CloudFormation::Stack MyStack UPDATE_ROLLBACK_IN_PROGRESS The resource(s) failed to update: [MyDB] Topics • To view stack events by using the console (p. 139) • To view stack events by using the command line (p. 140) To view stack events by using the console 1. In the AWS CloudFormation console, select the stack that you updated and then click the Events tab to view the stacks events. API Version 2010-05-15 139 AWS CloudFormation User Guide Canceling a Stack Update 2. To update the event list with the most recent events, click the refresh button in the AWS CloudFormation console. To view stack events by using the command line • Use the command aws cloudformation describe-stack-events to view the events for a stack. Canceling a Stack Update After a stack update has begun, you can cancel the stack update if the stack is still in the UPDATE_IN_PROGRESS state. After an update has finished, you cannot cancel it. You can, however, update a stack again with any previous settings. If you cancel a stack update, the stack is rolled back to the stack configuration that existed prior to initiating the stack update. Topics • To cancel a stack update by using the console (p. 140) • To cancel a stack update by using the command line (p. 140) To cancel a stack update by using the console 1. From the list of stacks in the AWS CloudFormation console, select the stack that is currently being updated (its state must be UPDATE_IN_PROGRESS) . 2. Choose Actions and then Cancel Update. 3. To continue canceling the update, click Yes, Cancel Update when prompted. Otherwise, click Cancel to resume the update. The stack proceeds to the UPDATE_ROLLBACK_IN_PROGRESS state. After the update cancellation is complete, the stack is set to UPDATE_ROLLBACK_COMPLETE. To cancel a stack update by using the command line • Use the command aws cloudformation cancel-update-stack to cancel an update. API Version 2010-05-15 140 AWS CloudFormation User Guide Prevent Updates to Stack Resources Prevent Updates to Stack Resources When you create a stack, all update actions are allowed on all resources. By default, anyone with stack update permissions can update all of the resources in the stack. During an update, some resources might require an interruption or be completely replaced, resulting in new physical IDs or completely new storage. You can prevent stack resources (p. 499) from being unintentionally updated or deleted during a stack update by using a stack policy. A stack policy is a JSON document that defines the update actions that can be performed on designated resources. After you set a stack policy, all of the resources in the stack are protected by default. To allow updates on specific resources, you specify an explicit Allow statement for those resources in your stack policy. You can define only one stack policy per stack, but, you can protect multiple resources within a single policy. A stack policy applies to all AWS CloudFormation users who attempt to update the stack. You can't associate different stack policies with different users. A stack policy applies only during stack updates. It doesn't provide access controls like an AWS Identity and Access Management (IAM) policy. Use a stack policy only as a fail-safe mechanism to prevent accidental updates to specific stack resources. To control access to AWS resources or actions, use IAM. Topics • Example Stack Policy (p. 141) • Defining a Stack Policy (p. 142) • Setting a Stack Policy (p. 144) • Updating Protected Resources (p. 146) • Modifying a Stack Policy (p. 148) • More Example Stack Policies (p. 148) Example Stack Policy The following example stack policy prevents updates to the ProductionDatabase resource: { } "Statement" : [ { "Effect" : "Allow", "Action" : "Update:*", "Principal": "*", "Resource" : "*" }, { "Effect" : "Deny", "Action" : "Update:*", "Principal": "*", "Resource" : "LogicalResourceId/ProductionDatabase" } ] When you set a stack policy, all resources are protected by default. To allow updates on all resources, we add an Allow statement that allows all actions on all resources. Although the Allow statement specifies all resources, the explicit Deny statement overrides it for the resource with the ProductionDatabase logical ID. This Deny statement prevents all update actions, such as replacement or deletion, on the ProductionDatabase resource. The Principal element is required, but supports only the wild card (*), which means that the statement applies to all principals. API Version 2010-05-15 141 AWS CloudFormation User Guide Prevent Updates to Stack Resources Note During a stack update, AWS CloudFormation automatically updates resources that depend on other updated resources. For example, AWS CloudFormation updates a resource that references an updated resource. AWS CloudFormation makes no physical changes, such as the resources' ID, to automatically updated resources, but if a stack policy is associated with those resources, you must have permission to update them. Defining a Stack Policy When you create a stack, no stack policy is set, so all update actions are allowed on all resources. To protect stack resources from update actions, define a stack policy and then set it on your stack. A stack policy is a JSON document that defines the AWS CloudFormation stack update actions that AWS CloudFormation users can perform and the resources that the actions apply to. You set the stack policy when you create a stack, by specifying a text file that contains your stack policy or typing it out. When you set a stack policy on your stack, any update not explicitly allowed is denied by default. You define a stack policy with five elements: Effect, Action, Principal, Resource, and Condition. The following pseudo code shows stack policy syntax. { } "Statement" : [ { "Effect" : "Deny_or_Allow", "Action" : "update_actions", "Principal" : "*", "Resource" : "LogicalResourceId/resource_logical_ID", "Condition" : { "StringEquals_or_StringLike" : { "ResourceType" : [resource_type, ...] } } } ] Effect Determines whether the actions that you specify are denied or allowed on the resource(s) that you specify. You can specify only Deny or Allow, such as: "Effect" : "Deny" Important If a stack policy includes overlapping statements (both allowing and denying updates on a resource), a Deny statement always overrides an Allow statement. To ensure that a resource is protected, use a Deny statement for that resource. Action Specifies the update actions that are denied or allowed: Update:Modify Specifies update actions during which resources might experience no interruptions or some interruptions while changes are being applied. All resources maintain their physical IDs. Update:Replace Specifies update actions during which resources are recreated. AWS CloudFormation creates a new resource with the specified updates and then deletes the old resource. Because the resource is recreated, the physical ID of the new resource might be different. API Version 2010-05-15 142 AWS CloudFormation User Guide Prevent Updates to Stack Resources Update:Delete Specifies update actions during which resources are removed. Updates that completely remove resources from a stack template require this action. Update:* Specifies all update actions. The asterisk is a wild card that represents all update actions. The following example shows how to specify just the replace and delete actions: "Action" : ["Update:Replace", "Update:Delete"] To allow all update actions except for one, use NotAction. For example, to allow all update actions except for Update:Delete, use NotAction, as shown in this example: { } "Statement" : [ { "Effect" : "Allow", "NotAction" : "Update:Delete", "Principal": "*", "Resource" : "*" } ] For more information about stack updates, see AWS CloudFormation Stacks Updates (p. 118). Principal The Principal element specifies the entity that the policy applies to. This element is required but supports only the wild card (*), which means that the policy applies to all principals. Resource Specifies the logical IDs of the resources that the policy applies to. To specify types of resources (p. 499), use the Condition element. To specify a single resource, use its logical ID. For example: "Resource" : ["LogicalResourceId/myEC2instance"] You can use a wild card with logical IDs. For example, if you use a common logical ID prefix for all related resources, you can specify all of them with a wild card: "Resource" : ["LogicalResourceId/CriticalResource*"] You can also use a Not element with resources. For example, to allow updates to all resources except for one, use a NotResource element to protect that resource: { } "Statement" : [ { "Effect" : "Allow", "Action" : "Update:*", "Principal": "*", "NotResource" : "LogicalResourceId/ProductionDatabase" } ] API Version 2010-05-15 143 AWS CloudFormation User Guide Prevent Updates to Stack Resources When you set a stack policy, any update not explicitly allowed is denied. By allowing updates to all resources except for the ProductionDatabase resource, you deny updates to the ProductionDatabase resource. Conditions Specifies the resource type (p. 499) that the policy applies to. To specify the logical IDs of specific resources, use the Resource element. You can specify a resource type, such as all EC2 and RDS DB instances, as shown in the following example: { } "Statement" : [ { "Effect" : "Deny", "Principal" : "*", "Action" : "Update:*", "Resource" : "*", "Condition" : { "StringEquals" : { "ResourceType" : ["AWS::EC2::Instance", "AWS::RDS::DBInstance"] } } }, { "Effect" : "Allow", "Principal" : "*", "Action" : "Update:*", "Resource" : "*" } ] The Allow statement grants update permissions to all resources and the Deny statement denies updates to EC2 and RDS DB instances. The Deny statement always overrides allow actions. You can use a wild card with resource types. For example, you can deny update permissions to all Amazon EC2 resources—such as instances, security groups, and subnets—by using a wild card, as shown in the following example: "Condition" : { "StringLike" : { "ResourceType" : ["AWS::EC2::*"] } } You must use the StringLike condition when you use wild cards. Setting a Stack Policy You can use the console or AWS CLI to apply a stack policy when you create a stack. You can also use the AWS CLI to apply a stack policy to an existing stack. After you apply a stack policy, you can't remove it from the stack, but you can use the AWS CLI to modify it. Stack policies apply to all AWS CloudFormation users who attempt to update the stack. You can't associate different stack policies with different users. For information about writing stack policies, see Defining a Stack Policy (p. 142). API Version 2010-05-15 144 AWS CloudFormation User Guide Prevent Updates to Stack Resources To set a stack policy when you create a stack (console) 1. Open the AWS CloudFormation console at https://console.aws.amazon.com/cloudformation. 2. On the CloudFormation Stacks page, choose Create Stack. 3. In the Create Stack wizard, on the Options page, expand the Advanced section. 4. Choose Browse, and then choose the file that contains the stack policy, or type the policy in the Stack policy text box. To set a stack policy when you create a stack (CLI) • Use the aws cloudformation create-stack command with the --stack-policy-body option to type in a modified policy or the --stack-policy-url option to specify a file containing the policy. To set a stack policy on an existing stack (CLI only) • Use the aws cloudformation set-stack-policy command with the --stack-policy-body option to type in a modified policy or the --stack-policy-url option to specify a file containing the policy. API Version 2010-05-15 145 AWS CloudFormation User Guide Prevent Updates to Stack Resources Note To add a policy to an existing stack, you must have permission to the AWS CloudFormation SetStackPolicy action. Updating Protected Resources To update protected resources, create a temporary policy that overrides the stack policy and allows updates on those resources. Specify the override policy when you update the stack. The override policy doesn't permanently change the stack policy. To update protected resources, you must have permission to use the AWS CloudFormation SetStackPolicy action. For information about setting AWS CloudFormation permissions, see Controlling Access with AWS Identity and Access Management (p. 9). Note During a stack update, AWS CloudFormation automatically updates resources that depend on other updated resources. For example, AWS CloudFormation updates a resource that references an updated resource. AWS CloudFormation makes no physical changes, such as the resources' ID, to automatically updated resources, but if a stack policy is associated with those resources, you must have permission to update them. To update a protected resource (console) 1. 2. Open the AWS CloudFormation console at https://console.aws.amazon.com/cloudformation. Select the stack that you want to update, choose Actions, and then choose Update Stack. 3. If you modified the stack template, specify the location of the updated template. If not, choose Use current template. • For a template stored locally on your computer, choose Upload a template to Amazon S3. Choose Choose File to navigate to the file, select it, and then choose Next. • For a template stored in an Amazon S3 bucket, choose Specify an Amazon S3 URL. Type or paste the URL for the template, and then choose Next. 4. If you have a template in a versioning-enabled bucket, you can specify a specific version of the template, such as https://s3.amazonaws.com/templates/myTemplate.template? versionId=123ab1cdeKdOW5IH4GAcYbEngcpTJTDW. For more information, see Managing Objects in a Versioning-Enabled Bucket in the Amazon Simple Storage Service Console User Guide. If your template contains parameters, on the Specify Parameters page, enter or modify the parameter values, and then choose Next. AWS CloudFormation populates each parameter with the value that is currently set in the stack except for parameters declared with the NoEcho attribute. You can use current values for those parameters by choosing Use existing value. API Version 2010-05-15 146 AWS CloudFormation User Guide Prevent Updates to Stack Resources 5. On the Options page, choose the file that contains the overriding stack policy or type a policy, and then choose Next. The override policy must specify an Allow statement for the protected resources that you want to update. For example, to update all protected resources, specify a temporary override policy that allows all updates: { } "Statement" : [ { "Effect" : "Allow", "Action" : "Update:*", "Principal": "*", "Resource" : "*" } ] Note AWS CloudFormation applies the override policy only during this update. The override policy doesn't permanently change the stack policy. To modify a stack policy, see Modifying a Stack Policy (p. 148). 6. Review the stack information and the changes that you submitted. In the Review section, check that you submitted the correct information, such as the correct parameter values or template URL. If your template contains IAM resources, choose I acknowledge that this template may create IAM resources to specify that you want to use IAM resources in the template. For more information about using IAM resources in templates, see Controlling Access with AWS Identity and Access Management (p. 9). In the Preview your changes section, check that AWS CloudFormation will make all the changes that you expect. For example, check that AWS CloudFormation adds, removes, and modifies the resources that you intended to add, remove, or modify. AWS CloudFormation generates this preview by creating a change set for the stack. For more information, see Updating Stacks Using Change Sets (p. 122). 7. Choose Update. Your stack enters the UPDATE_IN_PROGRESS state. After it has finished updating, the state is set to UPDATE_COMPLETE. If the stack update fails, AWS CloudFormation automatically rolls back changes, and sets the state to UPDATE_ROLLBACK_COMPLETE. To update a protected resource (CLI) • Use the aws cloudformation update-stack command with the --stack-policy-duringupdate-body option to type in a modified policy or the --stack-policy-during-update-url option to specify a file containing the policy. Note AWS CloudFormation applies the override policy only during this update. The override policy doesn't permanently change the stack policy. To modify a stack policy, see Modifying a Stack Policy (p. 148). API Version 2010-05-15 147 AWS CloudFormation User Guide Prevent Updates to Stack Resources Modifying a Stack Policy To protect additional resources or to remove protection from resources, modify the stack policy. For example, when you add a database that you want to protect to your stack, add a Deny statement for that database to the stack policy. To modify the policy, you must have permission to use the SetStackPolicy action. Use the AWS CLI to modify stack policies. To modify a stack policy (CLI) • Use the aws cloudformation set-stack-policy command with the --stack-policy-body option to type in a modified policy or the --stack-policy-url option to specify a file containing the policy. You can't delete a stack policy. To remove all protection from all resources, you modify the policy to explicitly allow all actions on all resources. The following policy allows all updates on all resources: { } "Statement" : [ { "Effect" : "Allow", "Action" : "Update:*", "Principal": "*", "Resource" : "*" } ] More Example Stack Policies The following example policies show how to prevent updates to all stack resources and to specific resources, and prevent specific types of updates. Prevent Updates to All Stack Resources To prevent updates to all stack resources, the following policy specifies a Deny statement for all update actions on all resources. { } "Statement" : [ { "Effect" : "Deny", "Action" : "Update:*", "Principal": "*", "Resource" : "*" } ] Prevent Updates to a Single Resource The following policy denies all update actions on the database with the MyDatabase logical ID. It allows all update actions on all other stack resources with an Allow statement. The Allow statement doesn't apply to the MyDatabase resource because the Deny statement always overrides allow actions. { "Statement" : [ API Version 2010-05-15 148 AWS CloudFormation User Guide Prevent Updates to Stack Resources { "Effect" : "Deny", "Action" : "Update:*", "Principal": "*", "Resource" : "LogicalResourceId/MyDatabase" }, { } ] } "Effect" : "Allow", "Action" : "Update:*", "Principal": "*", "Resource" : "*" You can achieve the same result as the previous example by using a default denial. When you set a stack policy, AWS CloudFormation denies any update that is not explicitly allowed. The following policy allows updates to all resources except for the ProductionDatabase resource, which is denied by default. { } "Statement" : [ { "Effect" : "Allow", "Action" : "Update:*", "Principal": "*", "NotResource" : "LogicalResourceId/ProductionDatabase" } ] Important There is risk in using a default denial. If you have an Allow statement elsewhere in the policy (such as an Allow statement that uses a wildcard), you might unknowingly grant update permission to resources that you don't intend to. Because an explicit denial overrides any allow actions, you can ensure that a resource is protected by using a Deny statement. Prevent Updates to All Instances of a Resource Type The following policy denies all update actions on the RDS DB instance resource type. It allows all update actions on all other stack resources with an Allow statement. The Allow statement doesn't apply to the RDS DB instance resources because a Deny statement always overrides allow actions. { "Statement" : [ { "Effect" : "Deny", "Action" : "Update:*", "Principal": "*", "Resource" : "*", "Condition" : { "StringEquals" : { "ResourceType" : ["AWS::RDS::DBInstance"] } } }, { "Effect" : "Allow", "Action" : "Update:*", "Principal": "*", "Resource" : "*" } ] API Version 2010-05-15 149 AWS CloudFormation User Guide Continue Rolling Back an Update } Prevent Replacement Updates for an Instance The following policy denies updates that would cause a replacement of the instance with the MyInstance logical ID. It allows all update actions on all other stack resources with an Allow statement. The Allow statement doesn't apply to the MyInstance resource because the Deny statement always overrides allow actions. { } "Statement" : [ { "Effect" : "Deny", "Action" : "Update:Replace", "Principal": "*", "Resource" : "LogicalResourceId/MyInstance" }, { "Effect" : "Allow", "Action" : "Update:*", "Principal": "*", "Resource" : "*" } ] Prevent Updates to Nested Stacks The following policy denies all update actions on the AWS CloudFormation stack resource type (nested stacks). It allows all update actions on all other stack resources with an Allow statement. The Allow statement doesn't apply to the AWS CloudFormationstack resources because the Deny statement always overrides allow actions. { } "Statement" : [ { "Effect" : "Deny", "Action" : "Update:*", "Principal": "*", "Resource" : "*", "Condition" : { "StringEquals" : { "ResourceType" : ["AWS::CloudFormation::Stack"] } } }, { "Effect" : "Allow", "Action" : "Update:*", "Principal": "*", "Resource" : "*" } ] Continue Rolling Back an Update A stack goes into the UPDATE_ROLLBACK_FAILED state when AWS CloudFormation cannot roll back all changes during an update. For example, you might have a stack that begins to roll back to an old database instance that was deleted outside of AWS CloudFormation. Because AWS CloudFormation API Version 2010-05-15 150 AWS CloudFormation User Guide Continue Rolling Back an Update doesn't know that the database was deleted, it assumes that the database instance still exists and attempts to roll back to it, causing the update rollback to fail. When a stack is in the UPDATE_ROLLBACK_FAILED state, you can continue to roll it back to a working state (UPDATE_ROLLBACK_COMPLETE). You can't update a stack that is in the UPDATE_ROLLBACK_FAILED state. However, if you can continue to roll it back, you can return the stack to its original settings and then try to update it again. In most cases, you must fix the error that causes the update rollback to fail before you can continue to roll back your stack. In other cases, you can continue to roll back the update without any changes, for example when a stack operation times out. Note If you use nested stacks, rolling back the parent stack will attempt to roll back all the child stacks as well. To continue rolling back an update (console) 1. Open the AWS CloudFormation console at https://console.aws.amazon.com/cloudformation. 2. Select the stack that you want to update, choose Actions, and then choose Continue Update Rollback. If none of the solutions in the troubleshooting guide worked, you can use the advanced option to skip the resources that AWS CloudFormation can't successfully roll back. You must look up (p. 99) and type the logical IDs of the resources that you want to skip. Specify only resources that went into the UPDATE_FAILED state during the UpdateRollback and not during the forward update. Warning AWS CloudFormation sets the status of the specified resources to UPDATE_COMPLETE and continues to roll back the stack. After the rollback is complete, the state of the skipped resources will be inconsistent with the state of the resources in the stack template. Before performing another stack update, you must update the stack or resources to be consistent with each other. If you don't, subsequent stack updates might fail, and the stack will become unrecoverable. Specify the minimum number of resources required to successfully roll back your stack. For example, a failed resource update might cause dependent resources to fail. In this case, it might not be necessary to skip the dependent resources. To skip resources that are part of nested stacks, use the following format: NestedStackName.ResourceLogicalID. If you want to specify the logical ID of a stack resource (Type: AWS::CloudFormation::Stack) in the ResourcesToSkip list, then its corresponding embedded stack must be in one of the following states: DELETE_IN_PROGRESS, DELETE_COMPLETE, or DELETE_FAILED. API Version 2010-05-15 151 AWS CloudFormation User Guide Continue Rolling Back an Update To continue rolling back an update (AWS CLI) • Use the aws cloudformation continue-update-rollback command with the stack-name option to specify the ID of the stack that you want to continue to roll back. Using ResourcesToSkip to recover a nested stacks hierarchy The following diagram shows a nested stacks hierarchy that is in the UPDATE_ROLLBACK_FAILED state. In this example, the WebInfra root stack has two nested stacks: WebInfra-Compute and WebInfraStorage, which in turn have one or more nested stacks. Note The stack names in this example are truncated for simplicity. Child stack names are typically generated by AWS CloudFormation and contain unique random strings, so actual names might not be user-friendly. To successfully get the root stack into an operable state using continue-update-rollback, you must use the resources-to-skip parameter to skip resources that failed to rollback. In this example, resources-to-skip would include the following items: 1. myCustom 2. WebInfra-Compute-Asg.myAsg 3. WebInfra-Compute-LB.myLoadBalancer 4. WebInfra-Storage.DB The following example is the full CLI command: API Version 2010-05-15 152 AWS CloudFormation User Guide Exporting Stack Output Values PROMPT> aws cloudformation continue-update-rollback --stack-name WebInfra --resourcesto-skip myCustom WebInfra-Compute-Asg.myAsg WebInfra-Compute-LB.myLoadBalancer WebInfraStorage.DB Note that we specified resources from nested stacks by using the NestedStackName.ResourceLogicalID format, but for the resources of the root stack, such as myCustom, we specified only the logical ID. Finding the stack name of a nested stack You can find a child stack's name in its stack ID or Amazon Resource Name (ARN). In the following example, the stack name is WebInfra-Storage-Z2VKC706XKXT: arn:aws:cloudformation:us-east-1:123456789012:stack/WebInfra-StorageZ2VKC706XKXT/ea9e7f90-54f7-11e6-a032-028f3d2330bd Finding the logical ID of a nested stack You can find a child stack's logical ID in the template definition of its parent. In the diagram, the LogicalId of the WebInfra-Storage-DB child stack is DB in its parent WebInfra-Storage. In the AWS CloudFormation console, you can also find the logical ID in the Logical ID column for the stack resource on the Resources tab or the Events tab. Exporting Stack Output Values To share information between stacks, export a stack's output values. Other stacks that are in the same AWS account and region can import the exported values. For example, you might have a single networking stack that exports the IDs of a subnet and security group for public web servers. Stacks with a public web server can easily import those networking resources. You don't need to hard code resource IDs in the stack's template or pass IDs as input parameters. To export a stack's output value, use the Export field in the Output (p. 199) section of the stack's template. To import those values, use the Fn::ImportValue (p. 2300) function in the template for the other stacks. For a walkthrough and sample templates, see Walkthrough: Refer to Resource Outputs in Another AWS CloudFormation Stack (p. 248). Note After another stack imports an output value, you can't delete the stack that is exporting the output value or modify the exported output value. All of the imports must be removed before you can delete the exporting stack or modify the output value. Exporting Stack Output Values vs. Using Nested Stacks A nested stack is a stack that you create within another stack by using the AWS::CloudFormation::Stack (p. 694) resource. With nested stacks, you deploy and manage all resources from a single stack. You can use outputs from one stack in the nested stack group as inputs to another stack in the group. This differs from exporting values. If you want to isolate information sharing to within a nested stack group, we suggest that you use nested stacks. To share information with other stacks (not just within the group of nested stacks), export values. For example, you can create a single stack with a subnet and then export its ID. Other stacks can use that subnet by importing its ID; each stack doesn't need to create its own subnet. Note that as long as stacks are importing the subnet ID, you can't change or delete it. API Version 2010-05-15 153 AWS CloudFormation User Guide Listing Exported Output Values Listing Exported Output Values To see the values that you can import, list all of the exported output values by using the AWS CloudFormation console, AWS CLI, or AWS CloudFormation API. AWS CloudFormation shows the names and values of the exported outputs for the current region and the stack from which the outputs are exported. To reference an exported output value in a stack's template, use the export name and the Fn::ImportValue (p. 2300) function. To list exported output values (console) • In the AWS CloudFormation console, from the CloudFormation drop-down menu, choose Exports. To list exported output values (AWS CLI) • Run the aws cloudformation list-exports command. To list exported output values (API) • Run the ListExports API. Listing Stacks That Import an Exported Output Value When you export an output value, stacks that are in the same AWS account and region can import that value. To see which stacks are importing a particular output value, use the list import action. To delete or modify exported output values, use the ListImports action to track which stacks are importing them, and then modify those stacks to remove the Fn::ImportValue (p. 2300) functions that reference the output values. You must remove all of the imports that reference exported output values before you can delete or modify the exported output values. For more information about exporting and importing output values, see Exporting Stack Output Values (p. 153). To list stacks that import an exported output value (console) 1. In the AWS CloudFormation console, from the CloudFormation drop-down menu, choose Exports. API Version 2010-05-15 154 AWS CloudFormation User Guide Working with Nested Stacks 2. From the list of exported output values, choose the value. The Imports section of the detail page lists all of the stacks that are importing the value. To list stacks that import an exported output value (CLI) • Run the aws cloudformation list-imports command, providing the name of the exported output value. AWS CloudFormation returns a list of stacks that are importing the value. To list stacks that import an exported output value (API) • Run the ListImports API, providing the name of the exported output value. AWS CloudFormation returns a list of stacks that are importing the value. Working with Nested Stacks Nested stacks are stacks created as part of other stacks. You create a nested stack within another stack by using the AWS::CloudFormation::Stack (p. 694) resource. As your infrastructure grows, common patterns can emerge in which you declare the same components in multiple templates. You can separate out these common components and create dedicated templates for them. Then use the resource in your template to reference other templates, creating nested stacks. For example, assume that you have a load balancer configuration that you use for most of your stacks. Instead of copying and pasting the same configurations into your templates, you can create a dedicated template for the load balancer. Then, you just use the resource to reference that template from within other templates. Nested stacks can themselves contain other nested stacks, resulting in a hierarchy of stacks, as in the diagram below. The root stack is the top-level stack to which all the nested stacks ultimately belong. In addition, each nested stack has an immediate parent stack. For the first level of nested stacks, the root stack is also the parent stack. in the diagram below, for example: • Stack A is the root stack for all the other, nested, stacks in the hierarchy. • For stack B, stack A is both the parent stack, as well as the root stack. • For stack D, stack C is the parent stack; while for stack C, stack B is the parent stack. API Version 2010-05-15 155 AWS CloudFormation User Guide Working with Nested Stacks Using nested stacks to declare common components is considered a best practice (p. 70). Certain stack operations, such as stack updates, should be initiated from the root stack rather than performed directly on nested stacks themselves. Also, in some cases, nested stacks affect how stack operations are performed. For more information, refer to the following topics: • Use Nested Stacks to Reuse Common Template Patterns (p. 70) • Protecting a Stack From Being Deleted (p. 106) • Update Behaviors of Stack Resources (p. 118) • Exporting Stack Output Values vs. Using Nested Stacks (p. 153) • Using ResourcesToSkip to recover a nested stacks hierarchy (p. 152) • Nested Stacks are Stuck in UPDATE_COMPLETE_CLEANUP_IN_PROGRESS, UPDATE_ROLLBACK_COMPLETE_CLEANUP_IN_PROGRESS, or UPDATE_ROLLBACK_IN_PROGRESS (p. 2345) To view the root stack of a nested stack 1. Sign in to the AWS Management Console and open the AWS CloudFormation console at https:// console.aws.amazon.com/cloudformation/. Select the stack that you want. Nested stacks display NESTED next to their stack name. 2. On the Overview tab, click the stack name listed as Root stack. To view the nested stacks that belong to a root stack 1. Sign in to the AWS Management Console and open the AWS CloudFormation console at https:// console.aws.amazon.com/cloudformation/. Click the name of the root stack whose nested stacks you want to view. 2. Expand the Resources section. Look for resources of type AWS::CloudFormation::Stack. API Version 2010-05-15 156 AWS CloudFormation User Guide Working with Windows Stacks Working with Microsoft Windows Stacks on AWS CloudFormation AWS CloudFormation allows you to create Microsoft Windows stacks based on Amazon EC2 Windows Amazon Machine Images (AMIs) and provides you with the ability to install software, to use remote desktop to access your stack, and to update and configure your stack. The topics in this section are designed to demonstrate how common tasks related to creation and management of Windows instances are accomplished with AWS CloudFormation. In This Section • Microsoft Windows Amazon Machine Images (AMIs) and AWS CloudFormation Templates (p. 157) • Bootstrapping AWS CloudFormation Windows Stacks (p. 157) Microsoft Windows Amazon Machine Images (AMIs) and AWS CloudFormation Templates With AWS CloudFormation, you can create Microsoft Windows stacks for running Windows server instances. A number of pre-configured templates are available to launch directly from the AWS CloudFormation Sample Templates page, such as the following templates: • Windows_Single_Server_SharePoint_Foundation.template - SharePoint® Foundation 2010 running on Microsoft Windows Server® 2008 R2 • Windows_Single_Server_Active_Directory.template - Create a single server installation of Active Directory running on Microsoft Windows Server® 2008 R2. • Windows_Roles_And_Features.template - Create a single server specifying server roles running on Microsoft Windows Server® 2008 R2. • ElasticBeanstalk_Windows_Sample.template - Launch an AWS Elastic Beanstalk sample application on Windows Server 2008 R2 running IIS 7.5. Note Microsoft, Windows Server, and SharePoint are trademarks of the Microsoft group of companies. Although these stacks are already configured, you can use any EC2 Windows AMI as the basis of an AWS CloudFormation Windows stack. Bootstrapping AWS CloudFormation Windows Stacks This topic describes how to bootstrap a Windows stack and troubleshoot stack creation issues. If you will be creating your own Windows image for use with CloudFormation, see the information at Configuring a Windows Instance Using EC2ConfigService in the Amazon EC2 Microsoft Windows Guide for instructions. You must set up a Windows instance with EC2ConfigService for it to work with the AWS CloudFormation bootstrapping tools. Example of Bootstrapping a Windows Stack For the purposes of illustration, we'll examine the AWS CloudFormation single-instance Sharepoint server template, which can be viewed, in its entirety, at the following URL: API Version 2010-05-15 157 AWS CloudFormation User Guide Bootstrapping Windows Stacks • https://s3.amazonaws.com/cloudformation-templates-us-east-1/ Windows_Single_Server_SharePoint_Foundation.template This example demonstrates how to: • Create an IAM User and Security Group for access to the instance • Configure initialization files: cfn-credentials, cfn-hup.conf, and cfn-auto-reloader.conf • Download and install a package such as Sharepoint Foundation 2010 on the server instance. • Use a WaitCondition to ensure resources are ready • Retrieve an IP for the instance with Amazon Elastic IP (EIP). The AWS CloudFormation helper script cfn-init is used to perform each of these actions, based on information in the AWS::CloudFormation::Init (p. 677) resource in the Windows Single Server Sharepoint Foundation template. The AWS::CloudFormation::Init section is named "SharePointFoundation", and begins with a standard declaration: "SharePointFoundation": { "Type" : "AWS::EC2::Instance", "Metadata" : { "AWS::CloudFormation::Init" : { "config" : { After this, the files section of AWS::CloudFormation::Init is declared: "files" : { "c:\\cfn\\cfn-hup.conf" : { "content" : { "Fn::Join" : ["", [ "[main]\n", "stack=", { "Ref" : "AWS::StackName" }, "\n", "region=", { "Ref" : "AWS::Region" }, "\n" ]]} }, "c:\\cfn\\hooks.d\\cfn-auto-reloader.conf" : { "content": { "Fn::Join" : ["", [ "[cfn-auto-reloader-hook]\n", "triggers=post.update\n", "path=Resources.SharePointFoundation.Metadata.AWS::CloudFormation::Init\n", "action=cfn-init.exe -v -s ", { "Ref" : "AWS::StackName" }, " -r SharePointFoundation", " --region ", { "Ref" : "AWS::Region" }, "\n" ]]} }, "C:\\SharePoint\\SharePointFoundation2010.exe" : { "source" : "http://d3adzpja92utk0.cloudfront.net/SharePointFoundation.exe" } }, Three files are created here and placed in the C:\cfn directory on the server instance. They are: • cfn-hup.conf, the configuration file for cfn-hup. • cfn-auto-reloader.conf, the configuration file for the hook used by cfn-hup to initiate an update (calling cfn-init) when the metadata in AWS::CloudFormation::Init changes. API Version 2010-05-15 158 AWS CloudFormation User Guide Bootstrapping Windows Stacks There is also a file that is downloaded to the server: SharePointFoundation.exe. This file is used to install SharePoint on the server instance. Important Since paths on Windows use a backslash ('\') character, you must always remember to properly escape all backslashes by prepending another backslash whenever you refer to a Windows path in the AWS CloudFormation template. Next is the commands section, which are cmd.exe commands. "commands" : { "1-extract" : { "command" : "C:\\SharePoint\\SharePointFoundation2010.exe /extract:C:\\SharePoint\ \SPF2010 /quiet /log:C:\\SharePoint\\SharePointFoundation2010-extract.log" }, "2-prereq" : { "command" : "C:\\SharePoint\\SPF2010\\PrerequisiteInstaller.exe /unattended" }, "3-install" : { "command" : "C:\\SharePoint\\SPF2010\\setup.exe /config C:\\SharePoint\\SPF2010\\Files\ \SetupSilent\\config.xml" } Because commands in the instance are processed in alphabetical order by name, each command has been prepended with a number indicating its desired execution order. Thus, we can make sure that the installation package is first extracted, all prerequisites are then installed, and finally, installation of SharePoint is started. Next is the Properties section: "Properties": { "InstanceType" : { "Ref" : "InstanceType" }, "ImageId" : { "Fn::FindInMap" : [ "AWSRegionArch2AMI", { "Ref" : "AWS::Region" }, { "Fn::FindInMap" : [ "AWSInstanceType2Arch", { "Ref" : "InstanceType" }, "Arch" ] } ] }, "SecurityGroups" : [ {"Ref" : "SharePointFoundationSecurityGroup"} ], "KeyName" : { "Ref" : "KeyPairName" }, "UserData" : { "Fn::Base64" : { "Fn::Join" : ["", [ "" ]]}} In this section, the UserData property contains a cmd.exe script that will be executed by cfn-init, surrounded by " ] ] } } } }, "LogGroup": { "Type": "AWS::Logs::LogGroup", "Properties": { "RetentionInDays": 7 } }, "404MetricFilter": { "Type": "AWS::Logs::MetricFilter", "Properties": { "LogGroupName": { "Ref": "LogGroup" }, "FilterPattern": "[timestamps,serverip, method, uri, query, port, dash, clientip, useragent, status_code = 404, ...]", "MetricTransformations": [ { "MetricValue": "1", "MetricNamespace": "test/404s", "MetricName": "test404Count" } ] } }, "404Alarm": { "Type": "AWS::CloudWatch::Alarm", "Properties": { "AlarmDescription": "The number of 404s is greater than 2 over 2 minutes", "MetricName": "test404Count", "Namespace": "test/404s", "Statistic": "Sum", "Period": "60", "EvaluationPeriods": "2", "Threshold": "2", "AlarmActions": [ { "Ref": "AlarmNotificationTopic" } ], "ComparisonOperator": "GreaterThanThreshold" } }, "AlarmNotificationTopic": { "Type": "AWS::SNS::Topic", "Properties": { "Subscription": [ { "Endpoint": { "Ref": "OperatorEmail" }, "Protocol": "email" } ] } } }, API Version 2010-05-15 326 AWS CloudFormation User Guide CloudWatch Logs "Outputs": { "InstanceId": { "Description": "The instance ID of the web server", "Value": { "Ref": "WebServerHost" } }, "WebsiteURL" : { "Value" : { "Fn::Join" : ["", ["http://", { "Fn::GetAtt" : [ "WebServerHost", "PublicDnsName" ]}]] }, "Description" : "URL for newly created IIS web server" }, "PublicIP": { "Description": "Public IP address of the web server", "Value": { "Fn::GetAtt": [ "WebServerHost", "PublicIp" ] } }, "CloudWatchLogGroupName": { "Description": "The name of the CloudWatch log group", "Value": { "Ref": "LogGroup" } } } } YAML AWSTemplateFormatVersion: '2010-09-09' Description: Sample template that sets up and configures CloudWatch logs on Windows 2012R2 instance instance. Parameters: KeyPair: Description: Name of an existing EC2 KeyPair to enable RDP access to the instances Type: AWS::EC2::KeyPair::KeyName ConstraintDescription: must be the name of an existing EC2 KeyPair. RDPLocation: Description: The IP address range that can be used to RDP to the EC2 instances Type: String MinLength: '9' MaxLength: '18' Default: 0.0.0.0/0 AllowedPattern: (\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})/(\d{1,2}) ConstraintDescription: must be a valid IP CIDR range of the form x.x.x.x/x. OperatorEmail: Description: Email address to notify if there are any scaling operations Type: String Mappings: AWSAMIRegionMap: ap-northeast-1: WS2012R2: ami-cb7429ac ap-northeast-2: WS2012R2: ami-34d4075a ap-south-1: WS2012R2: ami-dd8cfcb2 ap-southeast-1: WS2012R2: ami-e5a51786 ap-southeast-2: WS2012R2: ami-a63934c5 API Version 2010-05-15 327 AWS CloudFormation User Guide CloudWatch Logs ca-central-1: WS2012R2: ami-d242ffb6 eu-central-1: WS2012R2: ami-d029febf eu-west-1: WS2012R2: ami-d3dee9b5 eu-west-2: WS2012R2: ami-e5b3a681 sa-east-1: WS2012R2: ami-83f594ef us-east-1: WS2012R2: ami-11e84107 us-east-2: WS2012R2: ami-d85773bd us-west-1: WS2012R2: ami-052d7565 us-west-2: WS2012R2: ami-09f47d69 Resources: WebServerSecurityGroup: Type: AWS::EC2::SecurityGroup Properties: GroupDescription: Enable HTTP access via port 80 and RDP access via port 3389 SecurityGroupIngress: - IpProtocol: tcp FromPort: '80' ToPort: '80' CidrIp: 0.0.0.0/0 - IpProtocol: tcp FromPort: '3389' ToPort: '3389' CidrIp: !Ref 'RDPLocation' LogRole: Type: AWS::IAM::Role Properties: AssumeRolePolicyDocument: Version: '2012-10-17' Statement: - Effect: Allow Principal: Service: - ec2.amazonaws.com Action: - sts:AssumeRole ManagedPolicyArns: - arn:aws:iam::aws:policy/service-role/AmazonEC2RoleforSSM Path: / Policies: - PolicyName: LogRolePolicy PolicyDocument: Version: '2012-10-17' Statement: - Effect: Allow Action: - logs:Create* - logs:PutLogEvents - s3:GetObject Resource: - arn:aws:logs:*:*:* - arn:aws:s3:::* LogRoleInstanceProfile: Type: AWS::IAM::InstanceProfile Properties: Path: / Roles: - !Ref 'LogRole' API Version 2010-05-15 328 AWS CloudFormation User Guide CloudWatch Logs WebServerHost: Type: AWS::EC2::Instance CreationPolicy: ResourceSignal: Timeout: PT15M Metadata: AWS::CloudFormation::Init: configSets: config: - 00-ConfigureCWLogs - 01-InstallWebServer - 02-ConfigureApplication - 03-Finalize 00-ConfigureCWLogs: files: C:\Program Files\Amazon\SSM\Plugins\awsCloudWatch \AWS.EC2.Windows.CloudWatch.json: content: !Sub | { "EngineConfiguration": { "Components": [ { "FullName": "AWS.EC2.Windows.CloudWatch.EventLog.EventLogInputComponent,AWS.EC2.Windows.CloudWatch", "Id": "ApplicationEventLog", "Parameters": { "Levels": "7", "LogName": "Application" } }, { "FullName": "AWS.EC2.Windows.CloudWatch.EventLog.EventLogInputComponent,AWS.EC2.Windows.CloudWatch", "Id": "SystemEventLog", "Parameters": { "Levels": "7", "LogName": "System" } }, { "FullName": "AWS.EC2.Windows.CloudWatch.EventLog.EventLogInputComponent,AWS.EC2.Windows.CloudWatch", "Id": "SecurityEventLog", "Parameters": { "Levels": "7", "LogName": "Security" } }, { "FullName": "AWS.EC2.Windows.CloudWatch.CustomLog.CustomLogInputComponent,AWS.EC2.Windows.CloudWatch", "Id": "EC2ConfigLog", "Parameters": { "CultureName": "en-US", "Encoding": "ASCII", "Filter": "EC2ConfigLog.txt", "LogDirectoryPath": "C:\\Program Files\\Amazon\ \Ec2ConfigService\\Logs", "TimeZoneKind": "UTC", "TimestampFormat": "yyyy-MM-ddTHH:mm:ss.fffZ:" } }, { "FullName": "AWS.EC2.Windows.CloudWatch.CustomLog.CustomLogInputComponent,AWS.EC2.Windows.CloudWatch", "Id": "CfnInitLog", API Version 2010-05-15 329 AWS CloudFormation User Guide CloudWatch Logs }, { "Parameters": { "CultureName": "en-US", "Encoding": "ASCII", "Filter": "cfn-init.log", "LogDirectoryPath": "C:\\cfn\\log", "TimeZoneKind": "Local", "TimestampFormat": "yyyy-MM-dd HH:mm:ss,fff" } "FullName": "AWS.EC2.Windows.CloudWatch.CustomLog.CustomLogInputComponent,AWS.EC2.Windows.CloudWatch", "Id": "IISLogs", "Parameters": { "CultureName": "en-US", "Encoding": "UTF-8", "Filter": "", "LineCount": "3", "LogDirectoryPath": "C:\\inetpub\\logs\\LogFiles\ \W3SVC1", "TimeZoneKind": "UTC", "TimestampFormat": "yyyy-MM-dd HH:mm:ss" } }, { "FullName": "AWS.EC2.Windows.CloudWatch.PerformanceCounterComponent.PerformanceCounterInputComponent,AWS.EC2.Windo "Id": "MemoryPerformanceCounter", "Parameters": { "CategoryName": "Memory", "CounterName": "Available MBytes", "DimensionName": "", "DimensionValue": "", "InstanceName": "", "MetricName": "Memory", "Unit": "Megabytes" } }, { "FullName": "AWS.EC2.Windows.CloudWatch.CloudWatchLogsOutput,AWS.EC2.Windows.CloudWatch", "Id": "CloudWatchApplicationEventLog", "Parameters": { "AccessKey": "", "LogGroup": "${LogGroup}", "LogStream": "{instance_id}/ApplicationEventLog", "Region": "${AWS::Region}", "SecretKey": "" } }, { "FullName": "AWS.EC2.Windows.CloudWatch.CloudWatchLogsOutput,AWS.EC2.Windows.CloudWatch", "Id": "CloudWatchSystemEventLog", "Parameters": { "AccessKey": "", "LogGroup": "${LogGroup}", "LogStream": "{instance_id}/SystemEventLog", "Region": "${AWS::Region}", "SecretKey": "" } }, { "FullName": "AWS.EC2.Windows.CloudWatch.CloudWatchLogsOutput,AWS.EC2.Windows.CloudWatch", "Id": "CloudWatchSecurityEventLog", API Version 2010-05-15 330 AWS CloudFormation User Guide CloudWatch Logs }, { "Parameters": { "AccessKey": "", "LogGroup": "${LogGroup}", "LogStream": "{instance_id}/SecurityEventLog", "Region": "${AWS::Region}", "SecretKey": "" } "FullName": "AWS.EC2.Windows.CloudWatch.CloudWatchLogsOutput,AWS.EC2.Windows.CloudWatch", "Id": "CloudWatchEC2ConfigLog", "Parameters": { "AccessKey": "", "LogGroup": "${LogGroup}", "LogStream": "{instance_id}/EC2ConfigLog", "Region": "${AWS::Region}", "SecretKey": "" } }, { "FullName": "AWS.EC2.Windows.CloudWatch.CloudWatchLogsOutput,AWS.EC2.Windows.CloudWatch", "Id": "CloudWatchCfnInitLog", "Parameters": { "AccessKey": "", "LogGroup": "${LogGroup}", "LogStream": "{instance_id}/CfnInitLog", "Region": "${AWS::Region}", "SecretKey": "" } }, { "FullName": "AWS.EC2.Windows.CloudWatch.CloudWatchLogsOutput,AWS.EC2.Windows.CloudWatch", "Id": "CloudWatchIISLogs", "Parameters": { "AccessKey": "", "LogGroup": "${LogGroup}", "LogStream": "{instance_id}/IISLogs", "Region": "${AWS::Region}", "SecretKey": "" } }, { "FullName": "AWS.EC2.Windows.CloudWatch.CloudWatch.CloudWatchOutputComponent,AWS.EC2.Windows.CloudWatch", "Id": "CloudWatch", "Parameters": { "AccessKey": "", "NameSpace": "Windows/Default", "Region": "${AWS::Region}", "SecretKey": "" } } ], "Flows": { "Flows": [ "ApplicationEventLog,CloudWatchApplicationEventLog", "SystemEventLog,CloudWatchSystemEventLog", "SecurityEventLog,CloudWatchSecurityEventLog", "EC2ConfigLog,CloudWatchEC2ConfigLog", "CfnInitLog,CloudWatchCfnInitLog", "IISLogs,CloudWatchIISLogs", "MemoryPerformanceCounter,CloudWatch" ] API Version 2010-05-15 331 AWS CloudFormation User Guide CloudWatch Logs }, "PollInterval": "00:00:05" }, "IsEnabled": true } commands: 0-enableSSM: command: 'powershell.exe -Command "Set-Service -Name AmazonSSMAgent StartupType Automatic" ' waitAfterCompletion: '0' 1-restartSSM: command: 'powershell.exe -Command "Restart-Service AmazonSSMAgent "' waitAfterCompletion: '30' 01-InstallWebServer: commands: 01_install_webserver: command: powershell.exe -Command "Install-WindowsFeature Web-Server IncludeAllSubFeature" waitAfterCompletion: '0' 02-ConfigureApplication: files: c:\Inetpub\wwwroot\index.htm: content: ' Test Application Page

Congratulations !! Your IIS server is configured.

' 03-Finalize: commands: 00_signal_success: command: !Sub 'cfn-signal.exe -e 0 --resource WebServerHost --stack ${AWS::StackName} --region ${AWS::Region}' waitAfterCompletion: '0' Properties: KeyName: !Ref 'KeyPair' ImageId: !FindInMap [AWSAMIRegionMap, !Ref 'AWS::Region', WS2012R2] InstanceType: t2.xlarge SecurityGroupIds: - !Ref 'WebServerSecurityGroup' IamInstanceProfile: !Ref 'LogRoleInstanceProfile' UserData: Fn::Base64: !Sub | LogGroup: Type: AWS::Logs::LogGroup Properties: RetentionInDays: 7 404MetricFilter: Type: AWS::Logs::MetricFilter Properties: LogGroupName: !Ref 'LogGroup' API Version 2010-05-15 332 AWS CloudFormation User Guide DynamoDB FilterPattern: '[timestamps, serverip, method, uri, query, port, dash, clientip, useragent, status_code = 404, ...]' MetricTransformations: - MetricValue: '1' MetricNamespace: test/404s MetricName: test404Count 404Alarm: Type: AWS::CloudWatch::Alarm Properties: AlarmDescription: The number of 404s is greater than 2 over 2 minutes MetricName: test404Count Namespace: test/404s Statistic: Sum Period: '60' EvaluationPeriods: '2' Threshold: '2' AlarmActions: - !Ref 'AlarmNotificationTopic' ComparisonOperator: GreaterThanThreshold AlarmNotificationTopic: Type: AWS::SNS::Topic Properties: Subscription: - Endpoint: !Ref 'OperatorEmail' Protocol: email Outputs: InstanceId: Description: The instance ID of the web server Value: !Ref 'WebServerHost' WebsiteURL: Value: !Sub 'http://${WebServerHost.PublicDnsName}' Description: URL for newly created IIS web server PublicIP: Description: Public IP address of the web server Value: !GetAtt 'WebServerHost.PublicIp' CloudWatchLogGroupName: Description: The name of the CloudWatch log group Value: !Ref 'LogGroup' See Also For more information about CloudWatch Logs resources, see AWS::Logs::LogGroup (p. 1270) or AWS::Logs::MetricFilter (p. 1273). Amazon DynamoDB Template Snippets Topics • Application Auto Scaling with an Amazon DynamoDB Table (p. 333) • See Also (p. 337) Application Auto Scaling with an Amazon DynamoDB Table This example sets up Application Auto Scaling for a AWS::DynamoDB::Table resource. The template defines a TargetTrackingScaling scaling policy that scales up the WriteCapacityUnits throughput for the table. JSON { API Version 2010-05-15 333 AWS CloudFormation User Guide DynamoDB "Resources": { "DDBTable": { "Type": "AWS::DynamoDB::Table", "Properties": { "AttributeDefinitions": [ { "AttributeName": "ArtistId", "AttributeType": "S" }, { "AttributeName": "Concert", "AttributeType": "S" }, { "AttributeName": "TicketSales", "AttributeType": "S" } ], "KeySchema": [ { "AttributeName": "ArtistId", "KeyType": "HASH" }, { "AttributeName": "Concert", "KeyType": "RANGE" } ], "GlobalSecondaryIndexes": [ { "IndexName": "GSI", "KeySchema": [ { "AttributeName": "TicketSales", "KeyType": "HASH" } ], "Projection": { "ProjectionType": "KEYS_ONLY" }, "ProvisionedThroughput": { "ReadCapacityUnits": 5, "WriteCapacityUnits": 5 } } ], "ProvisionedThroughput": { "ReadCapacityUnits": 5, "WriteCapacityUnits": 5 } } }, "WriteCapacityScalableTarget": { "Type": "AWS::ApplicationAutoScaling::ScalableTarget", "Properties": { "MaxCapacity": 15, "MinCapacity": 5, "ResourceId": { "Fn::Join": [ "/", [ "table", { "Ref": "DDBTable" } ] ] }, "RoleARN": { "Fn::GetAtt": ["ScalingRole", "Arn"] API Version 2010-05-15 334 AWS CloudFormation User Guide DynamoDB }, "ScalableDimension": "dynamodb:table:WriteCapacityUnits", "ServiceNamespace": "dynamodb" } }, "ScalingRole": { "Type": "AWS::IAM::Role", "Properties": { "AssumeRolePolicyDocument": { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Principal": { "Service": [ "application-autoscaling.amazonaws.com" ] }, "Action": [ "sts:AssumeRole" ] } ] }, "Path": "/", "Policies": [ { "PolicyName": "root", "PolicyDocument": { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": [ "dynamodb:DescribeTable", "dynamodb:UpdateTable", "cloudwatch:PutMetricAlarm", "cloudwatch:DescribeAlarms", "cloudwatch:GetMetricStatistics", "cloudwatch:SetAlarmState", "cloudwatch:DeleteAlarms" ], "Resource": "*" } ] } } ] } }, "WriteScalingPolicy": { "Type": "AWS::ApplicationAutoScaling::ScalingPolicy", "Properties": { "PolicyName": "WriteAutoScalingPolicy", "PolicyType": "TargetTrackingScaling", "ScalingTargetId": { "Ref": "WriteCapacityScalableTarget" }, "TargetTrackingScalingPolicyConfiguration": { "TargetValue": 50.0, "ScaleInCooldown": 60, "ScaleOutCooldown": 60, "PredefinedMetricSpecification": { "PredefinedMetricType": "DynamoDBWriteCapacityUtilization" } } API Version 2010-05-15 335 AWS CloudFormation User Guide DynamoDB } } } } YAML Resources: DDBTable: Type: AWS::DynamoDB::Table Properties: AttributeDefinitions: AttributeName: "ArtistId" AttributeType: "S" AttributeName: "Concert" AttributeType: "S" AttributeName: "TicketSales" AttributeType: "S" KeySchema: AttributeName: "ArtistId" KeyType: "HASH" AttributeName: "Concert" KeyType: "RANGE" GlobalSecondaryIndexes: IndexName: "GSI" KeySchema: AttributeName: "TicketSales" KeyType: "HASH" Projection: ProjectionType: "KEYS_ONLY" ProvisionedThroughput: ReadCapacityUnits: 5 WriteCapacityUnits: 5 ProvisionedThroughput: ReadCapacityUnits: 5 WriteCapacityUnits: 5 WriteCapacityScalableTarget: Type: AWS::ApplicationAutoScaling::ScalableTarget Properties: MaxCapacity: 15 MinCapacity: 5 ResourceId: !Join - / - - table - !Ref DDBTable RoleARN: !GetAtt ScalingRole.Arn ScalableDimension: dynamodb:table:WriteCapacityUnits ServiceNamespace: dynamodb ScalingRole: Type: AWS::IAM::Role Properties: AssumeRolePolicyDocument: Version: "2012-10-17" Statement: Effect: "Allow" Principal: API Version 2010-05-15 336 AWS CloudFormation User Guide Amazon EC2 Service: - application-autoscaling.amazonaws.com Action: - "sts:AssumeRole" Path: "/" Policies: PolicyName: "root" PolicyDocument: Version: "2012-10-17" Statement: Effect: "Allow" Action: - "dynamodb:DescribeTable" - "dynamodb:UpdateTable" - "cloudwatch:PutMetricAlarm" - "cloudwatch:DescribeAlarms" - "cloudwatch:GetMetricStatistics" - "cloudwatch:SetAlarmState" - "cloudwatch:DeleteAlarms" Resource: "*" WriteScalingPolicy: Type: AWS::ApplicationAutoScaling::ScalingPolicy Properties: PolicyName: WriteAutoScalingPolicy PolicyType: TargetTrackingScaling ScalingTargetId: !Ref WriteCapacityScalableTarget TargetTrackingScalingPolicyConfiguration: TargetValue: 50.0 ScaleInCooldown: 60 ScaleOutCooldown: 60 PredefinedMetricSpecification: PredefinedMetricType: DynamoDBWriteCapacityUtilization See Also For more information about DynamoDB resources, see AWS::DynamoDB::Table (p. 848). Amazon EC2 Template Snippets EC2 Block Device Mapping Examples EC2 Instance with Block Device Mapping JSON "Ec2Instance" : { "Type" : "AWS::EC2::Instance", "Properties" : { "ImageId" : { "Fn::FindInMap" : [ "AWSRegionArch2AMI", { "Ref" : "AWS::Region" }, { "Fn::FindInMap" : [ "AWSInstanceType2Arch", { "Ref" : "InstanceType" }, "Arch" ] } ] }, "KeyName" : { "Ref" : "KeyName" }, "InstanceType" : { "Ref" : "InstanceType" }, "SecurityGroups" : [{ "Ref" : "Ec2SecurityGroup" }], "BlockDeviceMappings" : [ { "DeviceName" : "/dev/sda1", "Ebs" : { "VolumeSize" : "50" } },{ API Version 2010-05-15 337 AWS CloudFormation User Guide Amazon EC2 } } ] } "DeviceName" : "/dev/sdm", "Ebs" : { "VolumeSize" : "100" } YAML EC2Instance: Type: AWS::EC2::Instance Properties: ImageId: !FindInMap [ AWSRegionArch2AMI, !Ref 'AWS::Region' , !FindInMap [ AWSInstanceType2Arch, !Ref InstanceType, Arch ] ] KeyName: !Ref KeyName InstanceType: !Ref InstanceType SecurityGroups: - !Ref Ec2SecurityGroup BlockDeviceMappings: DeviceName: /dev/sda1 Ebs: VolumeSize: 50 DeviceName: /dev/sdm Ebs: VolumeSize: 100 EC2 Instance with Ephemeral Drives JSON "Ec2Instance" : { "Type" : "AWS::EC2::Instance", "Properties" : { "ImageId" : { "Fn::FindInMap" : [ "AWSRegionArch2AMI", { "Ref" : "AWS::Region" }, "PV64" ]}, "KeyName" : { "Ref" : "KeyName" }, "InstanceType" : "m1.small", "SecurityGroups" : [{ "Ref" : "Ec2SecurityGroup" }], "BlockDeviceMappings" : [ { "DeviceName" : "/dev/sdc", "VirtualName" : "ephemeral0" } ] } } YAML EC2Instance: Type: AWS::EC2::Instance Properties: ImageId: !FindInMap [ AWSRegionArch2AMI, !Ref 'AWS::Region', PV64 ] KeyName: !Ref KeyName InstanceType: m1.small SecurityGroups: - !Ref Ec2SecurityGroup BlockDeviceMappings: - API Version 2010-05-15 338 AWS CloudFormation User Guide Amazon EC2 DeviceName: /dev/sdc VirtualName: ephemeral0 Assigning an Amazon EC2 Elastic IP Using AWS::EC2::EIP Snippet This example shows how to allocate an Amazon EC2 Elastic IP address and assign it to an Amazon EC2 instance using a AWS::EC2::EIP resource (p. 868). JSON "MyEIP" : { "Type" : "AWS::EC2::EIP", "Properties" : { "InstanceId" : { "Ref" : "logical name of an AWS::EC2::Instance resource" } } } YAML MyEIP: Type: AWS::EC2::EIP Properties: InstanceId: !Ref Logical name of an AWS::EC2::Instance resource Assigning an Existing Elastic IP to an Amazon EC2 instance using AWS::EC2::EIPAssociation Snippet This example shows how to assign an existing Amazon EC2 Elastic IP address to an Amazon EC2 instance using an AWS::EC2::EIPAssociation resource (p. 870). JSON "IPAssoc" : { "Type" : "AWS::EC2::EIPAssociation", "Properties" : { "InstanceId" : { "Ref" : "logical name of an AWS::EC2::Instance resource" }, "EIP" : "existing Elastic IP address" } } YAML IPAssoc: Type: AWS::EC2::EIPAssociation Properties: InstanceId: !Ref Logical name of an AWS::EC2::Instance resource EIP: existing Elastic IP Address Assigning an Existing VPC Elastic IP to an Amazon EC2 instance using AWS::EC2::EIPAssociation Snippet This example shows how to assign an existing VPC Elastic IP address to an Amazon EC2 instance using an AWS::EC2::EIPAssociation resource (p. 870). API Version 2010-05-15 339 AWS CloudFormation User Guide Amazon EC2 JSON "VpcIPAssoc" : { "Type" : "AWS::EC2::EIPAssociation", "Properties" : { "InstanceId" : { "Ref" : "logical name of an AWS::EC2::Instance resource" }, "AllocationId" : "existing VPC Elastic IP allocation ID" } } YAML VpcIPAssoc: Type: AWS::EC2::EIPAssociation Properties: InstanceId: !Ref Logical name of an AWS::EC2::Instance resource AllocationId: Existing VPC Elastic IP allocation ID Elastic Network Interface (ENI) Template Snippets VPC_EC2_Instance_With_ENI Sample template showing how to create an instance with two elastic network interface (ENI). The sample assumes you have already created a VPC. JSON "Resources" : { "ControlPortAddress" : { "Type" : "AWS::EC2::EIP", "Properties" : { "Domain" : "vpc" } }, "AssociateControlPort" : { "Type" : "AWS::EC2::EIPAssociation", "Properties" : { "AllocationId" : { "Fn::GetAtt" : [ "ControlPortAddress", "AllocationId" ]}, "NetworkInterfaceId" : { "Ref" : "controlXface" } } }, "WebPortAddress" : { "Type" : "AWS::EC2::EIP", "Properties" : { "Domain" : "vpc" } }, "AssociateWebPort" : { "Type" : "AWS::EC2::EIPAssociation", "Properties" : { "AllocationId" : { "Fn::GetAtt" : [ "WebPortAddress", "AllocationId" ]}, "NetworkInterfaceId" : { "Ref" : "webXface" } } }, "SSHSecurityGroup" : { "Type" : "AWS::EC2::SecurityGroup", "Properties" : { "VpcId" : { "Ref" : "VpcId" }, "GroupDescription" : "Enable SSH access via port 22", API Version 2010-05-15 340 AWS CloudFormation User Guide Amazon EC2 "SecurityGroupIngress" : [ { "IpProtocol" : "tcp", "FromPort" : "22", "ToPort" : "22", "CidrIp" : "0.0.0.0/0" } ] } }, "WebSecurityGroup" : { "Type" : "AWS::EC2::SecurityGroup", "Properties" : { "VpcId" : { "Ref" : "VpcId" }, "GroupDescription" : "Enable HTTP access via user defined port", "SecurityGroupIngress" : [ { "IpProtocol" : "tcp", "FromPort" : 80, "ToPort" : 80, "CidrIp" : "0.0.0.0/0" } ] } }, "controlXface" : { "Type" : "AWS::EC2::NetworkInterface", "Properties" : { "SubnetId" : { "Ref" : "SubnetId" }, "Description" :"Interface for control traffic such as SSH", "GroupSet" : [ {"Ref" : "SSHSecurityGroup"} ], "SourceDestCheck" : "true", "Tags" : [ {"Key" : "Network", "Value" : "Control"}] } }, "webXface" : { "Type" : "AWS::EC2::NetworkInterface", "Properties" : { "SubnetId" : { "Ref" : "SubnetId" }, "Description" :"Interface for web traffic", "GroupSet" : [ {"Ref" : "WebSecurityGroup"} ], "SourceDestCheck" : "true", "Tags" : [ {"Key" : "Network", "Value" : "Web"}] } }, "Ec2Instance" : { "Type" : "AWS::EC2::Instance", "Properties" : { "ImageId" : { "Fn::FindInMap" : [ "RegionMap", { "Ref" : "AWS::Region" }, "AMI" ]}, "KeyName" : { "Ref" : "KeyName" }, "NetworkInterfaces" : [ { "NetworkInterfaceId" : {"Ref" : "controlXface"}, "DeviceIndex" : "0" }, { "NetworkInterfaceId" : {"Ref" : "webXface"}, "DeviceIndex" : "1" }], "Tags" : [ {"Key" : "Role", "Value" : "Test Instance"}], "UserData" : {"Fn::Base64" : { "Fn::Join" : ["",[ "#!/bin/bash -ex","\n", "\n","yum install ec2-net-utils -y","\n", "ec2ifup eth1","\n", "service httpd start"]]} } } } } YAML Resources: ControlPortAddress: Type: AWS::EC2::EIP Properties: Domain: vpc AssociateControlPort: Type: AWS::EC2::EIPAssociation Properties: AllocationId: !GetAtt ControlPortAddress.AllocationId NetworkInterfaceId: !Ref controlXface API Version 2010-05-15 341 AWS CloudFormation User Guide Amazon EC2 WebPortAddress: Type: AWS::EC2::EIP Properties: Domain: vpc AssociateWebPort: Type: AWS::EC2::EIPAssociation Properties: AllocationId: !GetAtt WebPortAddress.AllocationId NetworkInterfaceId: !Ref webXface SSHSecurityGroup: Type: AWS::EC2::SecurityGroup Properties: VpcId: !Ref VpcId GroupDescription: Enable SSH access via port 22 SecurityGroupIngress: - CidrIp: 0.0.0.0/0 FromPort: 22 IpProtocol: tcp ToPort: 22 WebSecurityGroup: Type: AWS::EC2::SecurityGroup Properties: VpcId: !Ref VpcId GroupDescription: Enable HTTP access via user defined port SecurityGroupIngress: - CidrIp: 0.0.0.0/0 FromPort: 80 IpProtocol: tcp ToPort: 80 controlXface: Type: AWS::EC2::NetworkInterface Properties: SubnetId: !Ref SubnetId Description: Interface for controlling traffic such as SSH GroupSet: - !Ref SSHSecurityGroup SourceDestCheck: true Tags: Key: Network Value: Control webXface: Type: AWS::EC2::NetworkInterface Properties: SubnetId: !Ref SubnetId Description: Interface for controlling traffic such as SSH GroupSet: - !Ref WebSecurityGroup SourceDestCheck: true Tags: Key: Network Value: Web Ec2Instance: Type: AWS::EC2::Instance Properties: ImageId: !FindInMap [ RegionMap, !Ref 'AWS::Region', AMI ] KeyName: !Ref KeyName NetworkInterfaces: NetworkInterfaceId: !Ref controlXface DeviceIndex: 0 NetworkInterfaceId: !Ref webXface DeviceIndex: 1 Tags: API Version 2010-05-15 342 AWS CloudFormation User Guide Amazon EC2 - Key: Role Value: Test Instance UserData: Fn::Base64: !Sub | #!/bin/bash -xe yum install ec2-net-utils -y ec2ifup eth1 service httpd start Amazon EC2 Instance Resource This snippet shows a simple AWS::EC2::Instance resource. JSON "MyInstance" : { "Type" : "AWS::EC2::Instance", "Properties" : { "AvailabilityZone" : "us-east-1a", "ImageId" : "ami-20b65349" } } YAML MyInstance: Type: AWS::EC2::Instance Properties: AvailabilityZone: us-east-1a ImageId: ami-20b65349 Amazon EC2 Instance with Volume, Tag, and UserData Properties This snippet shows an AWS::EC2::Instance resource with one Amazon EC2 volume, one tag, and a user data property. An AWS::EC2::SecurityGroup resource, an AWS::SNS::Topic resource, and an AWS::EC2::Volume resource all must be defined in the same template. Also, the reference to KeyName is a parameters that must be defined in the Parameters section of the template. JSON "MyInstance" : { "Type" : "AWS::EC2::Instance", "Properties" : { "KeyName" : { "Ref" : "KeyName" }, "SecurityGroups" : [ { "Ref" : "logical name of AWS::EC2::SecurityGroup resource" } ], "UserData" : { "Fn::Base64" : { "Fn::Join" : [ ":", [ "PORT=80", "TOPIC=", { "Ref" : "logical name of an AWS::SNS::Topic resource" } ] ] } }, API Version 2010-05-15 343 AWS CloudFormation User Guide Amazon EC2 "InstanceType" : "m1.small", "AvailabilityZone" : "us-east-1a", "ImageId" : "ami-1e817677", "Volumes" : [ { "VolumeId" : { "Ref" : "logical name of AWS::EC2::Volume resource" }, "Device" : "/dev/sdk" } ], } "Tags" : [ { "Key" : "Name", "Value" : "MyTag" } ] } YAML MyInstance: Type: AWS::EC2::Instance Properties: KeyName: !Ref KeyName SecurityGroups: - !Ref logical name of AWS::EC2::SecurityGroup resource UserData: Fn::Base64: !Sub | PORT=80 TOPIC=${ logical name of an AWS::SNS::Topic resource } InstanceType: m1.small AvailabilityZone: us-east-1a ImageId: ami-1e817677 Volumes: VolumeId: !Ref logical name of AWS::EC2::Volume resource Device: /dev/sdk Tags: Key: Name Value: MyTag Amazon EC2 Instance Resource with an Amazon SimpleDB Domain This snippet shows an AWS::EC2::Instance resource with an Amazon SimpleDB domain specified in the UserData. JSON "MyInstance" : { "Type" : "AWS::EC2::Instance", "Properties" : { "UserData" : { "Fn::Base64" : { "Fn::Join" : [ "", [ "Domain=", { "Ref" : "logical name of an AWS::SDB::Domain resource" } ] ] } }, API Version 2010-05-15 344 AWS CloudFormation User Guide Amazon EC2 } "AvailabilityZone" : "us-east-1a", "ImageId" : "ami-20b65349" } YAML MyInstance: Type: AWS::EC2::Instance Properties: UserData: Fn::Base64: !Sub | Domain=${ logical name of an AWS::SDB::Domain resource } AvailabilityZone: us-east-1a ImageId: ami-20b65349 Amazon EC2 Security Group Resource with Two CIDR Range Ingress Rules This snippet shows an AWS::EC2::SecurityGroup resource that describes two ingress rules giving access to a specified CIDR range for the TCP protocol on the specified ports. JSON "ServerSecurityGroup" : { "Type" : "AWS::EC2::SecurityGroup", "Properties" : { "GroupDescription" : "allow connections from specified CIDR ranges", "SecurityGroupIngress" : [ { "IpProtocol" : "tcp", "FromPort" : "80", "ToPort" : "80", "CidrIp" : "0.0.0.0/0" },{ "IpProtocol" : "tcp", "FromPort" : "22", "ToPort" : "22", "CidrIp" : "192.168.1.1/32" } ] } } YAML ServerSecurityGroup: Type: AWS::EC2::SecurityGroup Properties: GroupDescription: allow connections from specified CIDR ranges SecurityGroupIngress: - IpProtocol: tcp FromPort: 80 ToPort: 80 CidrIp: 0.0.0.0/0 - IpProtocol: tcp FromPort: 22 ToPort: 22 CidrIp: 192.168.1.1/32 API Version 2010-05-15 345 AWS CloudFormation User Guide Amazon EC2 Amazon EC2 Security Group Resource with Two Security Group Ingress Rules This snippet shows an AWS::EC2::SecurityGroup resource that describes two security group ingress rules. The first ingress rule grants access to the existing security group myadminsecuritygroup, which is owned by the 1234-5678-9012 AWS account, for the TCP protocol on port 22. The second ingress rule grants access to the security group mysecuritygroupcreatedincfn for TCP on port 80. This ingress rule uses the Ref intrinsic function to refer to a security group (whose logical name is mysecuritygroupcreatedincfn) created in the same template. You must declare a value for both the SourceSecurityGroupName and SourceSecurityGroupOwnerId properties. JSON "ServerSecurityGroupBySG" : { "Type" : "AWS::EC2::SecurityGroup", "Properties" : { "GroupDescription" : "allow connections from specified source security group", "SecurityGroupIngress" : [ { "IpProtocol" : "tcp", "FromPort" : "22", "ToPort" : "22", "SourceSecurityGroupName" : "myadminsecuritygroup", "SourceSecurityGroupOwnerId" : "123456789012" }, { "IpProtocol" : "tcp", "FromPort" : "80", "ToPort" : "80", "SourceSecurityGroupName" : {"Ref" : "mysecuritygroupcreatedincfn"} } ] } } YAML ServerSecurityGroupBySG: Type: AWS::EC2::SecurityGroup Properties: GroupDescription: allow connections from specified source security group SecurityGroupIngress: - IpProtocol: tcp FromPort: 80 ToPort: 80 SourceSecurityGroupName: myadminsecuritygroup SourceSecurityGroupOwnerId: 123456789012 - IpProtocol: tcp FromPort: 80 ToPort: 80 SourceSecurityGroupName: !Ref mysecuritygroupcreatedincfn Amazon EC2 Security Group Resource with LoadBalancer Ingress Rule This template shows an AWS::EC2::SecurityGroup resource that contains a security group ingress rule that grants access to the LoadBalancer myELB for TCP on port 80. Note that the rule uses the API Version 2010-05-15 346 AWS CloudFormation User Guide Amazon EC2 SourceSecurityGroup.OwnerAlias and SourceSecurityGroup.GroupName properties of the myELB resource to specify the source security group of the LoadBalancer. JSON { } "AWSTemplateFormatVersion": "2010-09-09", "Resources": { "myELB": { "Type": "AWS::ElasticLoadBalancing::LoadBalancer", "Properties": { "AvailabilityZones": [ "eu-west-1a" ], "Listeners": [ { "LoadBalancerPort": "80", "InstancePort": "80", "Protocol": "HTTP" } ] } }, "myELBIngressGroup": { "Type": "AWS::EC2::SecurityGroup", "Properties": { "GroupDescription": "ELB ingress group", "SecurityGroupIngress": [ { "IpProtocol": "tcp", "FromPort": "80", "ToPort": "80", "SourceSecurityGroupOwnerId": { "Fn::GetAtt": [ "myELB", "SourceSecurityGroup", "OwnerAlias" ] }, "SourceSecurityGroupName": { "Fn::GetAtt": [ "myELB", "SourceSecurityGroup", "GroupName" ] } } ] } } } YAML AWSTemplateFormatVersion: 2010-09-09 Resources: myELB: Type: AWS::ElasticLoadBalancing::LoadBalancer Properties: AvailabilityZones: - eu-west-1a Listeners: API Version 2010-05-15 347 AWS CloudFormation User Guide Amazon EC2 - LoadBalancerPort: '80' InstancePort: '80' Protocol: HTTP myELBIngressGroup: Type: AWS::EC2::SecurityGroup Properties: GroupDescription: ELB ingress group SecurityGroupIngress: - IpProtocol: tcp FromPort: '80' ToPort: '80' SourceSecurityGroupOwnerId: !GetAtt myELB.SourceSecurityGroup.OwnerAlias SourceSecurityGroupName: !GetAtt myELB.SourceSecurityGroup.GroupName Using AWS::EC2::SecurityGroupIngress to Create Mutually Referencing Amazon EC2 Security Group Resources This snippet shows two AWS::EC2::SecurityGroupIngress resources that add mutual ingress rules to the EC2 security groups SGroup1 and SGroup2. The SGroup1Ingress resource enables ingress from SGroup2 through TCP/IP port 80 to SGroup1. The SGroup2Ingress resource enables ingress from SGroup1 through TCP/IP port 80 to SGroup2. Note If you are using an Amazon VPC, use the AWS::EC2::SecurityGroup resource and specify the VpcId property. JSON "SGroup1" : { "Type" : "AWS::EC2::SecurityGroup", "Properties" : { "GroupDescription" : "EC2 Instance access" } }, "SGroup2" : { "Type" : "AWS::EC2::SecurityGroup", "Properties" : { "GroupDescription" : "EC2 Instance access" } }, "SGroup1Ingress" : { "Type" : "AWS::EC2::SecurityGroupIngress", "Properties" : { "GroupName" : { "Ref" : "SGroup1" }, "IpProtocol" : "tcp", "ToPort" : "80", "FromPort" : "80", "SourceSecurityGroupName" : { "Ref" : "SGroup2" } } }, "SGroup2Ingress" : { "Type" : "AWS::EC2::SecurityGroupIngress", "Properties" : { "GroupName" : { "Ref" : "SGroup2" }, "IpProtocol" : "tcp", "ToPort" : "80", "FromPort" : "80", "SourceSecurityGroupName" : { "Ref" : "SGroup1" } } } API Version 2010-05-15 348 AWS CloudFormation User Guide Amazon EC2 YAML SGroup1: Type: AWS::EC2::SecurityGroup Properties: GroupDescription: EC2 Instance access SGroup2: Type: AWS::EC2::SecurityGroup Properties: GroupDescription: EC2 Instance access SGroup1Ingress: Type: AWS::EC2::SecurityGroupIngress Properties: GroupName: !Ref SGroup1 IpProtocol: tcp ToPort: 80 FromPort: 80 SourceSecurityGroupName: !Ref SGroup2 SGroup2Ingress: Type: AWS::EC2::SecurityGroupIngress Properties: GroupName: !Ref SGroup2 IpProtocol: tcp ToPort: 80 FromPort: 80 SourceSecurityGroupName: !Ref SGroup1 Amazon EC2 Volume Resource This snippet shows a simple Amazon EC2 volume resource with a DeletionPolicy attribute set to Snapshot. With the Snapshot DeletionPolicy set, AWS CloudFormation will take a snapshot of this volume before deleting it during stack deletion. Make sure you specify a value for SnapShotId, or a value for Size, but not both. Remove the one you don't need. JSON "MyEBSVolume" : { "Type" : "AWS::EC2::Volume", "Properties" : { "Size" : "specify a size if no SnapShotId", "SnapshotId" : "specify a SnapShotId if no Size", "AvailabilityZone" : { "Ref" : "AvailabilityZone" } }, "DeletionPolicy" : "Snapshot" } YAML MyEBSVolume: Type: AWS::EC2::Volume Properties: Size: specify a size if no SnapshotId SnapshotId: specify a SnapShotId if no Size AvailabilityZone: !Ref AvailabilityZone DeletionPolicy: Snapshot Amazon EC2 VolumeAttachment Resource This snippet shows the following resources: an Amazon EC2 instance using an Amazon Linux AMI from the US-East (Northern Virginia) Region, an EC2 security group that allows SSH access to IP addresses, a API Version 2010-05-15 349 AWS CloudFormation User Guide Amazon EC2 new Amazon EBS volume sized at 100 GB and in the same Availability Zone as the EC2 instance, and a volume attachment that attaches the new volume to the EC2 instance. JSON "Resources" : { "Ec2Instance" : { "Type" : "AWS::EC2::Instance", "Properties" : { "SecurityGroups" : [ { "Ref" : "InstanceSecurityGroup" } ], "ImageId" : "ami-76f0061f" } }, "InstanceSecurityGroup" : { "Type" : "AWS::EC2::SecurityGroup", "Properties" : { "GroupDescription" : "Enable SSH access via port 22", "SecurityGroupIngress" : [ { "IpProtocol" : "tcp", "FromPort" : "22", "ToPort" : "22", "CidrIp" : "0.0.0.0/0" } ] } }, "NewVolume" : { "Type" : "AWS::EC2::Volume", "Properties" : { "Size" : "100", "AvailabilityZone" : { "Fn::GetAtt" : [ "Ec2Instance", "AvailabilityZone" ]}, } }, "MountPoint" : { "Type" : "AWS::EC2::VolumeAttachment", "Properties" : { "InstanceId" : { "Ref" : "Ec2Instance" }, "VolumeId" : { "Ref" : "NewVolume" }, "Device" : "/dev/sdh" } } } YAML Resources: Ec2Instance: Type: AWS::EC2::Instance Properties: SecurityGroups: - !Ref InstanceSecurityGroup ImageId: ami-76f0061f InstanceSecurityGroup: Type: AWS::EC2::SecurityGroup Properties: GroupDescription: Enable SSH access via port 22 SecurityGroupIngress: - IpProtocol: tcp FromPort: 22 ToPort: 22 CidrIp: 0.0.0.0/0 API Version 2010-05-15 350 AWS CloudFormation User Guide Amazon EC2 NewVolume: Type: AWS::EC2::Volume Properties: Size: 100 AvailabilityZone: !GetAtt Ec2Instance.AvailabilityZone MountPoint: Type: AWS::EC2::VolumeAttachment Properties: InstanceId: !Ref Ec2Instance VolumeId: !Ref NewVolume Device: /dev/sdh Amazon EC2 Instance in a Default VPC Security Group Whenever you create a VPC, AWS automatically creates default resources for that VPC, such as a security group. However, when you define a VPC in AWS CloudFormation templates, you don't yet have the physical IDs of those default resources. To obtain the IDs, use the Fn::GetAtt (p. 2285) intrinsic function. That way, you can use the default resources instead of creating new ones in your template. For example, the following template snippet associates the default security group of the myVPC VPC with the myInstance Amazon EC2 instance. JSON "myVPC": { "Type": "AWS::EC2::VPC", "Properties": { "CidrBlock": {"Ref": "myVPCCIDRRange"}, "EnableDnsSupport": false, "EnableDnsHostnames": false, "InstanceTenancy": "default" } }, "myInstance" : { "Type" : "AWS::EC2::Instance", "Properties" : { "ImageId": { "Fn::FindInMap": ["AWSRegionToAMI",{"Ref": "AWS::Region"},"64"] }, "SecurityGroupIds" : [{"Fn::GetAtt": ["myVPC", "DefaultSecurityGroup"]}], "SubnetId" : {"Ref" : "mySubnet"} } } YAML myVPC: Type: AWS::EC2::VPC Properties: CidrBlock: !Ref myVPCCIDRRange EnableDnsSupport: false EnableDnsHostnames: false InstanceTenancy: default myInstance: Type: AWS::EC2::Instance Properties: ImageId: !FindInMap [ AWSRegionToAMI , !Ref 'AWS::Region', 64 ] SecurityGroupIds: - !GetAtt myVPC.DefaultSecurityGroup SubnetId: !Ref mySubnet API Version 2010-05-15 351 AWS CloudFormation User Guide Amazon EC2 Amazon EC2 Route with Egress-Only Internet Gateway The following template sets up an egress-only Internet gateway that's used with an EC2 route. JSON { } "Resources": { "DefaultIpv6Route": { "Properties": { "DestinationIpv6CidrBlock": "::/0", "EgressOnlyInternetGatewayId": { "Ref": "EgressOnlyInternetGateway" }, "RouteTableId": { "Ref": "RouteTable" } }, "Type": "AWS::EC2::Route" }, "EgressOnlyInternetGateway": { "Properties": { "VpcId": { "Ref": "VPC" } }, "Type": "AWS::EC2::EgressOnlyInternetGateway" }, "RouteTable": { "Properties": { "VpcId": { "Ref": "VPC" } }, "Type": "AWS::EC2::RouteTable" }, "VPC": { "Properties": { "CidrBlock": "10.0.0.0/16" }, "Type": "AWS::EC2::VPC" } } YAML Resources: DefaultIpv6Route: Type: AWS::EC2::Route Properties: DestinationIpv6CidrBlock: "::/0" EgressOnlyInternetGatewayId: !Ref EgressOnlyInternetGateway RouteTableId: !Ref RouteTable EgressOnlyInternetGateway: Type: AWS::EC2::EgressOnlyInternetGateway Properties: VpcId: !Ref VPC RouteTable: Type: AWS::EC2::RouteTable Properties: VpcId: !Ref VPC VPC: API Version 2010-05-15 352 AWS CloudFormation User Guide Amazon ECS Type: AWS::EC2::VPC Properties: CidrBlock: 10.0.0.0/16 Amazon Elastic Container Service Template Snippets Amazon Elastic Container Service (Amazon ECS) is a container management service that makes it easy to run, stop, and manage Docker containers on a cluster of Amazon Elastic Compute Cloud (Amazon EC2) instances. The following example template deploys a web application in an Amazon ECS container with autoscaling and an application load balancer. For more information, see Getting Started with Amazon ECS in the Amazon Elastic Container Service Developer Guide. Important For the latest AMI IDs, see Amazon ECS-optimized AMI in the Amazon Elastic Container Service Developer Guide. JSON { "AWSTemplateFormatVersion":"2010-09-09", "Parameters":{ "KeyName":{ "Type":"AWS::EC2::KeyPair::KeyName", "Description":"Name of an existing EC2 KeyPair to enable SSH access to the ECS instances." }, "VpcId":{ "Type":"AWS::EC2::VPC::Id", "Description":"Select a VPC that allows instances to access the Internet." }, "SubnetId":{ "Type":"List", "Description":"Select at two subnets in your selected VPC." }, "DesiredCapacity":{ "Type":"Number", "Default":"1", "Description":"Number of instances to launch in your ECS cluster." }, "MaxSize":{ "Type":"Number", "Default":"1", "Description":"Maximum number of instances that can be launched in your ECS cluster." }, "InstanceType":{ "Description":"EC2 instance type", "Type":"String", "Default":"t2.micro", "AllowedValues":[ "t2.micro", "t2.small", "t2.medium", "t2.large", "m3.medium", "m3.large", "m3.xlarge", "m3.2xlarge", "m4.large", "m4.xlarge", "m4.2xlarge", API Version 2010-05-15 353 AWS CloudFormation User Guide Amazon ECS "m4.4xlarge", "m4.10xlarge", "c4.large", "c4.xlarge", "c4.2xlarge", "c4.4xlarge", "c4.8xlarge", "c3.large", "c3.xlarge", "c3.2xlarge", "c3.4xlarge", "c3.8xlarge", "r3.large", "r3.xlarge", "r3.2xlarge", "r3.4xlarge", "r3.8xlarge", "i2.xlarge", "i2.2xlarge", "i2.4xlarge", "i2.8xlarge" ], "ConstraintDescription":"Please choose a valid instance type." } }, "Mappings":{ "AWSRegionToAMI":{ "us-east-1":{ "AMIID":"ami-eca289fb" }, "us-east-2":{ "AMIID":"ami-446f3521" }, "us-west-1":{ "AMIID":"ami-9fadf8ff" }, "us-west-2":{ "AMIID":"ami-7abc111a" }, "eu-west-1":{ "AMIID":"ami-a1491ad2" }, "eu-central-1":{ "AMIID":"ami-54f5303b" }, "ap-northeast-1":{ "AMIID":"ami-9cd57ffd" }, "ap-southeast-1":{ "AMIID":"ami-a900a3ca" }, "ap-southeast-2":{ "AMIID":"ami-5781be34" } } }, "Resources":{ "ECSCluster":{ "Type":"AWS::ECS::Cluster" }, "EcsSecurityGroup":{ "Type":"AWS::EC2::SecurityGroup", "Properties":{ "GroupDescription":"ECS Security Group", "VpcId":{ "Ref":"VpcId" API Version 2010-05-15 354 AWS CloudFormation User Guide Amazon ECS } } }, "EcsSecurityGroupHTTPinbound":{ "Type":"AWS::EC2::SecurityGroupIngress", "Properties":{ "GroupId":{ "Ref":"EcsSecurityGroup" }, "IpProtocol":"tcp", "FromPort":"80", "ToPort":"80", "CidrIp":"0.0.0.0/0" } }, "EcsSecurityGroupSSHinbound":{ "Type":"AWS::EC2::SecurityGroupIngress", "Properties":{ "GroupId":{ "Ref":"EcsSecurityGroup" }, "IpProtocol":"tcp", "FromPort":"22", "ToPort":"22", "CidrIp":"0.0.0.0/0" } }, "EcsSecurityGroupALBports":{ "Type":"AWS::EC2::SecurityGroupIngress", "Properties":{ "GroupId":{ "Ref":"EcsSecurityGroup" }, "IpProtocol":"tcp", "FromPort":"31000", "ToPort":"61000", "SourceSecurityGroupId":{ "Ref":"EcsSecurityGroup" } } }, "CloudwatchLogsGroup":{ "Type":"AWS::Logs::LogGroup", "Properties":{ "LogGroupName":{ "Fn::Join":[ "-", [ "ECSLogGroup", { "Ref":"AWS::StackName" } ] ] }, "RetentionInDays":14 } }, "taskdefinition":{ "Type":"AWS::ECS::TaskDefinition", "Properties":{ "Family":{ "Fn::Join":[ "", [ { API Version 2010-05-15 355 AWS CloudFormation User Guide Amazon ECS ] ] "Ref":"AWS::StackName" }, "-ecs-demo-app" }, "ContainerDefinitions":[ { "Name":"simple-app", "Cpu":"10", "Essential":"true", "Image":"httpd:2.4", "Memory":"300", "LogConfiguration":{ "LogDriver":"awslogs", "Options":{ "awslogs-group":{ "Ref":"CloudwatchLogsGroup" }, "awslogs-region":{ "Ref":"AWS::Region" }, "awslogs-stream-prefix":"ecs-demo-app" } }, "MountPoints":[ { "ContainerPath":"/usr/local/apache2/htdocs", "SourceVolume":"my-vol" } ], "PortMappings":[ { "ContainerPort":80 } ] }, { "Name":"busybox", "Cpu":10, "Command":[ "/bin/sh -c \"while true; do echo ' Amazon ECS Sample App

Amazon ECS Sample App

Congratulations!

Your application is now running on a container in Amazon ECS.

' > top; /bin/date > date ; echo '
' > bottom; cat top date bottom > /usr/local/apache2/htdocs/index.html ; sleep 1; done\"" ], "EntryPoint":[ "sh", "-c" ], "Essential":false, "Image":"busybox", "Memory":200, "LogConfiguration":{ "LogDriver":"awslogs", "Options":{ "awslogs-group":{ "Ref":"CloudwatchLogsGroup" }, "awslogs-region":{ "Ref":"AWS::Region" }, "awslogs-stream-prefix":"ecs-demo-app" } API Version 2010-05-15 356 AWS CloudFormation User Guide Amazon ECS }, "VolumesFrom":[ { "SourceContainer":"simple-app" } ] } ], "Volumes":[ { "Name":"my-vol" } ] } }, "ECSALB":{ "Type":"AWS::ElasticLoadBalancingV2::LoadBalancer", "Properties":{ "Name":"ECSALB", "Scheme":"internet-facing", "LoadBalancerAttributes":[ { "Key":"idle_timeout.timeout_seconds", "Value":"30" } ], "Subnets":{ "Ref":"SubnetId" }, "SecurityGroups":[ { "Ref":"EcsSecurityGroup" } ] } }, "ALBListener":{ "Type":"AWS::ElasticLoadBalancingV2::Listener", "DependsOn":"ECSServiceRole", "Properties":{ "DefaultActions":[ { "Type":"forward", "TargetGroupArn":{ "Ref":"ECSTG" } } ], "LoadBalancerArn":{ "Ref":"ECSALB" }, "Port":"80", "Protocol":"HTTP" } }, "ECSALBListenerRule":{ "Type":"AWS::ElasticLoadBalancingV2::ListenerRule", "DependsOn":"ALBListener", "Properties":{ "Actions":[ { "Type":"forward", "TargetGroupArn":{ "Ref":"ECSTG" } } API Version 2010-05-15 357 AWS CloudFormation User Guide Amazon ECS ], "Conditions":[ { "Field":"path-pattern", "Values":[ "/" ] } ], "ListenerArn":{ "Ref":"ALBListener" }, "Priority":1 } }, "ECSTG":{ "Type":"AWS::ElasticLoadBalancingV2::TargetGroup", "DependsOn":"ECSALB", "Properties":{ "HealthCheckIntervalSeconds":10, "HealthCheckPath":"/", "HealthCheckProtocol":"HTTP", "HealthCheckTimeoutSeconds":5, "HealthyThresholdCount":2, "Name":"ECSTG", "Port":80, "Protocol":"HTTP", "UnhealthyThresholdCount":2, "VpcId":{ "Ref":"VpcId" } } }, "ECSAutoScalingGroup":{ "Type":"AWS::AutoScaling::AutoScalingGroup", "Properties":{ "VPCZoneIdentifier":{ "Ref":"SubnetId" }, "LaunchConfigurationName":{ "Ref":"ContainerInstances" }, "MinSize":"1", "MaxSize":{ "Ref":"MaxSize" }, "DesiredCapacity":{ "Ref":"DesiredCapacity" } }, "CreationPolicy":{ "ResourceSignal":{ "Timeout":"PT15M" } }, "UpdatePolicy":{ "AutoScalingReplacingUpdate":{ "WillReplace":"true" } } }, "ContainerInstances":{ "Type":"AWS::AutoScaling::LaunchConfiguration", "Properties":{ "ImageId":{ "Fn::FindInMap":[ API Version 2010-05-15 358 AWS CloudFormation User Guide Amazon ECS "AWSRegionToAMI", { "Ref":"AWS::Region" }, "AMIID" ] }, "SecurityGroups":[ { "Ref":"EcsSecurityGroup" } ], "InstanceType":{ "Ref":"InstanceType" }, "IamInstanceProfile":{ "Ref":"EC2InstanceProfile" }, "KeyName":{ "Ref":"KeyName" }, "UserData":{ "Fn::Base64":{ "Fn::Join":[ "", [ "#!/bin/bash -xe\n", "echo ECS_CLUSTER=", { "Ref":"ECSCluster" }, " >> /etc/ecs/ecs.config\n", "yum install -y aws-cfn-bootstrap\n", "/opt/aws/bin/cfn-signal -e $? ", " --stack ", { "Ref":"AWS::StackName" }, " --resource ECSAutoScalingGroup ", " --region ", { "Ref":"AWS::Region" }, "\n" ] ] } } } }, "service":{ "Type":"AWS::ECS::Service", "DependsOn":"ALBListener", "Properties":{ "Cluster":{ "Ref":"ECSCluster" }, "DesiredCount":"1", "LoadBalancers":[ { "ContainerName":"simple-app", "ContainerPort":"80", "TargetGroupArn":{ "Ref":"ECSTG" } } API Version 2010-05-15 359 AWS CloudFormation User Guide Amazon ECS ], "Role":{ "Ref":"ECSServiceRole" }, "TaskDefinition":{ "Ref":"taskdefinition" } } }, "ECSServiceRole":{ "Type":"AWS::IAM::Role", "Properties":{ "AssumeRolePolicyDocument":{ "Statement":[ { "Effect":"Allow", "Principal":{ "Service":[ "ecs.amazonaws.com" ] }, "Action":[ "sts:AssumeRole" ] } ] }, "Path":"/", "Policies":[ { "PolicyName":"ecs-service", "PolicyDocument":{ "Statement":[ { "Effect":"Allow", "Action":[ "elasticloadbalancing:DeregisterInstancesFromLoadBalancer", "elasticloadbalancing:DeregisterTargets", "elasticloadbalancing:Describe*", "elasticloadbalancing:RegisterInstancesWithLoadBalancer", "elasticloadbalancing:RegisterTargets", "ec2:Describe*", "ec2:AuthorizeSecurityGroupIngress" ], "Resource":"*" } ] } } ] } }, "ServiceScalingTarget":{ "Type":"AWS::ApplicationAutoScaling::ScalableTarget", "DependsOn":"service", "Properties":{ "MaxCapacity":2, "MinCapacity":1, "ResourceId":{ "Fn::Join":[ "", [ "service/", { "Ref":"ECSCluster" }, API Version 2010-05-15 360 AWS CloudFormation User Guide Amazon ECS ] ] "/", { "Fn::GetAtt":[ "service", "Name" ] } }, "RoleARN":{ "Fn::GetAtt":[ "AutoscalingRole", "Arn" ] }, "ScalableDimension":"ecs:service:DesiredCount", "ServiceNamespace":"ecs" } }, "ServiceScalingPolicy":{ "Type":"AWS::ApplicationAutoScaling::ScalingPolicy", "Properties":{ "PolicyName":"AStepPolicy", "PolicyType":"StepScaling", "ScalingTargetId":{ "Ref":"ServiceScalingTarget" }, "StepScalingPolicyConfiguration":{ "AdjustmentType":"PercentChangeInCapacity", "Cooldown":60, "MetricAggregationType":"Average", "StepAdjustments":[ { "MetricIntervalLowerBound":0, "ScalingAdjustment":200 } ] } } }, "ALB500sAlarmScaleUp":{ "Type":"AWS::CloudWatch::Alarm", "Properties":{ "EvaluationPeriods":"1", "Statistic":"Average", "Threshold":"10", "AlarmDescription":"Alarm if our ALB generates too many HTTP 500s.", "Period":"60", "AlarmActions":[ { "Ref":"ServiceScalingPolicy" } ], "Namespace":"AWS/ApplicationELB", "Dimensions":[ { "Name":"LoadBalancer", "Value":{ "Fn::GetAtt" : [ "ECSALB", "LoadBalancerFullName" ] } } ], API Version 2010-05-15 361 AWS CloudFormation User Guide Amazon ECS "ComparisonOperator":"GreaterThanThreshold", "MetricName":"HTTPCode_ELB_5XX_Count" } }, "EC2Role":{ "Type":"AWS::IAM::Role", "Properties":{ "AssumeRolePolicyDocument":{ "Statement":[ { "Effect":"Allow", "Principal":{ "Service":[ "ec2.amazonaws.com" ] }, "Action":[ "sts:AssumeRole" ] } ] }, "Path":"/", "Policies":[ { "PolicyName":"ecs-service", "PolicyDocument":{ "Statement":[ { "Effect":"Allow", "Action":[ "ecs:CreateCluster", "ecs:DeregisterContainerInstance", "ecs:DiscoverPollEndpoint", "ecs:Poll", "ecs:RegisterContainerInstance", "ecs:StartTelemetrySession", "ecs:Submit*", "logs:CreateLogStream", "logs:PutLogEvents" ], "Resource":"*" } ] } } ] } }, "AutoscalingRole":{ "Type":"AWS::IAM::Role", "Properties":{ "AssumeRolePolicyDocument":{ "Statement":[ { "Effect":"Allow", "Principal":{ "Service":[ "application-autoscaling.amazonaws.com" ] }, "Action":[ "sts:AssumeRole" ] } ] API Version 2010-05-15 362 AWS CloudFormation User Guide Amazon ECS }, "Path":"/", "Policies":[ { "PolicyName":"service-autoscaling", "PolicyDocument":{ "Statement":[ { "Effect":"Allow", "Action":[ "application-autoscaling:*", "cloudwatch:DescribeAlarms", "cloudwatch:PutMetricAlarm", "ecs:DescribeServices", "ecs:UpdateService" ], "Resource":"*" } ] } } ] } }, "EC2InstanceProfile":{ "Type":"AWS::IAM::InstanceProfile", "Properties":{ "Path":"/", "Roles":[ { "Ref":"EC2Role" } ] } } }, "Outputs":{ "ecsservice":{ "Value":{ "Ref":"service" } }, "ecscluster":{ "Value":{ "Ref":"ECSCluster" } }, "ECSALB":{ "Description":"Your ALB DNS URL", "Value":{ "Fn::Join":[ "", [ { "Fn::GetAtt":[ "ECSALB", "DNSName" ] } ] ] } }, "taskdef":{ "Value":{ "Ref":"taskdefinition" API Version 2010-05-15 363 AWS CloudFormation User Guide Amazon ECS } } } } YAML AWSTemplateFormatVersion: '2010-09-09' Parameters: KeyName: Type: AWS::EC2::KeyPair::KeyName Description: Name of an existing EC2 KeyPair to enable SSH access to the ECS instances. VpcId: Type: AWS::EC2::VPC::Id Description: Select a VPC that allows instances access to the Internet. SubnetId: Type: List Description: Select at two subnets in your selected VPC. DesiredCapacity: Type: Number Default: '1' Description: Number of instances to launch in your ECS cluster. MaxSize: Type: Number Default: '1' Description: Maximum number of instances that can be launched in your ECS cluster. InstanceType: Description: EC2 instance type Type: String Default: t2.micro AllowedValues: [t2.micro, t2.small, t2.medium, t2.large, m3.medium, m3.large, m3.xlarge, m3.2xlarge, m4.large, m4.xlarge, m4.2xlarge, m4.4xlarge, m4.10xlarge, c4.large, c4.xlarge, c4.2xlarge, c4.4xlarge, c4.8xlarge, c3.large, c3.xlarge, c3.2xlarge, c3.4xlarge, c3.8xlarge, r3.large, r3.xlarge, r3.2xlarge, r3.4xlarge, r3.8xlarge, i2.xlarge, i2.2xlarge, i2.4xlarge, i2.8xlarge] ConstraintDescription: Please choose a valid instance type. Mappings: AWSRegionToAMI: us-east-1: AMIID: ami-eca289fb us-east-2: AMIID: ami-446f3521 us-west-1: AMIID: ami-9fadf8ff us-west-2: AMIID: ami-7abc111a eu-west-1: AMIID: ami-a1491ad2 eu-central-1: AMIID: ami-54f5303b ap-northeast-1: AMIID: ami-9cd57ffd ap-southeast-1: AMIID: ami-a900a3ca ap-southeast-2: AMIID: ami-5781be34 Resources: ECSCluster: Type: AWS::ECS::Cluster EcsSecurityGroup: Type: AWS::EC2::SecurityGroup Properties: GroupDescription: ECS Security Group VpcId: !Ref 'VpcId' API Version 2010-05-15 364 AWS CloudFormation User Guide Amazon ECS EcsSecurityGroupHTTPinbound: Type: AWS::EC2::SecurityGroupIngress Properties: GroupId: !Ref 'EcsSecurityGroup' IpProtocol: tcp FromPort: '80' ToPort: '80' CidrIp: 0.0.0.0/0 EcsSecurityGroupSSHinbound: Type: AWS::EC2::SecurityGroupIngress Properties: GroupId: !Ref 'EcsSecurityGroup' IpProtocol: tcp FromPort: '22' ToPort: '22' CidrIp: 0.0.0.0/0 EcsSecurityGroupALBports: Type: AWS::EC2::SecurityGroupIngress Properties: GroupId: !Ref 'EcsSecurityGroup' IpProtocol: tcp FromPort: '31000' ToPort: '61000' SourceSecurityGroupId: !Ref 'EcsSecurityGroup' CloudwatchLogsGroup: Type: AWS::Logs::LogGroup Properties: LogGroupName: !Join ['-', [ECSLogGroup, !Ref 'AWS::StackName']] RetentionInDays: 14 taskdefinition: Type: AWS::ECS::TaskDefinition Properties: Family: !Join ['', [!Ref 'AWS::StackName', -ecs-demo-app]] ContainerDefinitions: - Name: simple-app Cpu: '10' Essential: 'true' Image: httpd:2.4 Memory: '300' LogConfiguration: LogDriver: awslogs Options: awslogs-group: !Ref 'CloudwatchLogsGroup' awslogs-region: !Ref 'AWS::Region' awslogs-stream-prefix: ecs-demo-app MountPoints: - ContainerPath: /usr/local/apache2/htdocs SourceVolume: my-vol PortMappings: - ContainerPort: 80 - Name: busybox Cpu: 10 Command: ['/bin/sh -c "while true; do echo '' Amazon ECS Sample App

Amazon ECS Sample App

Congratulations!

Your application is now running on a container in Amazon ECS.

'' > top; /bin/date > date ; echo ''
'' > bottom; cat top date bottom > /usr/local/ apache2/htdocs/index.html ; sleep 1; done"'] EntryPoint: [sh, -c] Essential: false Image: busybox Memory: 200 LogConfiguration: LogDriver: awslogs API Version 2010-05-15 365 AWS CloudFormation User Guide Amazon ECS Options: awslogs-group: !Ref 'CloudwatchLogsGroup' awslogs-region: !Ref 'AWS::Region' awslogs-stream-prefix: ecs-demo-app VolumesFrom: - SourceContainer: simple-app Volumes: - Name: my-vol ECSALB: Type: AWS::ElasticLoadBalancingV2::LoadBalancer Properties: Name: ECSALB Scheme: internet-facing LoadBalancerAttributes: - Key: idle_timeout.timeout_seconds Value: '30' Subnets: !Ref 'SubnetId' SecurityGroups: [!Ref 'EcsSecurityGroup'] ALBListener: Type: AWS::ElasticLoadBalancingV2::Listener DependsOn: ECSServiceRole Properties: DefaultActions: - Type: forward TargetGroupArn: !Ref 'ECSTG' LoadBalancerArn: !Ref 'ECSALB' Port: '80' Protocol: HTTP ECSALBListenerRule: Type: AWS::ElasticLoadBalancingV2::ListenerRule DependsOn: ALBListener Properties: Actions: - Type: forward TargetGroupArn: !Ref 'ECSTG' Conditions: - Field: path-pattern Values: [/] ListenerArn: !Ref 'ALBListener' Priority: 1 ECSTG: Type: AWS::ElasticLoadBalancingV2::TargetGroup DependsOn: ECSALB Properties: HealthCheckIntervalSeconds: 10 HealthCheckPath: / HealthCheckProtocol: HTTP HealthCheckTimeoutSeconds: 5 HealthyThresholdCount: 2 Name: ECSTG Port: 80 Protocol: HTTP UnhealthyThresholdCount: 2 VpcId: !Ref 'VpcId' ECSAutoScalingGroup: Type: AWS::AutoScaling::AutoScalingGroup Properties: VPCZoneIdentifier: !Ref 'SubnetId' LaunchConfigurationName: !Ref 'ContainerInstances' MinSize: '1' MaxSize: !Ref 'MaxSize' DesiredCapacity: !Ref 'DesiredCapacity' CreationPolicy: ResourceSignal: Timeout: PT15M UpdatePolicy: API Version 2010-05-15 366 AWS CloudFormation User Guide Amazon ECS AutoScalingReplacingUpdate: WillReplace: 'true' ContainerInstances: Type: AWS::AutoScaling::LaunchConfiguration Properties: ImageId: !FindInMap [AWSRegionToAMI, !Ref 'AWS::Region', AMIID] SecurityGroups: [!Ref 'EcsSecurityGroup'] InstanceType: !Ref 'InstanceType' IamInstanceProfile: !Ref 'EC2InstanceProfile' KeyName: !Ref 'KeyName' UserData: Fn::Base64: !Sub | #!/bin/bash -xe echo ECS_CLUSTER=${ECSCluster} >> /etc/ecs/ecs.config yum install -y aws-cfn-bootstrap /opt/aws/bin/cfn-signal -e $? --stack ${AWS::StackName} --resource ECSAutoScalingGroup --region ${AWS::Region} service: Type: AWS::ECS::Service DependsOn: ALBListener Properties: Cluster: !Ref 'ECSCluster' DesiredCount: '1' LoadBalancers: - ContainerName: simple-app ContainerPort: '80' TargetGroupArn: !Ref 'ECSTG' Role: !Ref 'ECSServiceRole' TaskDefinition: !Ref 'taskdefinition' ECSServiceRole: Type: AWS::IAM::Role Properties: AssumeRolePolicyDocument: Statement: - Effect: Allow Principal: Service: [ecs.amazonaws.com] Action: ['sts:AssumeRole'] Path: / Policies: - PolicyName: ecs-service PolicyDocument: Statement: - Effect: Allow Action: ['elasticloadbalancing:DeregisterInstancesFromLoadBalancer', 'elasticloadbalancing:DeregisterTargets', 'elasticloadbalancing:Describe*', 'elasticloadbalancing:RegisterInstancesWithLoadBalancer', 'elasticloadbalancing:RegisterTargets', 'ec2:Describe*', 'ec2:AuthorizeSecurityGroupIngress'] Resource: '*' ServiceScalingTarget: Type: AWS::ApplicationAutoScaling::ScalableTarget DependsOn: service Properties: MaxCapacity: 2 MinCapacity: 1 ResourceId: !Join ['', [service/, !Ref 'ECSCluster', /, !GetAtt [service, Name]]] RoleARN: !GetAtt [AutoscalingRole, Arn] ScalableDimension: ecs:service:DesiredCount ServiceNamespace: ecs ServiceScalingPolicy: Type: AWS::ApplicationAutoScaling::ScalingPolicy Properties: PolicyName: AStepPolicy PolicyType: StepScaling API Version 2010-05-15 367 AWS CloudFormation User Guide Amazon ECS ScalingTargetId: !Ref 'ServiceScalingTarget' StepScalingPolicyConfiguration: AdjustmentType: PercentChangeInCapacity Cooldown: 60 MetricAggregationType: Average StepAdjustments: - MetricIntervalLowerBound: 0 ScalingAdjustment: 200 ALB500sAlarmScaleUp: Type: AWS::CloudWatch::Alarm Properties: EvaluationPeriods: '1' Statistic: Average Threshold: '10' AlarmDescription: Alarm if our ALB generates too many HTTP 500s. Period: '60' AlarmActions: [!Ref 'ServiceScalingPolicy'] Namespace: AWS/ApplicationELB Dimensions: - Name: LoadBalancer Value: !GetAtt - ECSALB - LoadBalancerFullName ComparisonOperator: GreaterThanThreshold MetricName: HTTPCode_ELB_5XX_Count EC2Role: Type: AWS::IAM::Role Properties: AssumeRolePolicyDocument: Statement: - Effect: Allow Principal: Service: [ec2.amazonaws.com] Action: ['sts:AssumeRole'] Path: / Policies: - PolicyName: ecs-service PolicyDocument: Statement: - Effect: Allow Action: ['ecs:CreateCluster', 'ecs:DeregisterContainerInstance', 'ecs:DiscoverPollEndpoint', 'ecs:Poll', 'ecs:RegisterContainerInstance', 'ecs:StartTelemetrySession', 'ecs:Submit*', 'logs:CreateLogStream', 'logs:PutLogEvents'] Resource: '*' AutoscalingRole: Type: AWS::IAM::Role Properties: AssumeRolePolicyDocument: Statement: - Effect: Allow Principal: Service: [application-autoscaling.amazonaws.com] Action: ['sts:AssumeRole'] Path: / Policies: - PolicyName: service-autoscaling PolicyDocument: Statement: - Effect: Allow Action: ['application-autoscaling:*', 'cloudwatch:DescribeAlarms', 'cloudwatch:PutMetricAlarm', 'ecs:DescribeServices', 'ecs:UpdateService'] Resource: '*' EC2InstanceProfile: Type: AWS::IAM::InstanceProfile API Version 2010-05-15 368 AWS CloudFormation User Guide Amazon EFS Properties: Path: / Roles: [!Ref 'EC2Role'] Outputs: ecsservice: Value: !Ref 'service' ecscluster: Value: !Ref 'ECSCluster' ECSALB: Description: Your ALB DNS URL Value: !Join ['', [!GetAtt [ECSALB, DNSName]]] taskdef: Value: !Ref 'taskdefinition' Amazon Elastic File System Sample Template Amazon Elastic File System (Amazon EFS) is a file storage service for Amazon Elastic Compute Cloud (Amazon EC2) instances. With Amazon EFS, your applications have storage when they need it because storage capacity grows and shrinks automatically as you add and remove files. The following sample template deploys EC2 instances (in an Auto Scaling group) that are associated with an Amazon EFS file system. To associate the instances with the file system, the instances run the cfn-init helper script, which downloads and installs the nfs-utils yum package, creates a new directory, and then uses the file system's DNS name to mount the file system at that directory. The file system's DNS name resolves to a mount target’s IP address in the Amazon EC2 instance's Availability Zone. For more information about the DNS name structure, see Mounting File Systems in the Amazon Elastic File System User Guide. To measure Network File System activity, the template includes custom Amazon CloudWatch metrics. The template also creates a VPC, subnet, and security groups. To allow the instances to communicate with the file system, the VPC must have DNS enabled, and the mount target and the EC2 instances must be in the same Availability Zone (AZ), which is specified by the subnet. The security group of the mount target enables a network connection to TCP port 2049, which is required for an NFSv4 client to mount a file system. For more information on security groups for EC2 instances and mount targets, see Security in the Amazon Elastic File System User Guide. Note If you make an update to the mount target that causes it to be replaced, instances or applications that use the associated file system might be disrupted. This can cause uncommitted writes to be lost. To avoid disruption, stop your instances when you update the mount target by setting the desired capacity to zero. This allows the instances to unmount the file system before the mount target is deleted. After the mount update has completed, start your instances in a subsequent update by setting the desired capacity. JSON { "AWSTemplateFormatVersion": "2010-09-09", "Description": "This template creates an Amazon EFS file system and mount target and associates it with Amazon EC2 instances in an Auto Scaling group. **WARNING** This template creates Amazon EC2 instances and related resources. You will be billed for the AWS resources used if you create a stack from this template.", "Parameters": { "InstanceType" : { "Description" : "WebServer EC2 instance type", "Type" : "String", "Default" : "m1.small", "AllowedValues" : [ "t1.micro", "t2.micro", "t2.small", "t2.medium", "m1.small", "m1.medium", "m1.large", "m1.xlarge", "m2.xlarge", "m2.2xlarge", "m2.4xlarge", API Version 2010-05-15 369 AWS CloudFormation User Guide Amazon EFS "m3.medium", "m3.large", "m3.xlarge", "m3.2xlarge", "c1.medium", "c1.xlarge", "c3.large", "c3.xlarge", "c3.2xlarge", "c3.4xlarge", "c3.8xlarge", "c4.large", "c4.xlarge", "c4.2xlarge", "c4.4xlarge", "c4.8xlarge", "g2.2xlarge", "r3.large", "r3.xlarge", "r3.2xlarge", "r3.4xlarge", "r3.8xlarge", "i2.xlarge", "i2.2xlarge", "i2.4xlarge", "i2.8xlarge", "d2.xlarge", "d2.2xlarge", "d2.4xlarge", "d2.8xlarge", "hi1.4xlarge", "hs1.8xlarge", "cr1.8xlarge", "cc2.8xlarge", "cg1.4xlarge"], "ConstraintDescription" : "Must be a valid EC2 instance type." }, "KeyName": { "Type": "AWS::EC2::KeyPair::KeyName", "Description": "Name of an existing EC2 key pair to enable SSH access to the ECS instances" }, "AsgMaxSize": { "Type": "Number", "Description": "Maximum size and initial desired capacity of Auto Scaling Group", "Default": "2" }, "SSHLocation" : { "Description" : "The IP address range that can be used to connect to the EC2 instances by using SSH", "Type": "String", "MinLength": "9", "MaxLength": "18", "Default": "0.0.0.0/0", "AllowedPattern": "(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})/(\\d{1,2})", "ConstraintDescription": "must be a valid IP CIDR range of the form x.x.x.x/x." }, "VolumeName" : { "Description" : "The name to be used for the EFS volume", "Type": "String", "MinLength": "1", "Default": "myEFSvolume" }, "MountPoint" : { "Description" : "The Linux mount point for the EFS volume", "Type": "String", "MinLength": "1", "Default": "myEFSvolume" } }, "Mappings" : { "AWSInstanceType2Arch" : { "t1.micro" : { "Arch" : "PV64" }, "t2.micro" : { "Arch" : "HVM64" }, "t2.small" : { "Arch" : "HVM64" }, "t2.medium" : { "Arch" : "HVM64" }, "m1.small" : { "Arch" : "PV64" }, "m1.medium" : { "Arch" : "PV64" }, "m1.large" : { "Arch" : "PV64" }, "m1.xlarge" : { "Arch" : "PV64" }, "m2.xlarge" : { "Arch" : "PV64" }, "m2.2xlarge" : { "Arch" : "PV64" }, "m2.4xlarge" : { "Arch" : "PV64" }, "m3.medium" : { "Arch" : "HVM64" }, "m3.large" : { "Arch" : "HVM64" }, "m3.xlarge" : { "Arch" : "HVM64" }, "m3.2xlarge" : { "Arch" : "HVM64" }, "c1.medium" : { "Arch" : "PV64" }, "c1.xlarge" : { "Arch" : "PV64" }, "c3.large" : { "Arch" : "HVM64" }, "c3.xlarge" : { "Arch" : "HVM64" }, "c3.2xlarge" : { "Arch" : "HVM64" }, "c3.4xlarge" : { "Arch" : "HVM64" }, "c3.8xlarge" : { "Arch" : "HVM64" }, "c4.large" : { "Arch" : "HVM64" }, API Version 2010-05-15 370 AWS CloudFormation User Guide Amazon EFS "c4.xlarge" "c4.2xlarge" "c4.4xlarge" "c4.8xlarge" "g2.2xlarge" "r3.large" "r3.xlarge" "r3.2xlarge" "r3.4xlarge" "r3.8xlarge" "i2.xlarge" "i2.2xlarge" "i2.4xlarge" "i2.8xlarge" "d2.xlarge" "d2.2xlarge" "d2.4xlarge" "d2.8xlarge" "hi1.4xlarge" "hs1.8xlarge" "cr1.8xlarge" "cc2.8xlarge" : : : : : : : : : : : : : : : : : : : : : : { { { { { { { { { { { { { { { { { { { { { { "Arch" "Arch" "Arch" "Arch" "Arch" "Arch" "Arch" "Arch" "Arch" "Arch" "Arch" "Arch" "Arch" "Arch" "Arch" "Arch" "Arch" "Arch" "Arch" "Arch" "Arch" "Arch" : : : : : : : : : : : : : : : : : : : : : : "HVM64" "HVM64" "HVM64" "HVM64" "HVMG2" "HVM64" "HVM64" "HVM64" "HVM64" "HVM64" "HVM64" "HVM64" "HVM64" "HVM64" "HVM64" "HVM64" "HVM64" "HVM64" "HVM64" "HVM64" "HVM64" "HVM64" }, }, }, }, }, }, }, }, }, }, }, }, }, }, }, }, }, }, }, }, }, } }, "AWSRegionArch2AMI" : { "us-east-1" : {"PV64" : "ami-1ccae774", "HVM64" "ami-8c6b40e4"}, "us-west-2" : {"PV64" : "ami-ff527ecf", "HVM64" "ami-abbe919b"}, "us-west-1" : {"PV64" : "ami-d514f291", "HVM64" "ami-f31ffeb7"}, "eu-west-1" : {"PV64" : "ami-bf0897c8", "HVM64" "ami-d5bc24a2"}, "eu-central-1" : {"PV64" : "ami-ac221fb1", "HVM64" "ami-7cd2ef61"}, "ap-northeast-1" : {"PV64" : "ami-27f90e27", "HVM64" "ami-6318e863"}, "ap-southeast-1" : {"PV64" : "ami-acd9e8fe", "HVM64" "ami-3807376a"}, "ap-southeast-2" : {"PV64" : "ami-ff9cecc5", "HVM64" "ami-89790ab3"}, "sa-east-1" : {"PV64" : "ami-bb2890a6", "HVM64" "NOT_SUPPORTED"}, "cn-north-1" : {"PV64" : "ami-fa39abc3", "HVM64" "NOT_SUPPORTED"} } }, "Resources": { "CloudWatchPutMetricsRole" : { "Type" : "AWS::IAM::Role", "Properties" : { "AssumeRolePolicyDocument" : { "Statement" : [ { "Effect" : "Allow", "Principal" : { "Service" : [ "ec2.amazonaws.com" ] }, "Action" : [ "sts:AssumeRole" ] } ] }, "Path" : "/" } }, "CloudWatchPutMetricsRolePolicy" : { "Type" : "AWS::IAM::Policy", "Properties" : { "PolicyName" : "CloudWatch_PutMetricData", API Version 2010-05-15 371 : "ami-1ecae776", "HVMG2" : : "ami-e7527ed7", "HVMG2" : : "ami-d114f295", "HVMG2" : : "ami-a10897d6", "HVMG2" : : "ami-a8221fb5", "HVMG2" : : "ami-cbf90ecb", "HVMG2" : : "ami-68d8e93a", "HVMG2" : : "ami-fd9cecc7", "HVMG2" : : "ami-b52890a8", "HVMG2" : : "ami-f239abcb", "HVMG2" : AWS CloudFormation User Guide Amazon EFS "PolicyDocument" : { "Version": "2012-10-17", "Statement": [ { "Sid": "CloudWatchPutMetricData", "Effect": "Allow", "Action": ["cloudwatch:PutMetricData"], "Resource": ["*"] } ] }, "Roles" : [ { "Ref" : "CloudWatchPutMetricsRole" } ] } }, "CloudWatchPutMetricsInstanceProfile" : { "Type" : "AWS::IAM::InstanceProfile", "Properties" : { "Path" : "/", "Roles" : [ { "Ref" : "CloudWatchPutMetricsRole" } ] } }, "VPC": { "Type": "AWS::EC2::VPC", "Properties": { "EnableDnsSupport" : "true", "EnableDnsHostnames" : "true", "CidrBlock": "10.0.0.0/16", "Tags": [ {"Key": "Application", "Value": { "Ref": "AWS::StackId"} } ] } }, "InternetGateway" : { "Type" : "AWS::EC2::InternetGateway", "Properties" : { "Tags" : [ { "Key" : "Application", "Value" : { "Ref" : "AWS::StackName" } }, { "Key" : "Network", "Value" : "Public" } ] } }, "GatewayToInternet" : { "Type" : "AWS::EC2::VPCGatewayAttachment", "Properties" : { "VpcId" : { "Ref" : "VPC" }, "InternetGatewayId" : { "Ref" : "InternetGateway" } } }, "RouteTable":{ "Type":"AWS::EC2::RouteTable", "Properties":{ "VpcId": {"Ref":"VPC"} } }, "SubnetRouteTableAssoc": { "Type" : "AWS::EC2::SubnetRouteTableAssociation", "Properties" : { "RouteTableId" : {"Ref":"RouteTable"}, "SubnetId" : {"Ref":"Subnet"} } }, "InternetGatewayRoute": { "Type":"AWS::EC2::Route", "Properties":{ "DestinationCidrBlock":"0.0.0.0/0", "RouteTableId":{"Ref":"RouteTable"}, "GatewayId":{"Ref":"InternetGateway"} } API Version 2010-05-15 372 AWS CloudFormation User Guide Amazon EFS }, "Subnet": { "Type": "AWS::EC2::Subnet", "Properties": { "VpcId": { "Ref": "VPC" }, "CidrBlock": "10.0.0.0/24", "Tags": [ { "Key": "Application", "Value": { "Ref": "AWS::StackId" } } ] } }, "InstanceSecurityGroup": { "Type": "AWS::EC2::SecurityGroup", "Properties": { "VpcId": { "Ref": "VPC" }, "GroupDescription": "Enable SSH access via port 22", "SecurityGroupIngress": [ { "IpProtocol": "tcp", "FromPort": "22", "ToPort": "22", "CidrIp": { "Ref": "SSHLocation" } }, { "IpProtocol": "tcp", "FromPort": "80", "ToPort": "80", "CidrIp": "0.0.0.0/0" } ] } }, "MountTargetSecurityGroup": { "Type": "AWS::EC2::SecurityGroup", "Properties": { "VpcId": { "Ref": "VPC" }, "GroupDescription": "Security group for mount target", "SecurityGroupIngress": [ { "IpProtocol": "tcp", "FromPort": "2049", "ToPort": "2049", "CidrIp": "0.0.0.0/0" } ] } }, "FileSystem": { "Type": "AWS::EFS::FileSystem", "Properties": { "PerformanceMode": "generalPurpose", "FileSystemTags": [ { "Key": "Name", "Value": { "Ref" : "VolumeName" } } ] } }, "MountTarget": { "Type": "AWS::EFS::MountTarget", "Properties": { "FileSystemId": { "Ref": "FileSystem" }, "SubnetId": { "Ref": "Subnet" }, "SecurityGroups": [ { "Ref": "MountTargetSecurityGroup" } ] } }, "LaunchConfiguration": { "Type": "AWS::AutoScaling::LaunchConfiguration", "Metadata" : { "AWS::CloudFormation::Init" : { "configSets" : { "MountConfig" : [ "setup", "mount" ] }, "setup" : { "packages" : { "yum" : { API Version 2010-05-15 373 AWS CloudFormation User Guide Amazon EFS } "nfs-utils" : [] }, "files" : { "/home/ec2-user/post_nfsstat" : { "content" : { "Fn::Join" : [ "", [ "#!/bin/bash\n", "\n", "INPUT=\"$(cat)\"\n", "CW_JSON_OPEN='{ \"Namespace\": \"EFS\", \"MetricData\": [ '\n", "CW_JSON_CLOSE=' ] }'\n", "CW_JSON_METRIC=''\n", "METRIC_COUNTER=0\n", "\n", "for COL in 1 2 3 4 5 6; do\n", "\n", " COUNTER=0\n", " METRIC_FIELD=$COL\n", " DATA_FIELD=$(($COL+($COL-1)))\n", "\n", " while read line; do\n", " if [[ COUNTER -gt 0 ]]; then\n", "\n", " LINE=`echo $line | tr -s ' ' `\n", " AWS_COMMAND=\"aws cloudwatch put-metric-data --region ", { "Ref": "AWS::Region" }, "\"\n", " MOD=$(( $COUNTER % 2))\n", "\n", " if [ $MOD -eq 1 ]; then\n", " METRIC_NAME=`echo $LINE | cut -d ' ' -f $METRIC_FIELD`\n", " else\n", " METRIC_VALUE=`echo $LINE | cut -d ' ' -f $DATA_FIELD`\n", " fi\n", "\n", " if [[ -n \"$METRIC_NAME\" && -n \"$METRIC_VALUE\" ]]; then\n", " INSTANCE_ID=$(curl -s http://169.254.169.254/latest/metadata/instance-id)\n", " CW_JSON_METRIC=\"$CW_JSON_METRIC { \\\"MetricName\\\": \\ \"$METRIC_NAME\\\", \\\"Dimensions\\\": [{\\\"Name\\\": \\\"InstanceId\\\", \\\"Value\\\": \\\"$INSTANCE_ID\\\"} ], \\\"Value\\\": $METRIC_VALUE },\"\n", " unset METRIC_NAME\n", " unset METRIC_VALUE\n", "\n", " METRIC_COUNTER=$((METRIC_COUNTER+1))\n", " if [ $METRIC_COUNTER -eq 20 ]; then\n", " # 20 is max metric collection size, so we have to submit here\n", " aws cloudwatch put-metric-data --region ", { "Ref": "AWS::Region" }, " --cli-input-json \"`echo $CW_JSON_OPEN ${CW_JSON_METRIC%?} $CW_JSON_CLOSE`\"\n", "\n", " # reset\n", " METRIC_COUNTER=0\n", " CW_JSON_METRIC=''\n", " fi\n", " fi \n", "\n", "\n", "\n", " COUNTER=$((COUNTER+1))\n", " fi\n", "\n", " if [[ \"$line\" == \"Client nfs v4:\" ]]; then\n", " # the next line is the good stuff \n", " COUNTER=$((COUNTER+1))\n", " fi\n", API Version 2010-05-15 374 AWS CloudFormation User Guide Amazon EFS " done <<< \"$INPUT\"\n", "done\n", "\n", "# submit whatever is left\n", "aws cloudwatch put-metric-data --region ", { "Ref": "AWS::Region" }, " --cli-input-json \"`echo $CW_JSON_OPEN ${CW_JSON_METRIC%?} $CW_JSON_CLOSE`\"" ] ] }, "mode": "000755", "owner": "ec2-user", "group": "ec2-user" }, "/home/ec2-user/crontab" : { "content" : { "Fn::Join" : [ "", [ "* * * * * /usr/sbin/nfsstat | /home/ec2-user/post_nfsstat\n" ] ] }, "owner": "ec2-user", "group": "ec2-user" } }, "commands" : { "01_createdir" : { "command" : {"Fn::Join" : [ "", [ "mkdir /", { "Ref" : "MountPoint" }]]} } } }, "mount" : { "commands" : { "01_mount" : { "command" : { "Fn::Sub": "sudo mount -t nfs4 -o nfsvers=4.1,rsize=1048576,wsize=1048576,hard,timeo=600,retrans=2 ${FileSystem}.efs. ${AWS::Region}.amazonaws.com:/ /${MountPoint}"} }, "02_permissions" : { "command" : {"Fn::Join" : [ "", [ "chown ec2-user:ec2-user /", { "Ref" : "MountPoint" }]]} } } } } }, "Properties": { "AssociatePublicIpAddress" : true, "ImageId": { "Fn::FindInMap": [ "AWSRegionArch2AMI", { "Ref": "AWS::Region" }, { "Fn::FindInMap": [ "AWSInstanceType2Arch", { "Ref": "InstanceType" }, "Arch" ] } ] }, "InstanceType": { "Ref": "InstanceType" }, "KeyName": { "Ref": "KeyName" }, "SecurityGroups": [ { "Ref": "InstanceSecurityGroup" } ], "IamInstanceProfile" : { "Ref" : "CloudWatchPutMetricsInstanceProfile" }, "UserData" : { "Fn::Base64" : { "Fn::Join" : ["", [ "#!/bin/bash -xe\n", "yum install -y aws-cfn-bootstrap\n", "/opt/aws/bin/cfn-init -v ", " --stack ", { "Ref" : "AWS::StackName" }, " --resource LaunchConfiguration ", " --configsets MountConfig ", " --region ", { "Ref" : "AWS::Region" }, "\n", "crontab /home/ec2-user/crontab\n", "/opt/aws/bin/cfn-signal -e $? ", " --stack ", { "Ref" : "AWS::StackName" }, " --resource AutoScalingGroup ", API Version 2010-05-15 375 AWS CloudFormation User Guide Amazon EFS ]]}} " --region ", { "Ref" : "AWS::Region" }, "\n" } }, "AutoScalingGroup": { "Type": "AWS::AutoScaling::AutoScalingGroup", "DependsOn": ["MountTarget", "GatewayToInternet"], "CreationPolicy" : { "ResourceSignal" : { "Timeout" : "PT15M", "Count" : { "Ref": "AsgMaxSize" } } }, "Properties": { "VPCZoneIdentifier": [ { "Ref": "Subnet" } ], "LaunchConfigurationName": { "Ref": "LaunchConfiguration" }, "MinSize": "1", "MaxSize": { "Ref": "AsgMaxSize" }, "DesiredCapacity": { "Ref": "AsgMaxSize" }, "Tags": [ { "Key": "Name", "Value": "EFS FileSystem Mounted Instance", "PropagateAtLaunch": "true" } ] } } } }, "Outputs" : { "MountTargetID" : { "Description" : "Mount target ID", "Value" : { "Ref" : "MountTarget" } }, "FileSystemID" : { "Description" : "File system ID", "Value" : { "Ref" : "FileSystem" } } } YAML AWSTemplateFormatVersion: '2010-09-09' Description: This template creates an Amazon EFS file system and mount target and associates it with Amazon EC2 instances in an Auto Scaling group. **WARNING** This template creates Amazon EC2 instances and related resources. You will be billed for the AWS resources used if you create a stack from this template. Parameters: InstanceType: Description: WebServer EC2 instance type Type: String Default: m1.small AllowedValues: - t1.micro - t2.micro - t2.small - t2.medium - m1.small - m1.medium - m1.large - m1.xlarge - m2.xlarge - m2.2xlarge - m2.4xlarge - m3.medium API Version 2010-05-15 376 AWS CloudFormation User Guide Amazon EFS - m3.large - m3.xlarge - m3.2xlarge - c1.medium - c1.xlarge - c3.large - c3.xlarge - c3.2xlarge - c3.4xlarge - c3.8xlarge - c4.large - c4.xlarge - c4.2xlarge - c4.4xlarge - c4.8xlarge - g2.2xlarge - r3.large - r3.xlarge - r3.2xlarge - r3.4xlarge - r3.8xlarge - i2.xlarge - i2.2xlarge - i2.4xlarge - i2.8xlarge - d2.xlarge - d2.2xlarge - d2.4xlarge - d2.8xlarge - hi1.4xlarge - hs1.8xlarge - cr1.8xlarge - cc2.8xlarge - cg1.4xlarge ConstraintDescription: Must be a valid EC2 instance type. KeyName: Type: AWS::EC2::KeyPair::KeyName Description: Name of an existing EC2 key pair to enable SSH access to the ECS instances AsgMaxSize: Type: Number Description: Maximum size and initial desired capacity of Auto Scaling Group Default: '2' SSHLocation: Description: The IP address range that can be used to connect to the EC2 instances by using SSH Type: String MinLength: '9' MaxLength: '18' Default: 0.0.0.0/0 AllowedPattern: "(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})/(\\d{1,2})" ConstraintDescription: must be a valid IP CIDR range of the form x.x.x.x/x. VolumeName: Description: The name to be used for the EFS volume Type: String MinLength: '1' Default: myEFSvolume MountPoint: Description: The Linux mount point for the EFS volume Type: String MinLength: '1' Default: myEFSvolume Mappings: AWSInstanceType2Arch: t1.micro: Arch: PV64 API Version 2010-05-15 377 AWS CloudFormation User Guide Amazon EFS t2.micro: Arch: HVM64 t2.small: Arch: HVM64 t2.medium: Arch: HVM64 m1.small: Arch: PV64 m1.medium: Arch: PV64 m1.large: Arch: PV64 m1.xlarge: Arch: PV64 m2.xlarge: Arch: PV64 m2.2xlarge: Arch: PV64 m2.4xlarge: Arch: PV64 m3.medium: Arch: HVM64 m3.large: Arch: HVM64 m3.xlarge: Arch: HVM64 m3.2xlarge: Arch: HVM64 c1.medium: Arch: PV64 c1.xlarge: Arch: PV64 c3.large: Arch: HVM64 c3.xlarge: Arch: HVM64 c3.2xlarge: Arch: HVM64 c3.4xlarge: Arch: HVM64 c3.8xlarge: Arch: HVM64 c4.large: Arch: HVM64 c4.xlarge: Arch: HVM64 c4.2xlarge: Arch: HVM64 c4.4xlarge: Arch: HVM64 c4.8xlarge: Arch: HVM64 g2.2xlarge: Arch: HVMG2 r3.large: Arch: HVM64 r3.xlarge: Arch: HVM64 r3.2xlarge: Arch: HVM64 r3.4xlarge: Arch: HVM64 r3.8xlarge: Arch: HVM64 i2.xlarge: Arch: HVM64 API Version 2010-05-15 378 AWS CloudFormation User Guide Amazon EFS i2.2xlarge: Arch: HVM64 i2.4xlarge: Arch: HVM64 i2.8xlarge: Arch: HVM64 d2.xlarge: Arch: HVM64 d2.2xlarge: Arch: HVM64 d2.4xlarge: Arch: HVM64 d2.8xlarge: Arch: HVM64 hi1.4xlarge: Arch: HVM64 hs1.8xlarge: Arch: HVM64 cr1.8xlarge: Arch: HVM64 cc2.8xlarge: Arch: HVM64 AWSRegionArch2AMI: us-east-1: PV64: ami-1ccae774 HVM64: ami-1ecae776 HVMG2: ami-8c6b40e4 us-west-2: PV64: ami-ff527ecf HVM64: ami-e7527ed7 HVMG2: ami-abbe919b us-west-1: PV64: ami-d514f291 HVM64: ami-d114f295 HVMG2: ami-f31ffeb7 eu-west-1: PV64: ami-bf0897c8 HVM64: ami-a10897d6 HVMG2: ami-d5bc24a2 eu-central-1: PV64: ami-ac221fb1 HVM64: ami-a8221fb5 HVMG2: ami-7cd2ef61 ap-northeast-1: PV64: ami-27f90e27 HVM64: ami-cbf90ecb HVMG2: ami-6318e863 ap-southeast-1: PV64: ami-acd9e8fe HVM64: ami-68d8e93a HVMG2: ami-3807376a ap-southeast-2: PV64: ami-ff9cecc5 HVM64: ami-fd9cecc7 HVMG2: ami-89790ab3 sa-east-1: PV64: ami-bb2890a6 HVM64: ami-b52890a8 HVMG2: NOT_SUPPORTED cn-north-1: PV64: ami-fa39abc3 HVM64: ami-f239abcb HVMG2: NOT_SUPPORTED Resources: CloudWatchPutMetricsRole: Type: AWS::IAM::Role API Version 2010-05-15 379 AWS CloudFormation User Guide Amazon EFS Properties: AssumeRolePolicyDocument: Statement: - Effect: Allow Principal: Service: - ec2.amazonaws.com Action: - sts:AssumeRole Path: "/" CloudWatchPutMetricsRolePolicy: Type: AWS::IAM::Policy Properties: PolicyName: CloudWatch_PutMetricData PolicyDocument: Version: '2012-10-17' Statement: - Sid: CloudWatchPutMetricData Effect: Allow Action: - cloudwatch:PutMetricData Resource: - "*" Roles: - Ref: CloudWatchPutMetricsRole CloudWatchPutMetricsInstanceProfile: Type: AWS::IAM::InstanceProfile Properties: Path: "/" Roles: - Ref: CloudWatchPutMetricsRole VPC: Type: AWS::EC2::VPC Properties: EnableDnsSupport: 'true' EnableDnsHostnames: 'true' CidrBlock: 10.0.0.0/16 Tags: - Key: Application Value: Ref: AWS::StackId InternetGateway: Type: AWS::EC2::InternetGateway Properties: Tags: - Key: Application Value: Ref: AWS::StackName - Key: Network Value: Public GatewayToInternet: Type: AWS::EC2::VPCGatewayAttachment Properties: VpcId: Ref: VPC InternetGatewayId: Ref: InternetGateway RouteTable: Type: AWS::EC2::RouteTable Properties: VpcId: Ref: VPC SubnetRouteTableAssoc: Type: AWS::EC2::SubnetRouteTableAssociation Properties: RouteTableId: API Version 2010-05-15 380 AWS CloudFormation User Guide Amazon EFS Ref: RouteTable SubnetId: Ref: Subnet InternetGatewayRoute: Type: AWS::EC2::Route Properties: DestinationCidrBlock: 0.0.0.0/0 RouteTableId: Ref: RouteTable GatewayId: Ref: InternetGateway Subnet: Type: AWS::EC2::Subnet Properties: VpcId: Ref: VPC CidrBlock: 10.0.0.0/24 Tags: - Key: Application Value: Ref: AWS::StackId InstanceSecurityGroup: Type: AWS::EC2::SecurityGroup Properties: VpcId: Ref: VPC GroupDescription: Enable SSH access via port 22 SecurityGroupIngress: - IpProtocol: tcp FromPort: '22' ToPort: '22' CidrIp: Ref: SSHLocation - IpProtocol: tcp FromPort: '80' ToPort: '80' CidrIp: 0.0.0.0/0 MountTargetSecurityGroup: Type: AWS::EC2::SecurityGroup Properties: VpcId: Ref: VPC GroupDescription: Security group for mount target SecurityGroupIngress: - IpProtocol: tcp FromPort: '2049' ToPort: '2049' CidrIp: 0.0.0.0/0 FileSystem: Type: AWS::EFS::FileSystem Properties: PerformanceMode: generalPurpose FileSystemTags: - Key: Name Value: Ref: VolumeName MountTarget: Type: AWS::EFS::MountTarget Properties: FileSystemId: Ref: FileSystem SubnetId: Ref: Subnet SecurityGroups: - Ref: MountTargetSecurityGroup LaunchConfiguration: API Version 2010-05-15 381 AWS CloudFormation User Guide Amazon EFS Type: AWS::AutoScaling::LaunchConfiguration Metadata: AWS::CloudFormation::Init: configSets: MountConfig: - setup - mount setup: packages: yum: nfs-utils: [] files: "/home/ec2-user/post_nfsstat": content: !Sub | #!/bin/bash INPUT="$(cat)" CW_JSON_OPEN='{ "Namespace": "EFS", "MetricData": [ ' CW_JSON_CLOSE=' ] }' CW_JSON_METRIC='' METRIC_COUNTER=0 for COL in 1 2 3 4 5 6; do COUNTER=0 METRIC_FIELD=$COL DATA_FIELD=$(($COL+($COL-1))) while read line; do if [[ COUNTER -gt 0 ]]; then LINE=`echo $line | tr -s ' ' ` AWS_COMMAND="aws cloudwatch put-metric-data --region ${AWS::Region}" MOD=$(( $COUNTER % 2)) if [ $MOD -eq 1 ]; then METRIC_NAME=`echo $LINE | cut -d ' ' -f $METRIC_FIELD` else METRIC_VALUE=`echo $LINE | cut -d ' ' -f $DATA_FIELD` fi if [[ -n "$METRIC_NAME" && -n "$METRIC_VALUE" ]]; then INSTANCE_ID=$(curl -s http://169.254.169.254/latest/meta-data/ instance-id) CW_JSON_METRIC="$CW_JSON_METRIC { \"MetricName\": \"$METRIC_NAME\", \"Dimensions\": [{\"Name\": \"InstanceId\", \"Value\": \"$INSTANCE_ID\"} ], \"Value\": $METRIC_VALUE }," unset METRIC_NAME unset METRIC_VALUE METRIC_COUNTER=$((METRIC_COUNTER+1)) if [ $METRIC_COUNTER -eq 20 ]; then # 20 is max metric collection size, so we have to submit here aws cloudwatch put-metric-data --region ${AWS::Region} --cliinput-json "`echo $CW_JSON_OPEN ${!CW_JSON_METRIC%?} $CW_JSON_CLOSE`" # reset METRIC_COUNTER=0 CW_JSON_METRIC='' fi fi COUNTER=$((COUNTER+1)) fi API Version 2010-05-15 382 AWS CloudFormation User Guide Amazon EFS if [[ "$line" == "Client nfs v4:" ]]; then # the next line is the good stuff COUNTER=$((COUNTER+1)) fi done <<< "$INPUT" done # submit whatever is left aws cloudwatch put-metric-data --region ${AWS::Region} --cli-input-json "`echo $CW_JSON_OPEN ${!CW_JSON_METRIC%?} $CW_JSON_CLOSE`" mode: '000755' owner: ec2-user group: ec2-user "/home/ec2-user/crontab": content: "* * * * * /usr/sbin/nfsstat | /home/ec2-user/post_nfsstat\n" owner: ec2-user group: ec2-user commands: 01_createdir: command: !Sub "mkdir /${MountPoint}" mount: commands: 01_mount: command: !Sub > mount -t nfs4 -o nfsvers=4.1 ${FileSystem}.efs. ${AWS::Region}.amazonaws.com:/ /${MountPoint} 02_permissions: command: !Sub "chown ec2-user:ec2-user /${MountPoint}" Properties: AssociatePublicIpAddress: true ImageId: Fn::FindInMap: - AWSRegionArch2AMI - Ref: AWS::Region - Fn::FindInMap: - AWSInstanceType2Arch - Ref: InstanceType - Arch InstanceType: Ref: InstanceType KeyName: Ref: KeyName SecurityGroups: - Ref: InstanceSecurityGroup IamInstanceProfile: Ref: CloudWatchPutMetricsInstanceProfile UserData: Fn::Base64: !Sub | #!/bin/bash -xe yum install -y aws-cfn-bootstrap /opt/aws/bin/cfn-init -v --stack ${AWS::StackName} --resource LaunchConfiguration --configsets MountConfig --region ${AWS::Region} crontab /home/ec2-user/crontab /opt/aws/bin/cfn-signal -e $? --stack ${AWS::StackName} --resource AutoScalingGroup --region ${AWS::Region} AutoScalingGroup: Type: AWS::AutoScaling::AutoScalingGroup DependsOn: - MountTarget - GatewayToInternet CreationPolicy: ResourceSignal: Timeout: PT15M Count: Ref: AsgMaxSize API Version 2010-05-15 383 AWS CloudFormation User Guide Elastic Beanstalk Properties: VPCZoneIdentifier: - Ref: Subnet LaunchConfigurationName: Ref: LaunchConfiguration MinSize: '1' MaxSize: Ref: AsgMaxSize DesiredCapacity: Ref: AsgMaxSize Tags: - Key: Name Value: EFS FileSystem Mounted Instance PropagateAtLaunch: 'true' Outputs: MountTargetID: Description: Mount target ID Value: Ref: MountTarget FileSystemID: Description: File system ID Value: Ref: FileSystem Elastic Beanstalk Template Snippets With Elastic Beanstalk, you can quickly deploy and manage applications in AWS without worrying about the infrastructure that runs those applications. The following sample template can help you describe Elastic Beanstalk resources in your AWS CloudFormation template. Elastic Beanstalk Sample PHP The following sample template deploys a sample PHP web application that is stored in an Amazon S3 bucket. The Elastic Beanstalk environment is 64-bit Amazon Linux running PHP 5.3. The environment is also an autoscaling, load-balancing environment, with a minimum of two Amazon EC2 instances and a maximum of six. JSON { "AWSTemplateFormatVersion": "2010-09-09", "Resources": { "sampleApplication": { "Type": "AWS::ElasticBeanstalk::Application", "Properties": { "Description": "AWS Elastic Beanstalk Sample Application" } }, "sampleApplicationVersion": { "Type": "AWS::ElasticBeanstalk::ApplicationVersion", "Properties": { "ApplicationName": { "Ref": "sampleApplication" }, "Description": "AWS ElasticBeanstalk Sample Application Version", "SourceBundle": { "S3Bucket": { "Fn::Join": [ "-", [ "elasticbeanstalk-samples", { "Ref": "AWS::Region" } ] ] }, "S3Key": "php-newsample-app.zip" } } }, "sampleConfigurationTemplate": { API Version 2010-05-15 384 AWS CloudFormation User Guide Elastic Beanstalk "Type": "AWS::ElasticBeanstalk::ConfigurationTemplate", "Properties": { "ApplicationName": { "Ref": "sampleApplication" }, "Description": "AWS ElasticBeanstalk Sample Configuration Template", "OptionSettings": [ { "Namespace": "aws:autoscaling:asg", "OptionName": "MinSize", "Value": "2" }, { "Namespace": "aws:autoscaling:asg", "OptionName": "MaxSize", "Value": "6" }, { "Namespace": "aws:elasticbeanstalk:environment", "OptionName": "EnvironmentType", "Value": "LoadBalanced" } ], "SolutionStackName": "64bit Amazon Linux running PHP 5.3" } } } }, "sampleEnvironment": { "Type": "AWS::ElasticBeanstalk::Environment", "Properties": { "ApplicationName": { "Ref": "sampleApplication" }, "Description": "AWS ElasticBeanstalk Sample Environment", "TemplateName": { "Ref": "sampleConfigurationTemplate" }, "VersionLabel": { "Ref": "sampleApplicationVersion" } } } YAML AWSTemplateFormatVersion: '2010-09-09' Resources: sampleApplication: Type: AWS::ElasticBeanstalk::Application Properties: Description: AWS Elastic Beanstalk Sample Application sampleApplicationVersion: Type: AWS::ElasticBeanstalk::ApplicationVersion Properties: ApplicationName: Ref: sampleApplication Description: AWS ElasticBeanstalk Sample Application Version SourceBundle: S3Bucket: !Sub "elasticbeanstalk-samples-${AWS::Region}" S3Key: php-newsample-app.zip sampleConfigurationTemplate: Type: AWS::ElasticBeanstalk::ConfigurationTemplate Properties: ApplicationName: Ref: sampleApplication Description: AWS ElasticBeanstalk Sample Configuration Template OptionSettings: - Namespace: aws:autoscaling:asg OptionName: MinSize Value: '2' - Namespace: aws:autoscaling:asg API Version 2010-05-15 385 AWS CloudFormation User Guide Elastic Load Balancing OptionName: MaxSize Value: '6' - Namespace: aws:elasticbeanstalk:environment OptionName: EnvironmentType Value: LoadBalanced SolutionStackName: 64bit Amazon Linux running PHP 5.3 sampleEnvironment: Type: AWS::ElasticBeanstalk::Environment Properties: ApplicationName: Ref: sampleApplication Description: AWS ElasticBeanstalk Sample Environment TemplateName: Ref: sampleConfigurationTemplate VersionLabel: Ref: sampleApplicationVersion Elastic Load Balancing Template Snippets Elastic Load Balancing Load Balancer Resource This example shows an Elastic Load Balancing load balancer with a single listener, and no instances. JSON "MyLoadBalancer" : { "Type" : "AWS::ElasticLoadBalancing::LoadBalancer", "Properties" : { "AvailabilityZones" : [ "us-east-1a" ], "Listeners" : [ { "LoadBalancerPort" : "80", "InstancePort" : "80", "Protocol" : "HTTP" } ] } } YAML MyLoadBalancer: Type: AWS::ElasticLoadBalancing::LoadBalancer Properties: AvailabilityZones: - "us-east-1a" Listeners: - LoadBalancerPort: '80' InstancePort: '80' Protocol: HTTP Elastic Load Balancing Load Balancer Resource with Health Check This example shows an Elastic Load Balancing load balancer with two Amazon EC2 instances, a single listener and a health check. JSON "MyLoadBalancer" : { API Version 2010-05-15 386 AWS CloudFormation User Guide IAM "Type" : "AWS::ElasticLoadBalancing::LoadBalancer", "Properties" : { "AvailabilityZones" : [ "us-east-1a" ], "Instances" : [ { "Ref" : "logical name of AWS::EC2::Instance resource 1" }, { "Ref" : "logical name of AWS::EC2::Instance resource 2" } ], "Listeners" : [ { "LoadBalancerPort" : "80", "InstancePort" : "80", "Protocol" : "HTTP" } ], } } "HealthCheck" : { "Target" : "HTTP:80/", "HealthyThreshold" : "3", "UnhealthyThreshold" : "5", "Interval" : "30", "Timeout" : "5" } YAML MyLoadBalancer: Type: AWS::ElasticLoadBalancing::LoadBalancer Properties: AvailabilityZones: - "us-east-1a" Instances: - Ref: logical name of AWS::EC2::Instance resource 1 - Ref: logical name of AWS::EC2::Instance resource 2 Listeners: - LoadBalancerPort: '80' InstancePort: '80' Protocol: HTTP HealthCheck: Target: HTTP:80/ HealthyThreshold: '3' UnhealthyThreshold: '5' Interval: '30' Timeout: '5' AWS Identity and Access Management Template Snippets This section contains AWS Identity and Access Management template snippets. Topics • Declaring an IAM User Resource (p. 388) • Declaring an IAM Access Key Resource (p. 389) • Declaring an IAM Group Resource (p. 391) • Adding Users to a Group (p. 392) • Declaring an IAM Policy (p. 392) • Declaring an Amazon S3 Bucket Policy (p. 393) • Declaring an Amazon SNS Topic Policy (p. 394) API Version 2010-05-15 387 AWS CloudFormation User Guide IAM • Declaring an Amazon SQS Policy (p. 395) • IAM Role Template Examples (p. 396) Important When creating or updating a stack using a template containing IAM resources, you must acknowledge the use of IAM capabilities. For more information about using IAM resources in templates, see Controlling Access with AWS Identity and Access Management (p. 9). Declaring an IAM User Resource This snippet shows how to declare an AWS::IAM::User (p. 1205) resource to create an IAM user. The user is declared with the path ("/") and a login profile with the password (myP@ssW0rd). The policy document named giveaccesstoqueueonly gives the user permission to perform all Amazon SQS actions on the Amazon SQS queue resource myqueue, and denies access to all other Amazon SQS queue resources. The Fn::GetAtt (p. 2285) function gets the Arn attribute of the AWS::SQS::Queue (p. 1495) resource myqueue. The policy document named giveaccesstotopiconly is added to the user to give the user permission to perform all Amazon SNS actions on the Amazon SNS topic resource mytopic and to deny access to all other Amazon SNS resources. The Ref (p. 2311) function gets the ARN of the AWS::SNS::Topic (p. 1492) resource mytopic. JSON "myuser" : { "Type" : "AWS::IAM::User", "Properties" : { "Path" : "/", "LoginProfile" : { "Password" : "myP@ssW0rd" }, "Policies" : [ { "PolicyName" : "giveaccesstoqueueonly", "PolicyDocument" : { "Version": "2012-10-17", "Statement" : [ { "Effect" : "Allow", "Action" : [ "sqs:*" ], "Resource" : [ { "Fn::GetAtt" : [ "myqueue", "Arn" ] } ] }, { "Effect" : "Deny", "Action" : [ "sqs:*" ], "NotResource" : [ { "Fn::GetAtt" : [ "myqueue", "Arn" ] } ] } ] } }, { "PolicyName" : "giveaccesstotopiconly", "PolicyDocument" : { "Version": "2012-10-17", "Statement" : [ { "Effect" : "Allow", "Action" : [ "sns:*" ], "Resource" : [ { "Ref" : "mytopic" } ] }, { API Version 2010-05-15 388 AWS CloudFormation User Guide IAM "Effect" : "Deny", "Action" : [ "sns:*" ], "NotResource" : [ { "Ref" : "mytopic" } ] } } } } ] } ] YAML myuser: Type: AWS::IAM::User Properties: Path: "/" LoginProfile: Password: myP@ssW0rd Policies: - PolicyName: giveaccesstoqueueonly PolicyDocument: Version: '2012-10-17' Statement: - Effect: Allow Action: - sqs:* Resource: - !GetAtt myqueue.Arn - Effect: Deny Action: - sqs:* NotResource: - !GetAtt myqueue.Arn - PolicyName: giveaccesstotopiconly PolicyDocument: Version: '2012-10-17' Statement: - Effect: Allow Action: - sns:* Resource: - !Ref mytopic - Effect: Deny Action: - sns:* NotResource: - !Ref mytopic Declaring an IAM Access Key Resource This snippet shows an AWS::IAM::AccessKey (p. 1184) resource. The myaccesskey resource creates an access key and assigns it to an IAM user that is declared as an AWS::IAM::User (p. 1205) resource in the template. JSON "myaccesskey" : { "Type" : "AWS::IAM::AccessKey", "Properties" : { "UserName" : { "Ref" : "myuser" } API Version 2010-05-15 389 AWS CloudFormation User Guide IAM } } YAML myaccesskey: Type: AWS::IAM::AccessKey Properties: UserName: !Ref myuser You can get the secret key for an AWS::IAM::AccessKey resource using the Fn::GetAtt (p. 2285) function. The only time that you can get the secret key for an AWS access key is when it is created. One way to retrieve the secret key is to put it into an Output value. You can get the access key using the Ref function. The following Output value declarations get the access key and secret key for myaccesskey. JSON "AccessKeyformyaccesskey" : { "Value" : { "Ref" : "myaccesskey" } }, "SecretKeyformyaccesskey" : { "Value" : { "Fn::GetAtt" : [ "myaccesskey", "SecretAccessKey" ] } } YAML AccessKeyformyaccesskey: Value: !Ref myaccesskey SecretKeyformyaccesskey: Value: !GetAtt myaccesskey.SecretAccessKey You can also pass the AWS access key and secret key to an EC2 instance or Auto Scaling group defined in the template. The following AWS::EC2::Instance (p. 879) declaration uses the UserData property to pass the access key and secret key for the myaccesskey resource. JSON "myinstance" : { "Type" : "AWS::EC2::Instance", "Properties" : { "AvailabilityZone" : "us-east-1a", "ImageId" : "ami-20b65349", "UserData" : { "Fn::Base64" : { "Fn::Join" : [ "", [ "ACCESS_KEY=", { "Ref" : "myaccesskey" }, "&", API Version 2010-05-15 390 AWS CloudFormation User Guide IAM } } } } ] ] "SECRET_KEY=", { "Fn::GetAtt" : [ "myaccesskey", "SecretAccessKey" ] } YAML myinstance: Type: AWS::EC2::Instance Properties: AvailabilityZone: "us-east-1a" ImageId: ami-20b65349 UserData: Fn::Base64: !Sub "ACCESS_KEY=${myaccesskey}&SECRET_KEY=${myaccesskey.SecretAccessKey} Declaring an IAM Group Resource This snippet shows an AWS::IAM::Group (p. 1186) resource. The group has a path ("/ myapplication/"). The policy document named myapppolicy is added to the group to allow the group's users to perform all Amazon SQS actions on the Amazon SQS queue resource myqueue and deny access to all other Amazon SQS resources except myqueue. To assign a policy to a resource, IAM requires the Amazon Resource Name (ARN) for the resource. In the snippet, the Fn::GetAtt (p. 2285) function gets the ARN of the AWS::SQS::Queue (p. 1495) resource queue. JSON "mygroup" : { "Type" : "AWS::IAM::Group", "Properties" : { "Path" : "/myapplication/", "Policies" : [ { "PolicyName" : "myapppolicy", "PolicyDocument" : { "Version": "2012-10-17", "Statement" : [ { "Effect" : "Allow", "Action" : [ "sqs:*" ], "Resource" : [ { "Fn::GetAtt" : [ "myqueue", "Arn" ] } ] }, { "Effect" : "Deny", "Action" : [ "sqs:*" ], "NotResource" : [ { "Fn::GetAtt" : [ "myqueue", "Arn" ] } ] } ] } } ] } API Version 2010-05-15 391 AWS CloudFormation User Guide IAM } YAML mygroup: Type: AWS::IAM::Group Properties: Path: "/myapplication/" Policies: - PolicyName: myapppolicy PolicyDocument: Version: '2012-10-17' Statement: - Effect: Allow Action: - sqs:* Resource: !GetAtt myqueue.Arn - Effect: Deny Action: - sqs:* NotResource: !GetAtt myqueue.Arn Adding Users to a Group The AWS::IAM::UserToGroupAddition (p. 1208) resource adds users to a group. In the following snippet, the addUserToGroup resource adds the following users to an existing group named myexistinggroup2: the existing user existinguser1 and the user myuser which is declared as an AWS::IAM::User (p. 1205) resource in the template. JSON "addUserToGroup" : { "Type" : "AWS::IAM::UserToGroupAddition", "Properties" : { "GroupName" : "myexistinggroup2", "Users" : [ "existinguser1", { "Ref" : "myuser" } ] } } YAML addUserToGroup: Type: AWS::IAM::UserToGroupAddition Properties: GroupName: myexistinggroup2 Users: - existinguser1 - !Ref myuser Declaring an IAM Policy This snippet shows how to create a policy and apply it to multiple groups using an AWS::IAM::Policy (p. 1194) resource named mypolicy. The mypolicy resource contains a PolicyDocument property that allows GetObject, PutObject, and PutObjectAcl actions on the objects in the S3 bucket represented by the ARN arn:aws:s3:::myAWSBucket. The mypolicy resource applies the policy to an existing group named myexistinggroup1 and a group mygroup that API Version 2010-05-15 392 AWS CloudFormation User Guide IAM is declared in the template as an AWS::IAM::Group (p. 1186) resource. This example shows how to apply a policy to a group using the Groups property; however, you can alternatively use the Users property to add a policy document to a list of users. Important The Amazon SNS policy actions that are declared in the AWS::IAM::Policy resource (p. 392) differ from the Amazon SNS topic policy actions that are declared in the AWS::SNS::TopicPolicy resource (p. 394). For example, the policy actions sns:Unsubscribe and sns:SetSubscriptionAttributes are valid for the AWS::IAM::Policy resource, but are invalid for the AWS::SNS::TopicPolicy resource. For more information about valid Amazon SNS policy actions that you can use with the AWS::IAM::Policy resource, see Special Information for Amazon SNS Policies in the Amazon Simple Notification Service Developer Guide. JSON "mypolicy" : { "Type" : "AWS::IAM::Policy", "Properties" : { "PolicyName" : "mygrouppolicy", "PolicyDocument" : { "Version": "2012-10-17", "Statement" : [ { "Effect" : "Allow", "Action" : [ "s3:GetObject" , "s3:PutObject" , "s3:PutObjectAcl" ], "Resource" : "arn:aws:s3:::myAWSBucket/*" } ] }, "Groups" : [ "myexistinggroup1", { "Ref" : "mygroup" } ] } } YAML mypolicy: Type: AWS::IAM::Policy Properties: PolicyName: mygrouppolicy PolicyDocument: Version: '2012-10-17' Statement: - Effect: Allow Action: - s3:GetObject - s3:PutObject - s3:PutObjectAcl Resource: arn:aws:s3:::myAWSBucket/* Groups: - myexistinggroup1 - !Ref mygroup Declaring an Amazon S3 Bucket Policy This snippet shows how to create a policy and apply it to an Amazon S3 bucket using the AWS::S3::BucketPolicy (p. 1419) resource. The mybucketpolicy resource declares a policy document that allows the user1 IAM user to perform the GetObject action on all objects in the S3 bucket to which this policy is applied. In the snippet, the Fn::GetAtt (p. 2285) function gets the ARN of the user1 resource. The mybucketpolicy resource applies the policy to the API Version 2010-05-15 393 AWS CloudFormation User Guide IAM AWS::S3::Bucket (p. 1403) resource mybucket. The Ref (p. 2311) function gets the bucket name of the mybucket resource. JSON "mybucketpolicy" : { "Type" : "AWS::S3::BucketPolicy", "Properties" : { "PolicyDocument" : { "Id" : "MyPolicy", "Version": "2012-10-17", "Statement" : [ { "Sid" : "ReadAccess", "Action" : [ "s3:GetObject" ], "Effect" : "Allow", "Resource" : { "Fn::Join" : [ "", [ "arn:aws:s3:::", { "Ref" : "mybucket" } , "/*" ] ] }, "Principal" : { "AWS" : { "Fn::GetAtt" : [ "user1", "Arn" ] } } } ] }, "Bucket" : { "Ref" : "mybucket" } } } YAML mybucketpolicy: Type: AWS::S3::BucketPolicy Properties: PolicyDocument: Id: MyPolicy Version: '2012-10-17' Statement: - Sid: ReadAccess Action: - s3:GetObject Effect: Allow Resource: !Sub "arn:aws:s3:::${mybucket}/*" Principal: AWS: !GetAtt user1.Arn Bucket: !Ref mybucket Declaring an Amazon SNS Topic Policy This snippet shows how to create a policy and apply it to an Amazon SNS topic using the AWS::SNS::TopicPolicy (p. 1494) resource. The mysnspolicy resource contains a PolicyDocument property that allows the AWS::IAM::User (p. 1205) resource myuser to perform the Publish action on an AWS::SNS::Topic (p. 1492) resource mytopic. In the snippet, the Fn::GetAtt (p. 2285) function gets the ARN for the myuser resource and the Ref (p. 2311) function gets the ARN for the mytopic resource. Important The Amazon SNS policy actions that are declared in the AWS::IAM::Policy resource (p. 392) differ from the Amazon SNS topic policy actions that are declared in the AWS::SNS::TopicPolicy resource (p. 394). For example, the policy actions sns:Unsubscribe and sns:SetSubscriptionAttributes are valid for the API Version 2010-05-15 394 AWS CloudFormation User Guide IAM AWS::IAM::Policy resource, but are invalid for the AWS::SNS::TopicPolicy resource. For more information about valid Amazon SNS policy actions that you can use with the AWS::IAM::Policy resource, see Special Information for Amazon SNS Policies in the Amazon Simple Notification Service Developer Guide. JSON "mysnspolicy" : { "Type" : "AWS::SNS::TopicPolicy", "Properties" : { "PolicyDocument" : { "Id" : "MyTopicPolicy", "Version" : "2012-10-17", "Statement" : [ { "Sid" : "My-statement-id", "Effect" : "Allow", "Principal" : { "AWS" : { "Fn::GetAtt" : [ "myuser", "Arn" ] } }, "Action" : "sns:Publish", "Resource" : "*" } ] }, "Topics" : [ { "Ref" : "mytopic" } ] } } YAML mysnspolicy: Type: AWS::SNS::TopicPolicy Properties: PolicyDocument: Id: MyTopicPolicy Version: '2012-10-17' Statement: - Sid: My-statement-id Effect: Allow Principal: AWS: !GetAtt myuser.Arn Action: sns:Publish Resource: "*" Topics: - !Ref mytopic Declaring an Amazon SQS Policy This snippet shows how to create a policy and apply it to an Amazon SQS queue using the AWS::SQS::QueuePolicy (p. 1503) resource. The PolicyDocument property allows the existing user myapp (specified by its ARN) to perform the SendMessage action on an existing queue, which is specified by its URL, and an AWS::SQS::Queue (p. 1495) resource myqueue. The Ref (p. 2311) function gets the URL for the myqueue resource. JSON "mysqspolicy" : { "Type" : "AWS::SQS::QueuePolicy", "Properties" : { API Version 2010-05-15 395 AWS CloudFormation User Guide IAM } } "PolicyDocument" : { "Id" : "MyQueuePolicy", "Version" : "2012-10-17", "Statement" : [ { "Sid" : "Allow-User-SendMessage", "Effect" : "Allow", "Principal" : { "AWS" : "arn:aws:iam::123456789012:user/myapp" }, "Action" : [ "sqs:SendMessage" ], "Resource" : "*" } ] }, "Queues" : [ "https://sqs.us-east-2.amazonaws.com/123456789012/myexistingqueue", { "Ref" : "myqueue" } ] YAML mysqspolicy: Type: AWS::SQS::QueuePolicy Properties: PolicyDocument: Id: MyQueuePolicy Version: '2012-10-17' Statement: - Sid: Allow-User-SendMessage Effect: Allow Principal: AWS: arn:aws:iam::123456789012:user/myapp Action: - sqs:SendMessage Resource: "*" Queues: - https://sqs.us-east-2.amazonaws.com/123456789012/myexistingqueue - !Ref myqueue IAM Role Template Examples This section provides CloudFormation template examples for IAM Roles for EC2 Instances. For more information about IAM roles, see Working with Roles in the AWS Identity and Access Management User Guide. IAM Role with EC2 In this example, the instance profile is referenced by the IamInstanceProfile property of the EC2 Instance. Both the instance policy and role policy reference AWS::IAM::Role (p. 1197). JSON { "AWSTemplateFormatVersion": "2010-09-09", "Resources": { "myEC2Instance": { "Type": "AWS::EC2::Instance", "Version": "2009-05-15", "Properties": { API Version 2010-05-15 396 AWS CloudFormation User Guide IAM "ImageId": "ami-205fba49", "InstanceType": "m1.small", "Monitoring": "true", "DisableApiTermination": "false", "IamInstanceProfile": { "Ref": "RootInstanceProfile" } } } } }, "RootRole": { "Type": "AWS::IAM::Role", "Properties": { "AssumeRolePolicyDocument": { "Version" : "2012-10-17", "Statement": [ { "Effect": "Allow", "Principal": { "Service": [ "ec2.amazonaws.com" ] }, "Action": [ "sts:AssumeRole" ] } ] }, "Path": "/" } }, "RolePolicies": { "Type": "AWS::IAM::Policy", "Properties": { "PolicyName": "root", "PolicyDocument": { "Version" : "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": "*", "Resource": "*" } ] }, "Roles": [ { "Ref": "RootRole" } ] } }, "RootInstanceProfile": { "Type": "AWS::IAM::InstanceProfile", "Properties": { "Path": "/", "Roles": [ { "Ref": "RootRole" } ] } } YAML AWSTemplateFormatVersion: '2010-09-09' Resources: myEC2Instance: Type: AWS::EC2::Instance Version: '2009-05-15' Properties: ImageId: ami-205fba49 InstanceType: m1.small Monitoring: 'true' DisableApiTermination: 'false' IamInstanceProfile: !Ref RootInstanceProfile API Version 2010-05-15 397 AWS CloudFormation User Guide IAM RootRole: Type: AWS::IAM::Role Properties: AssumeRolePolicyDocument: Version: '2012-10-17' Statement: - Effect: Allow Principal: Service: - ec2.amazonaws.com Action: - sts:AssumeRole Path: "/" RolePolicies: Type: AWS::IAM::Policy Properties: PolicyName: root PolicyDocument: Version: '2012-10-17' Statement: - Effect: Allow Action: "*" Resource: "*" Roles: - !Ref RootRole RootInstanceProfile: Type: AWS::IAM::InstanceProfile Properties: Path: "/" Roles: - !Ref RootRole IAM Role with AutoScaling Group In this example, the instance profile is referenced by the IamInstanceProfile property of an AutoScaling Group Launch Configuration. JSON { "AWSTemplateFormatVersion": "2010-09-09", "Resources": { "myLCOne": { "Type": "AWS::AutoScaling::LaunchConfiguration", "Version": "2009-05-15", "Properties": { "ImageId": "ami-205fba49", "InstanceType": "m1.small", "InstanceMonitoring": "true", "IamInstanceProfile": { "Ref": "RootInstanceProfile" } } }, "myASGrpOne": { "Type": "AWS::AutoScaling::AutoScalingGroup", "Version": "2009-05-15", "Properties": { "AvailabilityZones": [ "us-east-1a" ], "LaunchConfigurationName": { "Ref": "myLCOne" }, "MinSize": "0", "MaxSize": "0", "HealthCheckType": "EC2", "HealthCheckGracePeriod": "120" } }, API Version 2010-05-15 398 AWS CloudFormation User Guide IAM } } "RootRole": { "Type": "AWS::IAM::Role", "Properties": { "AssumeRolePolicyDocument": { "Version" : "2012-10-17", "Statement": [ { "Effect": "Allow", "Principal": { "Service": [ "ec2.amazonaws.com" ] }, "Action": [ "sts:AssumeRole" ] } ] }, "Path": "/" } }, "RolePolicies": { "Type": "AWS::IAM::Policy", "Properties": { "PolicyName": "root", "PolicyDocument": { "Version" : "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": "*", "Resource": "*" } ] }, "Roles": [ { "Ref": "RootRole" } ] } }, "RootInstanceProfile": { "Type": "AWS::IAM::InstanceProfile", "Properties": { "Path": "/", "Roles": [ { "Ref": "RootRole" } ] } } YAML AWSTemplateFormatVersion: '2010-09-09' Resources: myLCOne: Type: AWS::AutoScaling::LaunchConfiguration Version: '2009-05-15' Properties: ImageId: ami-205fba49 InstanceType: m1.small InstanceMonitoring: 'true' IamInstanceProfile: !Ref RootInstanceProfile myASGrpOne: Type: AWS::AutoScaling::AutoScalingGroup Version: '2009-05-15' Properties: AvailabilityZones: - "us-east-1a" LaunchConfigurationName: !Ref myLCOne MinSize: '0' MaxSize: '0' API Version 2010-05-15 399 AWS CloudFormation User Guide AWS Lambda HealthCheckType: EC2 HealthCheckGracePeriod: '120' RootRole: Type: AWS::IAM::Role Properties: AssumeRolePolicyDocument: Version: '2012-10-17' Statement: - Effect: Allow Principal: Service: - ec2.amazonaws.com Action: - sts:AssumeRole Path: "/" RolePolicies: Type: AWS::IAM::Policy Properties: PolicyName: root PolicyDocument: Version: '2012-10-17' Statement: - Effect: Allow Action: "*" Resource: "*" Roles: - !Ref RootRole RootInstanceProfile: Type: AWS::IAM::InstanceProfile Properties: Path: "/" Roles: - !Ref RootRole AWS Lambda Template The following template uses an AWS Lambda (Lambda) function and custom resource to append a new security group to a list of existing security groups. This function is useful when you want to build a list of security groups dynamically, so that your list includes both new and existing security groups. For example, you can pass a list of existing security groups as a parameter value, append the new value to the list, and then associate all your values with an EC2 instance. For more information about the Lambda function resource type, see AWS::Lambda::Function (p. 1257). In the example, when AWS CloudFormation creates the AllSecurityGroups custom resource, AWS CloudFormation invokes the AppendItemToListFunction Lambda function. AWS CloudFormation passes the list of existing security groups and a new security group (NewSecurityGroup) to the function, which appends the new security group to the list and then returns the modified list. AWS CloudFormation uses the modified list to associate all security groups with the MyEC2Instance resource. JSON { "AWSTemplateFormatVersion": "2010-09-09", "Parameters" : { "ExistingSecurityGroups" : { "Type" : "List" }, "ExistingVPC" : { API Version 2010-05-15 400 AWS CloudFormation User Guide AWS Lambda "Type" : "AWS::EC2::VPC::Id", "Description" : "The VPC ID that includes the security groups in the ExistingSecurityGroups parameter." }, "InstanceType" : { "Type" : "String", "Default" : "t2.micro", "AllowedValues" : ["t2.micro", "m1.small"] } }, "Mappings": { "AWSInstanceType2Arch" : { "t2.micro" : { "Arch" : "HVM64" }, "m1.small" : { "Arch" : "PV64" } }, "AWSRegionArch2AMI" : { "us-east-1" : {"PV64" : "ami-1ccae774", "HVM64" : "ami-1ecae776"}, "us-west-2" : {"PV64" : "ami-ff527ecf", "HVM64" : "ami-e7527ed7"}, "us-west-1" : {"PV64" : "ami-d514f291", "HVM64" : "ami-d114f295"}, "eu-west-1" : {"PV64" : "ami-bf0897c8", "HVM64" : "ami-a10897d6"}, "eu-central-1" : {"PV64" : "ami-ac221fb1", "HVM64" : "ami-a8221fb5"}, "ap-northeast-1" : {"PV64" : "ami-27f90e27", "HVM64" : "ami-cbf90ecb"}, "ap-southeast-1" : {"PV64" : "ami-acd9e8fe", "HVM64" : "ami-68d8e93a"}, "ap-southeast-2" : {"PV64" : "ami-ff9cecc5", "HVM64" : "ami-fd9cecc7"}, "sa-east-1" : {"PV64" : "ami-bb2890a6", "HVM64" : "ami-b52890a8"}, "cn-north-1" : {"PV64" : "ami-fa39abc3", "HVM64" : "ami-f239abcb"} } }, "Resources" : { "SecurityGroup" : { "Type" : "AWS::EC2::SecurityGroup", "Properties" : { "GroupDescription" : "Allow HTTP traffic to the host", "VpcId" : {"Ref" : "ExistingVPC"}, "SecurityGroupIngress" : [{ "IpProtocol" : "tcp", "FromPort" : "80", "ToPort" : "80", "CidrIp" : "0.0.0.0/0" }], "SecurityGroupEgress" : [{ "IpProtocol" : "tcp", "FromPort" : "80", "ToPort" : "80", "CidrIp" : "0.0.0.0/0" }] } }, "AllSecurityGroups": { "Type": "Custom::Split", "Properties": { "ServiceToken": { "Fn::GetAtt" : ["AppendItemToListFunction", "Arn"] }, "List": { "Ref" : "ExistingSecurityGroups" }, "AppendedItem": { "Ref" : "SecurityGroup" } } }, "AppendItemToListFunction": { "Type": "AWS::Lambda::Function", "Properties": { "Handler": "index.handler", "Role": { "Fn::GetAtt" : ["LambdaExecutionRole", "Arn"] }, "Code": { "ZipFile": { "Fn::Join": ["", [ "var response = require('cfn-response');", "exports.handler = function(event, context) {", " var responseData = {Value: event.ResourceProperties.List};", API Version 2010-05-15 401 AWS CloudFormation User Guide AWS Lambda " responseData.Value.push(event.ResourceProperties.AppendedItem);", " response.send(event, context, response.SUCCESS, responseData);", "};" ]]} }, "Runtime": "nodejs4.3" } }, "MyEC2Instance" : { "Type" : "AWS::EC2::Instance", "Properties" : { "ImageId": { "Fn::FindInMap": [ "AWSRegionArch2AMI", { "Ref": "AWS::Region" }, { "Fn::FindInMap": [ "AWSInstanceType2Arch", { "Ref": "InstanceType" }, "Arch" ] } ] }, "SecurityGroupIds" : { "Fn::GetAtt": [ "AllSecurityGroups", "Value" ] }, "InstanceType" : { "Ref" : "InstanceType" } } }, "LambdaExecutionRole": { "Type": "AWS::IAM::Role", "Properties": { "AssumeRolePolicyDocument": { "Version": "2012-10-17", "Statement": [{ "Effect": "Allow", "Principal": {"Service": ["lambda.amazonaws.com"]}, "Action": ["sts:AssumeRole"] }] }, "Path": "/", "Policies": [{ "PolicyName": "root", "PolicyDocument": { "Version": "2012-10-17", "Statement": [{ "Effect": "Allow", "Action": ["logs:*"], "Resource": "arn:aws:logs:*:*:*" }] } }] } } }, "Outputs" : { "AllSecurityGroups" : { "Description" : "Security Groups that are associated with the EC2 instance", "Value" : { "Fn::Join" : [ ", ", { "Fn::GetAtt": [ "AllSecurityGroups", "Value" ] }]} } } } YAML AWSTemplateFormatVersion: '2010-09-09' Parameters: ExistingSecurityGroups: Type: List ExistingVPC: Type: AWS::EC2::VPC::Id Description: The VPC ID that includes the security groups in the ExistingSecurityGroups parameter. InstanceType: Type: String Default: t2.micro AllowedValues: - t2.micro - m1.small Mappings: API Version 2010-05-15 402 AWS CloudFormation User Guide AWS Lambda AWSInstanceType2Arch: t2.micro: Arch: HVM64 m1.small: Arch: PV64 AWSRegionArch2AMI: us-east-1: PV64: ami-1ccae774 HVM64: ami-1ecae776 us-west-2: PV64: ami-ff527ecf HVM64: ami-e7527ed7 us-west-1: PV64: ami-d514f291 HVM64: ami-d114f295 eu-west-1: PV64: ami-bf0897c8 HVM64: ami-a10897d6 eu-central-1: PV64: ami-ac221fb1 HVM64: ami-a8221fb5 ap-northeast-1: PV64: ami-27f90e27 HVM64: ami-cbf90ecb ap-southeast-1: PV64: ami-acd9e8fe HVM64: ami-68d8e93a ap-southeast-2: PV64: ami-ff9cecc5 HVM64: ami-fd9cecc7 sa-east-1: PV64: ami-bb2890a6 HVM64: ami-b52890a8 cn-north-1: PV64: ami-fa39abc3 HVM64: ami-f239abcb Resources: SecurityGroup: Type: AWS::EC2::SecurityGroup Properties: GroupDescription: Allow HTTP traffic to the host VpcId: Ref: ExistingVPC SecurityGroupIngress: - IpProtocol: tcp FromPort: '80' ToPort: '80' CidrIp: 0.0.0.0/0 SecurityGroupEgress: - IpProtocol: tcp FromPort: '80' ToPort: '80' CidrIp: 0.0.0.0/0 AllSecurityGroups: Type: Custom::Split Properties: ServiceToken: !GetAtt AppendItemToListFunction.Arn List: Ref: ExistingSecurityGroups AppendedItem: Ref: SecurityGroup AppendItemToListFunction: Type: AWS::Lambda::Function Properties: Handler: index.handler Role: !GetAtt LambdaExecutionRole.Arn API Version 2010-05-15 403 AWS CloudFormation User Guide AWS OpsWorks Code: ZipFile: !Sub | var response = require('cfn-response'); exports.handler = function(event, context) { var responseData = {Value: event.ResourceProperties.List}; responseData.Value.push(event.ResourceProperties.AppendedItem); response.send(event, context, response.SUCCESS, responseData); }; Runtime: nodejs4.3 MyEC2Instance: Type: AWS::EC2::Instance Properties: ImageId: Fn::FindInMap: - AWSRegionArch2AMI - Ref: AWS::Region - Fn::FindInMap: - AWSInstanceType2Arch - Ref: InstanceType - Arch SecurityGroupIds: !GetAtt AllSecurityGroups.Value InstanceType: Ref: InstanceType LambdaExecutionRole: Type: AWS::IAM::Role Properties: AssumeRolePolicyDocument: Version: '2012-10-17' Statement: - Effect: Allow Principal: Service: - lambda.amazonaws.com Action: - sts:AssumeRole Path: "/" Policies: - PolicyName: root PolicyDocument: Version: '2012-10-17' Statement: - Effect: Allow Action: - logs:* Resource: arn:aws:logs:*:*:* Outputs: AllSecurityGroups: Description: Security Groups that are associated with the EC2 instance Value: Fn::Join: - ", " - Fn::GetAtt: - AllSecurityGroups - Value AWS OpsWorks Template Snippets AWS OpsWorks is an application management service that simplifies a wide range of tasks such as software configuration, application deployment, scaling, and monitoring. AWS CloudFormation is a resource management service that you can use to manage AWS OpsWorks resources, such as AWS OpsWorks stacks, layers, apps, and instances. API Version 2010-05-15 404 AWS CloudFormation User Guide AWS OpsWorks AWS OpsWorks Sample PHP App The following sample template deploys a sample AWS OpsWorks PHP web application that is stored in public Git repository. The AWS OpsWorks stack includes two application servers with a load balancer that distributes incoming traffic evenly across the servers. The AWS OpsWorks stack also includes a back-end MySQL database server to store data. For more information about the sample AWS OpsWorks application, see Walkthrough: Learn AWS AWS OpsWorks Basics by Creating an Application Server Stack in the AWS OpsWorks User Guide. Note The ServiceRoleArn and DefaultInstanceProfileArn properties reference IAM roles that are created after you use AWS OpsWorks for the first time. JSON { "AWSTemplateFormatVersion": "2010-09-09", "Parameters": { "ServiceRole": { "Default": "aws-opsworks-service-role", "Description": "The OpsWorks service role", "Type": "String", "MinLength": "1", "MaxLength": "64", "AllowedPattern": "[a-zA-Z][a-zA-Z0-9-]*", "ConstraintDescription": "must begin with a letter and contain only alphanumeric characters." }, "InstanceRole": { "Default": "aws-opsworks-ec2-role", "Description": "The OpsWorks instance role", "Type": "String", "MinLength": "1", "MaxLength": "64", "AllowedPattern": "[a-zA-Z][a-zA-Z0-9-]*", "ConstraintDescription": "must begin with a letter and contain only alphanumeric characters." }, "AppName": { "Default": "myapp", "Description": "The app name", "Type": "String", "MinLength": "1", "MaxLength": "64", "AllowedPattern": "[a-zA-Z][a-zA-Z0-9]*", "ConstraintDescription": "must begin with a letter and contain only alphanumeric characters." }, "MysqlRootPassword" : { "Description" : "MysqlRootPassword", "NoEcho" : "true", "Type" : "String" } }, "Resources": { "myStack": { "Type": "AWS::OpsWorks::Stack", "Properties": { "Name": { "Ref": "AWS::StackName" }, "ServiceRoleArn": { "Fn::Join": [ API Version 2010-05-15 405 AWS CloudFormation User Guide AWS OpsWorks "", ["arn:aws:iam::", {"Ref": "AWS::AccountId"}, ":role/", {"Ref": "ServiceRole"}] ] }, "DefaultInstanceProfileArn": { "Fn::Join": [ "", ["arn:aws:iam::", {"Ref": "AWS::AccountId"}, ":instance-profile/", {"Ref": "InstanceRole"}] ] }, "UseCustomCookbooks": "true", "CustomCookbooksSource": { "Type": "git", "Url": "git://github.com/amazonwebservices/opsworks-example-cookbooks.git" } } }, "myLayer": { "Type": "AWS::OpsWorks::Layer", "DependsOn": "myApp", "Properties": { "StackId": {"Ref": "myStack"}, "Type": "php-app", "Shortname" : "php-app", "EnableAutoHealing" : "true", "AutoAssignElasticIps" : "false", "AutoAssignPublicIps" : "true", "Name": "MyPHPApp", "CustomRecipes" : { "Configure" : ["phpapp::appsetup"] } } }, "DBLayer" : { "Type" : "AWS::OpsWorks::Layer", "DependsOn": "myApp", "Properties" : { "StackId" : {"Ref":"myStack"}, "Type" : "db-master", "Shortname" : "db-layer", "EnableAutoHealing" : "true", "AutoAssignElasticIps" : "false", "AutoAssignPublicIps" : "true", "Name" : "MyMySQL", "CustomRecipes" : { "Setup" : ["phpapp::dbsetup"] }, "Attributes" : { "MysqlRootPassword" : {"Ref":"MysqlRootPassword"}, "MysqlRootPasswordUbiquitous": "true" }, "VolumeConfigurations":[{"MountPoint":"/vol/mysql","NumberOfDisks":1,"Size":10}] } }, "ELBAttachment" : { "Type" : "AWS::OpsWorks::ElasticLoadBalancerAttachment", "Properties" : { "ElasticLoadBalancerName" : { "Ref" : "ELB" }, "LayerId" : { "Ref" : "myLayer" } } }, "ELB" : { "Type": "AWS::ElasticLoadBalancing::LoadBalancer", "Properties": { "AvailabilityZones": { "Fn::GetAZs" : "" } , "Listeners": [{ API Version 2010-05-15 406 AWS CloudFormation User Guide AWS OpsWorks "LoadBalancerPort": "80", "InstancePort": "80", "Protocol": "HTTP", "InstanceProtocol": "HTTP" }], "HealthCheck": { "Target": "HTTP:80/", "HealthyThreshold": "2", "UnhealthyThreshold": "10", "Interval": "30", "Timeout": "5" } } } } }, "myAppInstance1": { "Type": "AWS::OpsWorks::Instance", "Properties": { "StackId": {"Ref": "myStack"}, "LayerIds": [{"Ref": "myLayer"}], "InstanceType": "m1.small" } }, "myAppInstance2": { "Type": "AWS::OpsWorks::Instance", "Properties": { "StackId": {"Ref": "myStack"}, "LayerIds": [{"Ref": "myLayer"}], "InstanceType": "m1.small" } }, "myDBInstance": { "Type": "AWS::OpsWorks::Instance", "Properties": { "StackId": {"Ref": "myStack"}, "LayerIds": [{"Ref": "DBLayer"}], "InstanceType": "m1.small" } }, "myApp" : { "Type" : "AWS::OpsWorks::App", "Properties" : { "StackId" : {"Ref":"myStack"}, "Type" : "php", "Name" : {"Ref": "AppName"}, "AppSource" : { "Type" : "git", "Url" : "git://github.com/amazonwebservices/opsworks-demo-php-simple-app.git", "Revision" : "version2" }, "Attributes" : { "DocumentRoot" : "web" } } } YAML AWSTemplateFormatVersion: '2010-09-09' Parameters: ServiceRole: Default: aws-opsworks-service-role Description: The OpsWorks service role API Version 2010-05-15 407 AWS CloudFormation User Guide AWS OpsWorks Type: String MinLength: '1' MaxLength: '64' AllowedPattern: "[a-zA-Z][a-zA-Z0-9-]*" ConstraintDescription: must begin with a letter and contain only alphanumeric characters. InstanceRole: Default: aws-opsworks-ec2-role Description: The OpsWorks instance role Type: String MinLength: '1' MaxLength: '64' AllowedPattern: "[a-zA-Z][a-zA-Z0-9-]*" ConstraintDescription: must begin with a letter and contain only alphanumeric characters. AppName: Default: myapp Description: The app name Type: String MinLength: '1' MaxLength: '64' AllowedPattern: "[a-zA-Z][a-zA-Z0-9]*" ConstraintDescription: must begin with a letter and contain only alphanumeric characters. MysqlRootPassword: Description: MysqlRootPassword NoEcho: 'true' Type: String Resources: myStack: Type: AWS::OpsWorks::Stack Properties: Name: Ref: AWS::StackName ServiceRoleArn: !Sub "arn:aws:iam::${AWS::AccountId}:role/${ServiceRole}" DefaultInstanceProfileArn: !Sub "arn:aws:iam::${AWS::AccountId}:instance-profile/ ${InstanceRole}" UseCustomCookbooks: 'true' CustomCookbooksSource: Type: git Url: git://github.com/amazonwebservices/opsworks-example-cookbooks.git myLayer: Type: AWS::OpsWorks::Layer DependsOn: myApp Properties: StackId: Ref: myStack Type: php-app Shortname: php-app EnableAutoHealing: 'true' AutoAssignElasticIps: 'false' AutoAssignPublicIps: 'true' Name: MyPHPApp CustomRecipes: Configure: - phpapp::appsetup DBLayer: Type: AWS::OpsWorks::Layer DependsOn: myApp Properties: StackId: Ref: myStack Type: db-master Shortname: db-layer EnableAutoHealing: 'true' AutoAssignElasticIps: 'false' API Version 2010-05-15 408 AWS CloudFormation User Guide AWS OpsWorks AutoAssignPublicIps: 'true' Name: MyMySQL CustomRecipes: Setup: - phpapp::dbsetup Attributes: MysqlRootPassword: Ref: MysqlRootPassword MysqlRootPasswordUbiquitous: 'true' VolumeConfigurations: - MountPoint: "/vol/mysql" NumberOfDisks: 1 Size: 10 ELBAttachment: Type: AWS::OpsWorks::ElasticLoadBalancerAttachment Properties: ElasticLoadBalancerName: Ref: ELB LayerId: Ref: myLayer ELB: Type: AWS::ElasticLoadBalancing::LoadBalancer Properties: AvailabilityZones: Fn::GetAZs: '' Listeners: - LoadBalancerPort: '80' InstancePort: '80' Protocol: HTTP InstanceProtocol: HTTP HealthCheck: Target: HTTP:80/ HealthyThreshold: '2' UnhealthyThreshold: '10' Interval: '30' Timeout: '5' myAppInstance1: Type: AWS::OpsWorks::Instance Properties: StackId: Ref: myStack LayerIds: - Ref: myLayer InstanceType: m1.small myAppInstance2: Type: AWS::OpsWorks::Instance Properties: StackId: Ref: myStack LayerIds: - Ref: myLayer InstanceType: m1.small myDBInstance: Type: AWS::OpsWorks::Instance Properties: StackId: Ref: myStack LayerIds: - Ref: DBLayer InstanceType: m1.small myApp: Type: AWS::OpsWorks::App Properties: StackId: Ref: myStack Type: php API Version 2010-05-15 409 AWS CloudFormation User Guide Amazon Redshift Name: Ref: AppName AppSource: Type: git Url: git://github.com/amazonwebservices/opsworks-demo-php-simple-app.git Revision: version2 Attributes: DocumentRoot: web Amazon Redshift Template Snippets Amazon Redshift is a fully managed, petabyte-scale data warehouse service in the cloud. You can use AWS CloudFormation to provision and manage Amazon Redshift clusters. Amazon Redshift Cluster The following sample template creates an Amazon Redshift cluster according to the parameter values that are specified when the stack is created. The cluster parameter group that is associated with the Amazon Redshift cluster enables user activity logging. The template also launches the Amazon Redshift clusters in an Amazon VPC that is defined in the template. The VPC includes an internet gateway so that you can access the Amazon Redshift clusters from the Internet. However, the communication between the cluster and the Internet gateway must also be enabled, which is done by the route table entry. Note The template includes the IsMultiNodeCluster condition so that the NumberOfNodes parameter is declared only when the ClusterType parameter value is set to multi-node. JSON { "AWSTemplateFormatVersion": "2010-09-09", "Parameters" : { "DatabaseName" : { "Description" : "The name of the first database to be created when the cluster is created", "Type" : "String", "Default" : "dev", "AllowedPattern" : "([a-z]|[0-9])+" }, "ClusterType" : { "Description" : "The type of cluster", "Type" : "String", "Default" : "single-node", "AllowedValues" : [ "single-node", "multi-node" ] }, "NumberOfNodes" : { "Description" : "The number of compute nodes in the cluster. For multi-node clusters, the NumberOfNodes parameter must be greater than 1", "Type" : "Number", "Default" : "1" }, "NodeType" : { "Description" : "The type of node to be provisioned", "Type" : "String", "Default" : "ds2.xlarge", "AllowedValues" : [ "ds2.xlarge", "ds2.8xlarge", "dc1.large", "dc1.8xlarge" ] }, "MasterUsername" : { "Description" : "The user name that is associated with the master user account for the cluster that is being created", "Type" : "String", "Default" : "defaultuser", API Version 2010-05-15 410 AWS CloudFormation User Guide Amazon Redshift "AllowedPattern" : "([a-z])([a-z]|[0-9])*" }, "MasterUserPassword" : { "Description" : "The password that is associated with the master user account for the cluster that is being created.", "Type" : "String", "NoEcho" : "true" }, "InboundTraffic" : { "Description" : "Allow inbound traffic to the cluster from this CIDR range.", "Type" : "String", "MinLength": "9", "MaxLength": "18", "Default" : "0.0.0.0/0", "AllowedPattern" : "(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})/(\\d{1,2})", "ConstraintDescription" : "must be a valid CIDR range of the form x.x.x.x/x." }, "PortNumber" : { "Description" : "The port number on which the cluster accepts incoming connections.", "Type" : "Number", "Default" : "5439" } }, "Conditions" : { "IsMultiNodeCluster" : { "Fn::Equals" : [{ "Ref" : "ClusterType" }, "multi-node" ] } }, "Resources" : { "RedshiftCluster" : { "Type" : "AWS::Redshift::Cluster", "DependsOn" : "AttachGateway", "Properties" : { "ClusterType" : { "Ref" : "ClusterType" }, "NumberOfNodes" : { "Fn::If" : [ "IsMultiNodeCluster", { "Ref" : "NumberOfNodes" }, { "Ref" : "AWS::NoValue" }]}, "NodeType" : { "Ref" : "NodeType" }, "DBName" : { "Ref" : "DatabaseName" }, "MasterUsername" : { "Ref" : "MasterUsername" }, "MasterUserPassword" : { "Ref" : "MasterUserPassword" }, "ClusterParameterGroupName" : { "Ref" : "RedshiftClusterParameterGroup" }, "VpcSecurityGroupIds" : [ { "Ref" : "SecurityGroup" } ], "ClusterSubnetGroupName" : { "Ref" : "RedshiftClusterSubnetGroup" }, "PubliclyAccessible" : "true", "Port" : { "Ref" : "PortNumber" } } }, "RedshiftClusterParameterGroup" : { "Type" : "AWS::Redshift::ClusterParameterGroup", "Properties" : { "Description" : "Cluster parameter group", "ParameterGroupFamily" : "redshift-1.0", "Parameters" : [{ "ParameterName" : "enable_user_activity_logging", "ParameterValue" : "true" }] } }, "RedshiftClusterSubnetGroup" : { "Type" : "AWS::Redshift::ClusterSubnetGroup", "Properties" : { "Description" : "Cluster subnet group", "SubnetIds" : [ { "Ref" : "PublicSubnet" } ] } }, "VPC" : { API Version 2010-05-15 411 AWS CloudFormation User Guide Amazon Redshift "Type" : "AWS::EC2::VPC", "Properties" : { "CidrBlock" : "10.0.0.0/16" } }, "PublicSubnet" : { "Type" : "AWS::EC2::Subnet", "Properties" : { "CidrBlock" : "10.0.0.0/24", "VpcId" : { "Ref" : "VPC" } } }, "SecurityGroup" : { "Type" : "AWS::EC2::SecurityGroup", "Properties" : { "GroupDescription" : "Security group", "SecurityGroupIngress" : [ { "CidrIp" : { "Ref": "InboundTraffic" }, "FromPort" : { "Ref" : "PortNumber" }, "ToPort" : { "Ref" : "PortNumber" }, "IpProtocol" : "tcp" } ], "VpcId" : { "Ref" : "VPC" } } }, "myInternetGateway" : { "Type" : "AWS::EC2::InternetGateway" }, "AttachGateway" : { "Type" : "AWS::EC2::VPCGatewayAttachment", "Properties" : { "VpcId" : { "Ref" : "VPC" }, "InternetGatewayId" : { "Ref" : "myInternetGateway" } } }, "PublicRouteTable" : { "Type" : "AWS::EC2::RouteTable", "Properties" : { "VpcId" : { "Ref" : "VPC" } } }, "PublicRoute" : { "Type" : "AWS::EC2::Route", "DependsOn" : "AttachGateway", "Properties" : { "RouteTableId" : { "Ref" : "PublicRouteTable" }, "DestinationCidrBlock" : "0.0.0.0/0", "GatewayId" : { "Ref" : "myInternetGateway" } } }, "PublicSubnetRouteTableAssociation" : { "Type" : "AWS::EC2::SubnetRouteTableAssociation", "Properties" : { "SubnetId" : { "Ref" : "PublicSubnet" }, "RouteTableId" : { "Ref" : "PublicRouteTable" } } API Version 2010-05-15 412 AWS CloudFormation User Guide Amazon Redshift } }, "Outputs" : { "ClusterEndpoint" : { "Description" : "Cluster endpoint", "Value" : { "Fn::Join" : [ ":", [ { "Fn::GetAtt" : [ "RedshiftCluster", "Endpoint.Address" ] }, { "Fn::GetAtt" : [ "RedshiftCluster", "Endpoint.Port" ] } ] ] } }, "ClusterName" : { "Description" : "Name of cluster", "Value" : { "Ref" : "RedshiftCluster" } }, "ParameterGroupName" : { "Description" : "Name of parameter group", "Value" : { "Ref" : "RedshiftClusterParameterGroup" } }, "RedshiftClusterSubnetGroupName" : { "Description" : "Name of cluster subnet group", "Value" : { "Ref" : "RedshiftClusterSubnetGroup" } }, "RedshiftClusterSecurityGroupName" : { "Description" : "Name of cluster security group", "Value" : { "Ref" : "SecurityGroup" } } } } YAML AWSTemplateFormatVersion: '2010-09-09' Parameters: DatabaseName: Description: The name of the first database to be created when the cluster is created Type: String Default: dev AllowedPattern: "([a-z]|[0-9])+" ClusterType: Description: The type of cluster Type: String Default: single-node AllowedValues: - single-node - multi-node NumberOfNodes: Description: The number of compute nodes in the cluster. For multi-node clusters, the NumberOfNodes parameter must be greater than 1 Type: Number Default: '1' NodeType: Description: The type of node to be provisioned Type: String Default: ds2.xlarge AllowedValues: - ds2.xlarge - ds2.8xlarge - dc1.large - dc1.8xlarge MasterUsername: Description: The user name that is associated with the master user account for the cluster that is being created Type: String Default: defaultuser AllowedPattern: "([a-z])([a-z]|[0-9])*" API Version 2010-05-15 413 AWS CloudFormation User Guide Amazon Redshift MasterUserPassword: Description: The password that is associated with the master user account for the cluster that is being created. Type: String NoEcho: 'true' InboundTraffic: Description: Allow inbound traffic to the cluster from this CIDR range. Type: String MinLength: '9' MaxLength: '18' Default: 0.0.0.0/0 AllowedPattern: "(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})/(\\d{1,2})" ConstraintDescription: must be a valid CIDR range of the form x.x.x.x/x. PortNumber: Description: The port number on which the cluster accepts incoming connections. Type: Number Default: '5439' Conditions: IsMultiNodeCluster: Fn::Equals: - Ref: ClusterType - multi-node Resources: RedshiftCluster: Type: AWS::Redshift::Cluster DependsOn: AttachGateway Properties: ClusterType: Ref: ClusterType NumberOfNodes: Fn::If: - IsMultiNodeCluster - Ref: NumberOfNodes - Ref: AWS::NoValue NodeType: Ref: NodeType DBName: Ref: DatabaseName MasterUsername: Ref: MasterUsername MasterUserPassword: Ref: MasterUserPassword ClusterParameterGroupName: Ref: RedshiftClusterParameterGroup VpcSecurityGroupIds: - Ref: SecurityGroup ClusterSubnetGroupName: Ref: RedshiftClusterSubnetGroup PubliclyAccessible: 'true' Port: Ref: PortNumber RedshiftClusterParameterGroup: Type: AWS::Redshift::ClusterParameterGroup Properties: Description: Cluster parameter group ParameterGroupFamily: redshift-1.0 Parameters: - ParameterName: enable_user_activity_logging ParameterValue: 'true' RedshiftClusterSubnetGroup: Type: AWS::Redshift::ClusterSubnetGroup Properties: Description: Cluster subnet group SubnetIds: - Ref: PublicSubnet VPC: API Version 2010-05-15 414 AWS CloudFormation User Guide Amazon Redshift Type: AWS::EC2::VPC Properties: CidrBlock: 10.0.0.0/16 PublicSubnet: Type: AWS::EC2::Subnet Properties: CidrBlock: 10.0.0.0/24 VpcId: Ref: VPC SecurityGroup: Type: AWS::EC2::SecurityGroup Properties: GroupDescription: Security group SecurityGroupIngress: - CidrIp: Ref: InboundTraffic FromPort: Ref: PortNumber ToPort: Ref: PortNumber IpProtocol: tcp VpcId: Ref: VPC myInternetGateway: Type: AWS::EC2::InternetGateway AttachGateway: Type: AWS::EC2::VPCGatewayAttachment Properties: VpcId: Ref: VPC InternetGatewayId: Ref: myInternetGateway PublicRouteTable: Type: AWS::EC2::RouteTable Properties: VpcId: Ref: VPC PublicRoute: Type: AWS::EC2::Route DependsOn: AttachGateway Properties: RouteTableId: Ref: PublicRouteTable DestinationCidrBlock: 0.0.0.0/0 GatewayId: Ref: myInternetGateway PublicSubnetRouteTableAssociation: Type: AWS::EC2::SubnetRouteTableAssociation Properties: SubnetId: Ref: PublicSubnet RouteTableId: Ref: PublicRouteTable Outputs: ClusterEndpoint: Description: Cluster endpoint Value: !Sub "${RedshiftCluster.Endpoint.Address}:${RedshiftCluster.Endpoint.Port}" ClusterName: Description: Name of cluster Value: Ref: RedshiftCluster ParameterGroupName: Description: Name of parameter group Value: Ref: RedshiftClusterParameterGroup RedshiftClusterSubnetGroupName: API Version 2010-05-15 415 AWS CloudFormation User Guide Amazon RDS Description: Name of cluster subnet group Value: Ref: RedshiftClusterSubnetGroup RedshiftClusterSecurityGroupName: Description: Name of cluster security group Value: Ref: SecurityGroup See Also AWS::Redshift::Cluster (p. 1373) Amazon RDS Template Snippets Topics • Amazon RDS DB Instance Resource (p. 416) • Amazon RDS Oracle Database DB Instance Resource (p. 417) • Amazon RDS DBSecurityGroup Resource for CIDR Range (p. 417) • Amazon RDS DBSecurityGroup with an Amazon EC2 security group (p. 418) • Multiple VPC security groups (p. 419) • Amazon RDS Database Instance in a VPC Security Group (p. 420) Amazon RDS DB Instance Resource This example shows an Amazon RDS DB Instance resource. Because the optional EngineVersion property is not specified, the default engine version is used for this DB Instance. For details about the default engine version and other default settings, see CreateDBInstance. The DBSecurityGroups property authorizes network ingress to the AWS::RDS::DBSecurityGroup resources named MyDbSecurityByEC2SecurityGroup and MyDbSecurityByCIDRIPGroup. For details, see AWS::RDS::DBInstance (p. 1341). The DB Instance resource also has a DeletionPolicy attribute set to Snapshot. With the Snapshot DeletionPolicy set, AWS CloudFormation will take a snapshot of this DB Instance before deleting it during stack deletion. JSON "MyDB" : { "Type" : "AWS::RDS::DBInstance", "Properties" : { "DBSecurityGroups" : [ {"Ref" : "MyDbSecurityByEC2SecurityGroup"}, {"Ref" : "MyDbSecurityByCIDRIPGroup"} ], "AllocatedStorage" : "5", "DBInstanceClass" : "db.m1.small", "Engine" : "MySQL", "MasterUsername" : "MyName", "MasterUserPassword" : "MyPassword" }, "DeletionPolicy" : "Snapshot" } YAML MyDB: Type: AWS::RDS::DBInstance Properties: API Version 2010-05-15 416 AWS CloudFormation User Guide Amazon RDS DBSecurityGroups: - Ref: MyDbSecurityByEC2SecurityGroup - Ref: MyDbSecurityByCIDRIPGroup AllocatedStorage: '5' DBInstanceClass: db.m1.small Engine: MySQL MasterUsername: MyName MasterUserPassword: MyPassword DeletionPolicy: Snapshot Amazon RDS Oracle Database DB Instance Resource This example creates an Oracle Database DB Instance resource by specifying the Engine as oracle-ee with a license model of bring-your-own-license. For details about the settings for Oracle Database DB instances, see CreateDBInstance. The DBSecurityGroups property authorizes network ingress to the AWS::RDS::DBSecurityGroup resources named MyDbSecurityByEC2SecurityGroup and MyDbSecurityByCIDRIPGroup. For details, see AWS::RDS::DBInstance (p. 1341). The DB Instance resource also has a DeletionPolicy attribute set to Snapshot. With the Snapshot DeletionPolicy set, AWS CloudFormation will take a snapshot of this DB Instance before deleting it during stack deletion. JSON "MyDB" : { "Type" : "AWS::RDS::DBInstance", "Properties" : { "DBSecurityGroups" : [ {"Ref" : "MyDbSecurityByEC2SecurityGroup"}, {"Ref" : "MyDbSecurityByCIDRIPGroup"} ], "AllocatedStorage" : "5", "DBInstanceClass" : "db.m1.small", "Engine" : "oracle-ee", "LicenseModel" : "bring-your-own-license", "MasterUsername" : "master", "MasterUserPassword" : "SecretPassword01" }, "DeletionPolicy" : "Snapshot" } YAML MyDB: Type: AWS::RDS::DBInstance Properties: DBSecurityGroups: - Ref: MyDbSecurityByEC2SecurityGroup - Ref: MyDbSecurityByCIDRIPGroup AllocatedStorage: '5' DBInstanceClass: db.m1.small Engine: oracle-ee LicenseModel: bring-your-own-license MasterUsername: master MasterUserPassword: SecretPassword01 DeletionPolicy: Snapshot Amazon RDS DBSecurityGroup Resource for CIDR Range This example shows an Amazon RDS DBSecurityGroup resource with ingress authorization for the specified CIDR range in the format ddd.ddd.ddd.ddd/dd. For details, see AWS::RDS::DBSecurityGroup (p. 1360) and Amazon RDS Security Group Rule (p. 2111). API Version 2010-05-15 417 AWS CloudFormation User Guide Amazon RDS JSON "MyDbSecurityByCIDRIPGroup" : { "Type" : "AWS::RDS::DBSecurityGroup", "Properties" : { "GroupDescription" : "Ingress for CIDRIP", "DBSecurityGroupIngress" : { "CIDRIP" : "192.168.0.0/32" } } } YAML MyDbSecurityByCIDRIPGroup: Type: AWS::RDS::DBSecurityGroup Properties: GroupDescription: Ingress for CIDRIP DBSecurityGroupIngress: CIDRIP: "192.168.0.0/32" Amazon RDS DBSecurityGroup with an Amazon EC2 security group This example shows an AWS::RDS::DBSecurityGroup (p. 1360) resource with ingress authorization from an Amazon EC2 security group referenced by MyEc2SecurityGroup. To do this, you define an EC2 security group and then use the intrinsic Ref function to refer to the EC2 security group within your DBSecurityGroup. JSON "DBInstance" : { "Type": "AWS::RDS::DBInstance", "Properties": { "DBName" : { "Ref" : "Engine" : "MySQL", "MasterUsername" : { "Ref" : "DBInstanceClass" : { "Ref" : "DBSecurityGroups" : [ { "Ref" "AllocatedStorage" : { "Ref" : "MasterUserPassword": { "Ref" : } }, "DBName" }, "DBUsername" }, "DBClass" }, : "DBSecurityGroup" } ], "DBAllocatedStorage" }, "DBPassword" } "DBSecurityGroup": { "Type": "AWS::RDS::DBSecurityGroup", "Properties": { "DBSecurityGroupIngress": { "EC2SecurityGroupName": { "Ref": "WebServerSecurityGroup" } }, "GroupDescription" : "Frontend Access" } }, "WebServerSecurityGroup" : { "Type" : "AWS::EC2::SecurityGroup", "Properties" : { "GroupDescription" : "Enable HTTP access via port 80 and SSH access", API Version 2010-05-15 418 AWS CloudFormation User Guide Amazon RDS "SecurityGroupIngress" : [ {"IpProtocol" : "tcp", "FromPort" : "80", "ToPort" : "80", "CidrIp" : "0.0.0.0/0"}, {"IpProtocol" : "tcp", "FromPort" : "22", "ToPort" : "22", "CidrIp" : "0.0.0.0/0"} ] } } YAML This example is extracted from the following full example: Drupal_Single_Instance_With_RDS.template DBInstance: Type: AWS::RDS::DBInstance Properties: DBName: Ref: DBName Engine: MySQL MasterUsername: Ref: DBUsername DBInstanceClass: Ref: DBClass DBSecurityGroups: - Ref: DBSecurityGroup AllocatedStorage: Ref: DBAllocatedStorage MasterUserPassword: Ref: DBPassword DBSecurityGroup: Type: AWS::RDS::DBSecurityGroup Properties: DBSecurityGroupIngress: EC2SecurityGroupName: Ref: WebServerSecurityGroup GroupDescription: Frontend Access WebServerSecurityGroup: Type: AWS::EC2::SecurityGroup Properties: GroupDescription: Enable HTTP access via port 80 and SSH access SecurityGroupIngress: - IpProtocol: tcp FromPort: '80' ToPort: '80' CidrIp: 0.0.0.0/0 - IpProtocol: tcp FromPort: '22' ToPort: '22' CidrIp: 0.0.0.0/0 Multiple VPC security groups This example shows an AWS::RDS::DBSecurityGroup (p. 1360) resource with ingress authorization for multiple Amazon EC2 VPC security groups in AWS::RDS::DBSecurityGroupIngress (p. 1363). JSON { "Resources" : { "DBinstance" : { "Type" : "AWS::RDS::DBInstance", "Properties" : { "AllocatedStorage" : "5", API Version 2010-05-15 419 AWS CloudFormation User Guide Amazon RDS "DBInstanceClass" : "db.m1.small", "DBName" : {"Ref": "MyDBName" }, "DBSecurityGroups" : [ { "Ref" : "DbSecurityByEC2SecurityGroup" } ], "DBSubnetGroupName" : { "Ref" : "MyDBSubnetGroup" }, "Engine" : "MySQL", "MasterUserPassword": { "Ref" : "MyDBPassword" }, "MasterUsername" : { "Ref" : "MyDBUsername" } }, "DeletionPolicy" : "Snapshot" } } }, "DbSecurityByEC2SecurityGroup" : { "Type" : "AWS::RDS::DBSecurityGroup", "Properties" : { "GroupDescription" : "Ingress for Amazon EC2 security group", "EC2VpcId" : { "Ref" : "MyVPC" }, "DBSecurityGroupIngress" : [ { "EC2SecurityGroupId" : "sg-b0ff1111", "EC2SecurityGroupOwnerId" : "111122223333" }, { "EC2SecurityGroupId" : "sg-ffd722222", "EC2SecurityGroupOwnerId" : "111122223333" } ] } } YAML Resources: DBinstance: Type: AWS::RDS::DBInstance Properties: AllocatedStorage: '5' DBInstanceClass: db.m1.small DBName: Ref: MyDBName DBSecurityGroups: - Ref: DbSecurityByEC2SecurityGroup DBSubnetGroupName: Ref: MyDBSubnetGroup Engine: MySQL MasterUserPassword: Ref: MyDBPassword MasterUsername: Ref: MyDBUsername DeletionPolicy: Snapshot DbSecurityByEC2SecurityGroup: Type: AWS::RDS::DBSecurityGroup Properties: GroupDescription: Ingress for Amazon EC2 security group EC2VpcId: Ref: MyVPC DBSecurityGroupIngress: - EC2SecurityGroupId: sg-b0ff1111 EC2SecurityGroupOwnerId: '111122223333' - EC2SecurityGroupId: sg-ffd722222 EC2SecurityGroupOwnerId: '111122223333' Amazon RDS Database Instance in a VPC Security Group This example shows an Amazon RDS database instance associated with an Amazon EC2 VPC security group. API Version 2010-05-15 420 AWS CloudFormation User Guide Amazon RDS JSON { } "DBEC2SecurityGroup": { "Type": "AWS::EC2::SecurityGroup", "Properties" : { "GroupDescription": "Open database for access", "SecurityGroupIngress" : [{ "IpProtocol" : "tcp", "FromPort" : "3306", "ToPort" : "3306", "SourceSecurityGroupName" : { "Ref" : "WebServerSecurityGroup" } }] } }, "DBInstance" : { "Type": "AWS::RDS::DBInstance", "Properties": { "DBName" : { "Ref" : "DBName" }, "Engine" : "MySQL", "MultiAZ" : { "Ref": "MultiAZDatabase" }, "MasterUsername" : { "Ref" : "DBUser" }, "DBInstanceClass" : { "Ref" : "DBClass" }, "AllocatedStorage" : { "Ref" : "DBAllocatedStorage" }, "MasterUserPassword": { "Ref" : "DBPassword" }, "VPCSecurityGroups" : [ { "Fn::GetAtt": [ "DBEC2SecurityGroup", "GroupId" ] } ] } } YAML DBEC2SecurityGroup: Type: AWS::EC2::SecurityGroup Properties: GroupDescription: Open database for access SecurityGroupIngress: - IpProtocol: tcp FromPort: '3306' ToPort: '3306' SourceSecurityGroupName: Ref: WebServerSecurityGroup DBInstance: Type: AWS::RDS::DBInstance Properties: DBName: Ref: DBName Engine: MySQL MultiAZ: Ref: MultiAZDatabase MasterUsername: Ref: DBUser DBInstanceClass: Ref: DBClass AllocatedStorage: Ref: DBAllocatedStorage MasterUserPassword: Ref: DBPassword VPCSecurityGroups: - !GetAtt DBEC2SecurityGroup.GroupId API Version 2010-05-15 421 AWS CloudFormation User Guide Route 53 Route 53 Template Snippets Topics • Amazon Route 53 Resource Record Set Using Hosted Zone Name or ID (p. 422) • Using RecordSetGroup to Set Up Weighted Resource Record Sets (p. 423) • Using RecordSetGroup to Set Up an Alias Resource Record Set (p. 424) • Alias Resource Record Set for a CloudFront Distribution (p. 425) Amazon Route 53 Resource Record Set Using Hosted Zone Name or ID When you create an Amazon Route 53 resource record set, you must specify the hosted zone where you want to add it. AWS CloudFormation provides two ways to do this. You can explicitly specify the hosted zone using the HostedZoneId property or have AWS CloudFormation find the hosted zone using the HostedZoneName property. If you use the HostedZoneName property and there are multiple hosted zones with the same domain name, AWS CloudFormation doesn't create the stack. Adding RecordSet using HostedZoneId This example adds an Amazon Route 53 resource record set containing an SPF record for the domain name mysite.example.com that uses the HostedZoneId property to specify the hosted zone. JSON "myDNSRecord" : { "Type" : "AWS::Route53::RecordSet", "Properties" : { "HostedZoneId" : "Z3DG6IL3SJCGPX", "Name" : "mysite.example.com.", "Type" : "SPF", "TTL" : "900", "ResourceRecords" : [ "\"v=spf1 ip4:192.168.0.1/16 -all\"" ] } } YAML myDNSRecord: Type: AWS::Route53::RecordSet Properties: HostedZoneId: Z3DG6IL3SJCGPX Name: mysite.example.com. Type: SPF TTL: '900' ResourceRecords: - '"v=spf1 ip4:192.168.0.1/16 -all"' Adding RecordSet using HostedZoneName This example adds an Amazon Route 53 resource record set containing A records for the domain name "mysite.example.com" using the HostedZoneName property to specify the hosted zone. JSON "myDNSRecord2" : { API Version 2010-05-15 422 AWS CloudFormation User Guide Route 53 } "Type" : "AWS::Route53::RecordSet", "Properties" : { "HostedZoneName" : "example.com.", "Name" : "mysite.example.com.", "Type" : "A", "TTL" : "900", "ResourceRecords" : [ "192.168.0.1", "192.168.0.2" ] } YAML myDNSRecord2: Type: AWS::Route53::RecordSet Properties: HostedZoneName: example.com. Name: mysite.example.com. Type: A TTL: '900' ResourceRecords: - 192.168.0.1 - 192.168.0.2 Using RecordSetGroup to Set Up Weighted Resource Record Sets This example uses an AWS::Route53::RecordSetGroup (p. 1401) to set up two CNAME records for the "example.com." hosted zone. The RecordSets property contains the CNAME record sets for the "mysite.example.com" DNS name. Each record set contains an identifier (SetIdentifier) and weight (Weight). The weighting for Frontend One is 40% (4 of 10) and Frontend Two is 60% (6 of 10). For more information about weighted resource record sets, see Setting Up Weighted Resource Record Sets in Route 53 Developer Guide. JSON "myDNSOne" : { "Type" : "AWS::Route53::RecordSetGroup", "Properties" : { "HostedZoneName" : "example.com.", "Comment" : "Weighted RR for my frontends.", "RecordSets" : [ { "Name" : "mysite.example.com.", "Type" : "CNAME", "TTL" : "900", "SetIdentifier" : "Frontend One", "Weight" : "4", "ResourceRecords" : ["example-ec2.amazonaws.com"] }, { "Name" : "mysite.example.com.", "Type" : "CNAME", "TTL" : "900", "SetIdentifier" : "Frontend Two", "Weight" : "6", "ResourceRecords" : ["example-ec2-larger.amazonaws.com"] } API Version 2010-05-15 423 AWS CloudFormation User Guide Route 53 } } ] YAML myDNSOne: Type: AWS::Route53::RecordSetGroup Properties: HostedZoneName: example.com. Comment: Weighted RR for my frontends. RecordSets: - Name: mysite.example.com. Type: CNAME TTL: '900' SetIdentifier: Frontend One Weight: '4' ResourceRecords: - example-ec2.amazonaws.com - Name: mysite.example.com. Type: CNAME TTL: '900' SetIdentifier: Frontend Two Weight: '6' ResourceRecords: - example-ec2-larger.amazonaws.com Using RecordSetGroup to Set Up an Alias Resource Record Set This example uses an AWS::Route53::RecordSetGroup (p. 1401) to set up an alias resource record set for the "example.com." hosted zone. The RecordSets property contains the A record for the zone apex "example.com." The AliasTarget (p. 2112) property specifies the hosted zone ID and DNS name for the myELB LoadBalancer by using the GetAtt (p. 2285) intrinsic function to retrieve the CanonicalHostedZoneNameID and DNSName properties of myELB resource. For more information about alias resource record sets, see Creating Alias Resource Record Sets in the Route 53 Developer Guide. JSON "myELB" : { "Type" : "AWS::ElasticLoadBalancing::LoadBalancer", "Properties" : { "AvailabilityZones" : [ "us-east-1a" ], "Listeners" : [ { "LoadBalancerPort" : "80", "InstancePort" : "80", "Protocol" : "HTTP" } ] } }, "myDNS" : { "Type" : "AWS::Route53::RecordSetGroup", "Properties" : { "HostedZoneName" : "example.com.", "Comment" : "Zone apex alias targeted to myELB LoadBalancer.", "RecordSets" : [ { "Name" : "example.com.", "Type" : "A", "AliasTarget" : { "HostedZoneId" : { "Fn::GetAtt" : ["myELB", "CanonicalHostedZoneNameID"] }, API Version 2010-05-15 424 AWS CloudFormation User Guide Route 53 } } ] } } "DNSName" : { "Fn::GetAtt" : ["myELB","DNSName"] } YAML myELB: Type: AWS::ElasticLoadBalancing::LoadBalancer Properties: AvailabilityZones: - "us-east-1a" Listeners: - LoadBalancerPort: '80' InstancePort: '80' Protocol: HTTP myDNS: Type: AWS::Route53::RecordSetGroup Properties: HostedZoneName: example.com. Comment: Zone apex alias targeted to myELB LoadBalancer. RecordSets: - Name: example.com. Type: A AliasTarget: HostedZoneId: !GetAtt myELB.CanonicalHostedZoneNameID DNSName: !GetAtt myELB.DNSName Alias Resource Record Set for a CloudFront Distribution The following example creates an alias record set that routes queries to the specified CloudFront distribution domain name. Note When you create alias resource record sets, you must specify Z2FDTNDATAQYW2 for the HostedZoneId property, as shown in the following example. Alias resource record sets for CloudFront can't be created in a private zone. JSON "myDNS" : { "Type" : "AWS::Route53::RecordSetGroup", "Properties" : { "HostedZoneId" : { "Ref" : "myHostedZoneID" }, "RecordSets" : [{ "Name" : { "Ref" : "myRecordSetDomainName" }, "Type" : "A", "AliasTarget" : { "HostedZoneId" : "Z2FDTNDATAQYW2", "DNSName" : { "Ref" : "myCloudFrontDistributionDomainName" } } }] } } YAML myDNS: API Version 2010-05-15 425 AWS CloudFormation User Guide Amazon S3 Type: AWS::Route53::RecordSetGroup Properties: HostedZoneId: Ref: myHostedZoneID RecordSets: - Name: Ref: myRecordSetDomainName Type: A AliasTarget: HostedZoneId: Z2FDTNDATAQYW2 DNSName: Ref: myCloudFrontDistributionDomainName Amazon S3 Template Snippets Topics • Creating an Amazon S3 Bucket with Defaults (p. 426) • Creating an Amazon S3 Bucket for Website Hosting and with a DeletionPolicy (p. 426) • Creating a Static Website Using a Custom Domain (p. 428) Creating an Amazon S3 Bucket with Defaults This example uses a AWS::S3::Bucket (p. 1403) to create a bucket with default settings. JSON "myS3Bucket" : { "Type" : "AWS::S3::Bucket" } YAML MyS3Bucket: Type: AWS::S3::Bucket Creating an Amazon S3 Bucket for Website Hosting and with a DeletionPolicy This example creates a bucket as a website. The AccessControl property is set to the canned ACL PublicRead (public read permissions are required for buckets set up for website hosting). Because this bucket resource has a DeletionPolicy attribute (p. 2248) set to Retain, AWS CloudFormation will not delete this bucket when it deletes the stack. The Output section uses Fn::GetAtt to retrieve the WebsiteURL attribute and DomainName attribute of the S3Bucket resource. JSON { "AWSTemplateFormatVersion": "2010-09-09", "Resources": { "S3Bucket": { "Type": "AWS::S3::Bucket", "Properties": { "AccessControl": "PublicRead", "WebsiteConfiguration": { "IndexDocument": "index.html", API Version 2010-05-15 426 AWS CloudFormation User Guide Amazon S3 } "ErrorDocument": "error.html" }, "DeletionPolicy": "Retain" }, "BucketPolicy": { "Type": "AWS::S3::BucketPolicy", "Properties": { "PolicyDocument": { "Id": "MyPolicy", "Version": "2012-10-17", "Statement": [ { "Sid": "PublicReadForGetBucketObjects", "Effect": "Allow", "Principal": "*", "Action": "s3:GetObject", "Resource": { "Fn::Join": [ "", [ "arn:aws:s3:::", { "Ref": "S3Bucket" }, "/*" ] ] } } ] }, "Bucket": { "Ref": "S3Bucket" } } } }, "Outputs": { "WebsiteURL": { "Value": { "Fn::GetAtt": [ "S3Bucket", "WebsiteURL" ] }, "Description": "URL for website hosted on S3" }, "S3BucketSecureURL": { "Value": { "Fn::Join": [ "", [ "https://", { "Fn::GetAtt": [ "S3Bucket", "DomainName" ] } ] ] }, "Description": "Name of S3 bucket to hold website content" } } API Version 2010-05-15 427 AWS CloudFormation User Guide Amazon S3 } YAML AWSTemplateFormatVersion: 2010-09-09 Resources: S3Bucket: Type: AWS::S3::Bucket Properties: AccessControl: PublicRead WebsiteConfiguration: IndexDocument: index.html ErrorDocument: error.html DeletionPolicy: Retain BucketPolicy: Type: AWS::S3::BucketPolicy Properties: PolicyDocument: Id: MyPolicy Version: 2012-10-17 Statement: - Sid: PublicReadForGetBucketObjects Effect: Allow Principal: '*' Action: 's3:GetObject' Resource: !Join - '' - - 'arn:aws:s3:::' - !Ref S3Bucket - /* Bucket: !Ref S3Bucket Outputs: WebsiteURL: Value: !GetAtt - S3Bucket - WebsiteURL Description: URL for website hosted on S3 S3BucketSecureURL: Value: !Join - '' - - 'https://' - !GetAtt - S3Bucket - DomainName Description: Name of S3 bucket to hold website content Creating a Static Website Using a Custom Domain You can use Route 53 with a registered domain. The following sample assumes that you have already created a hosted zone in Route 53 for your domain. The example creates two buckets for website hosting. The root bucket hosts the content, and the other bucket redirects www.domainname.com requests to the root bucket. The record sets map your domain name to Amazon S3 endpoints. Note that you will also need to add a bucket policy, as shown in the examples above. For more information about using a custom domain, see Setting Up a Static Website Using a Custom Domain in the Amazon Simple Storage Service Developer Guide. JSON { "AWSTemplateFormatVersion": "2010-09-09", API Version 2010-05-15 428 AWS CloudFormation User Guide Amazon S3 "Mappings" : { "RegionMap" : { "us-east-1" : { "S3hostedzoneID" : "Z3AQBSTGFYJSTF", "websiteendpoint" : "s3website-us-east-1.amazonaws.com" }, "us-west-1" : { "S3hostedzoneID" : "Z2F56UZL2M1ACD", "websiteendpoint" : "s3website-us-west-1.amazonaws.com" }, "us-west-2" : { "S3hostedzoneID" : "Z3BJ6K6RIION7M", "websiteendpoint" : "s3website-us-west-2.amazonaws.com" }, "eu-west-1" : { "S3hostedzoneID" : "Z1BKCTXD74EZPE", "websiteendpoint" : "s3website-eu-west-1.amazonaws.com" }, "ap-southeast-1" : { "S3hostedzoneID" : "Z3O0J2DXBE1FTB", "websiteendpoint" : "s3-website-ap-southeast-1.amazonaws.com" }, "ap-southeast-2" : { "S3hostedzoneID" : "Z1WCIGYICN2BYD", "websiteendpoint" : "s3-website-ap-southeast-2.amazonaws.com" }, "ap-northeast-1" : { "S3hostedzoneID" : "Z2M4EHUR26P7ZW", "websiteendpoint" : "s3-website-ap-northeast-1.amazonaws.com" }, "sa-east-1" : { "S3hostedzoneID" : "Z31GFT0UA1I2HV", "websiteendpoint" : "s3website-sa-east-1.amazonaws.com" } } }, "Parameters": { "RootDomainName": { "Description": "Domain name for your website (example.com)", "Type": "String" } }, "Resources": { "RootBucket": { "Type": "AWS::S3::Bucket", "Properties": { "BucketName" : {"Ref":"RootDomainName"}, "AccessControl": "PublicRead", "WebsiteConfiguration": { "IndexDocument":"index.html", "ErrorDocument":"404.html" } } }, "WWWBucket": { "Type": "AWS::S3::Bucket", "Properties": { "BucketName": { "Fn::Join": ["", ["www.", {"Ref":"RootDomainName"}]] }, "AccessControl": "BucketOwnerFullControl", "WebsiteConfiguration": { "RedirectAllRequestsTo": { "HostName": {"Ref": "RootBucket"} } } } }, "myDNS": { "Type": "AWS::Route53::RecordSetGroup", "Properties": { "HostedZoneName": { "Fn::Join": ["", [{"Ref": "RootDomainName"}, "."]] }, "Comment": "Zone apex alias.", "RecordSets": [ { "Name": {"Ref": "RootDomainName"}, "Type": "A", "AliasTarget": { "HostedZoneId": {"Fn::FindInMap" : [ "RegionMap", { "Ref" : "AWS::Region" }, "S3hostedzoneID"]}, API Version 2010-05-15 429 AWS CloudFormation User Guide Amazon S3 "DNSName": {"Fn::FindInMap" : [ "RegionMap", { "Ref" : "AWS::Region" }, "websiteendpoint"]} } }, { "Name": { "Fn::Join": ["", ["www.", {"Ref":"RootDomainName"}]] }, "Type": "CNAME", "TTL" : "900", "ResourceRecords" : [ {"Fn::GetAtt":["WWWBucket", "DomainName"]} ] } ] } } }, "Outputs": { "WebsiteURL": { "Value": {"Fn::GetAtt": ["RootBucket", "WebsiteURL"]}, "Description": "URL for website hosted on S3" } } } YAML Parameters: RootDomainName: Description: Domain name for your website (example.com) Type: String Mappings: RegionMap: us-east-1: S3hostedzoneID: Z3AQBSTGFYJSTF websiteendpoint: s3-website-us-east-1.amazonaws.com us-west-1: S3hostedzoneID: Z2F56UZL2M1ACD websiteendpoint: s3-website-us-west-1.amazonaws.com us-west-2: S3hostedzoneID: Z3BJ6K6RIION7M websiteendpoint: s3-website-us-west-2.amazonaws.com eu-west-1: S3hostedzoneID: Z1BKCTXD74EZPE websiteendpoint: s3-website-eu-west-1.amazonaws.com ap-southeast-1: S3hostedzoneID: Z3O0J2DXBE1FTB websiteendpoint: s3-website-ap-southeast-1.amazonaws.com ap-southeast-2: S3hostedzoneID: Z1WCIGYICN2BYD websiteendpoint: s3-website-ap-southeast-2.amazonaws.com ap-northeast-1: S3hostedzoneID: Z2M4EHUR26P7ZW websiteendpoint: s3-website-ap-northeast-1.amazonaws.com sa-east-1: S3hostedzoneID: Z31GFT0UA1I2HV websiteendpoint: s3-website-sa-east-1.amazonaws.com Resources: RootBucket: Type: AWS::S3::Bucket Properties: BucketName: !Ref RootDomainName AccessControl: PublicRead API Version 2010-05-15 430 AWS CloudFormation User Guide Amazon SNS WebsiteConfiguration: IndexDocument: index.html ErrorDocument: 404.html WWWBucket: Type: AWS::S3::Bucket Properties: BucketName: !Sub - www.${Domain} - Domain: !Ref RootDomainName AccessControl: BucketOwnerFullControl WebsiteConfiguration: RedirectAllRequestsTo: HostName: !Ref RootBucket myDNS: Type: AWS::Route53::RecordSetGroup Properties: HostedZoneName: !Sub - ${Domain}. - Domain: !Ref RootDomainName Comment: Zone apex alias. RecordSets: Name: !Ref RootDomainName Type: A AliasTarget: HostedZoneId: !FindInMap [ RegionMap, !Ref 'AWS::Region', S3hostedzoneID] DNSName: !FindInMap [ RegionMap, !Ref 'AWS::Region', websiteendpoint] Name: !Sub - www.${Domain} - Domain: !Ref RootDomainName Type: CNAME TTL: 900 ResourceRecords: - !GetAtt WWWBucket.DomainName Outputs: WebsiteURL: Value: !GetAtt RootBucket.WebsiteURL Description: URL for website hosted on S3 Amazon SNS Template Snippets This example shows an Amazon SNS topic resource. It requires a valid email address. JSON "MySNSTopic" : { "Type" : "AWS::SNS::Topic", "Properties" : { "Subscription" : [ { "Endpoint" : "add valid email address", "Protocol" : "email" } ] } } YAML MySNSTopic: Type: AWS::SNS::Topic API Version 2010-05-15 431 AWS CloudFormation User Guide Amazon SQS Properties: Subscription: - Endpoint: "add valid email address" Protocol: email Amazon SQS Template Snippets This example shows an Amazon SQS queue. JSON "MyQueue" : { "Type" : "AWS::SQS::Queue", "Properties" : { "VisibilityTimeout" : "value" } } YAML MyQueue: Type: AWS::SQS::Queue Properties: VisibilityTimeout: value Custom Resources Custom resources enable you to write custom provisioning logic in templates that AWS CloudFormation runs anytime you create, update (if you changed the custom resource), or delete stacks. For example, you might want to include resources that aren't available as AWS CloudFormation resource types (p. 499). You can include those resources by using custom resources. That way you can still manage all your related resources in a single stack. Use the AWS::CloudFormation::CustomResource (p. 674) or Custom::String (p. 674) resource type to define custom resources in your templates. Custom resources require one property: the service token, which specifies where AWS CloudFormation sends requests to, such as an Amazon SNS topic. Note If you use the VPC endpoint feature, custom resources in the VPC must have access to AWS CloudFormation-specific S3 buckets. Custom resources must send responses to a pre-signed Amazon S3 URL. If they can't send responses to Amazon S3, AWS CloudFormation won't receive a response and the stack operation fails. For more information, see AWS CloudFormation and VPC Endpoints (p. 24). How Custom Resources Work Any action taken for a custom resource involves three parties. template developer Creates a template that includes a custom resource type. The template developer specifies the service token and any input data in the template. API Version 2010-05-15 432 AWS CloudFormation User Guide How Custom Resources Work custom resource provider Owns the custom resource and determines how to handle and respond to requests from AWS CloudFormation. The custom resource provider must provide a service token that the template developer uses. AWS CloudFormation During a stack operation, sends a request to a service token that is specified in the template, and then waits for a response before proceeding with the stack operation. The template developer and custom resource provider can be the same person or entity, but the process is the same. The following steps describe the general process: 1. The template developer defines a custom resource in his or her template, which includes a service token and any input data parameters. Depending on the custom resource, the input data might be required; however, the service token is always required. The service token specifies where AWS CloudFormation sends requests to, such as to an Amazon SNS topic ARN or to an AWS Lambda function ARN. For more information, see AWS::CloudFormation::CustomResource (p. 674). The service token and the structure of the input data is defined by the custom resource provider. 2. Whenever anyone uses the template to create, update, or delete a custom resource, AWS CloudFormation sends a request to the specified service token. The service token must be in the same region in which you are creating the stack. In the request, AWS CloudFormation includes information such as the request type and a pre-signed Amazon Simple Storage Service URL, where the custom resource sends responses to. For more information about what's included in the request, see Custom Resource Request Objects (p. 446). The following sample data shows what AWS CloudFormation includes in a request: { } "RequestType" : "Create", "ResponseURL" : "http://pre-signed-S3-url-for-response", "StackId" : "arn:aws:cloudformation:us-west-2:EXAMPLE/stack-name/guid", "RequestId" : "unique id for this create request", "ResourceType" : "Custom::TestResource", "LogicalResourceId" : "MyTestResource", "ResourceProperties" : { "Name" : "Value", "List" : [ "1", "2", "3" ] } Note In this example, ResourceProperties allows AWS CloudFormation to create a custom payload to send to the Lambda function. 3. The custom resource provider processes the AWS CloudFormation request and returns a response of SUCCESS or FAILED to the pre-signed URL. The custom resource provider provides the response in a JSON-formatted file and uploads it to the pre-signed S3 URL. For more information, see Uploading Objects Using Pre-Signed URLs in the Amazon Simple Storage Service Developer Guide. In the response, the custom resource provider can also include name-value pairs that the template developer can access. For example, the response can include output data if the request succeeded or an error message if the request failed. For more information about responses, see Custom Resource Response Objects (p. 448). API Version 2010-05-15 433 AWS CloudFormation User Guide Amazon Simple Notification Service-backed Custom Resources Important If the name-value pairs contain sensitive information, you should use the NoEcho field to mask the output of the custom resource. Otherwise, the values are visible through APIs that surface property values (such as DescribeStackEvents). The custom resource provider is responsible for listening and responding to the request. For example, for Amazon SNS notifications, the custom resource provider must listen and respond to notifications that are sent to a specific topic ARN. AWS CloudFormation waits and listens for a response in the presigned URL location. The following sample data shows what a custom resource might include in a response: { } "Status" : "SUCCESS", "PhysicalResourceId" : "TestResource1", "StackId" : "arn:aws:cloudformation:us-west-2:EXAMPLE:stack/stack-name/guid", "RequestId" : "unique id for this create request", "LogicalResourceId" : "MyTestResource", "Data" : { "OutputName1" : "Value1", "OutputName2" : "Value2", } 4. After getting a SUCCESS response, AWS CloudFormation proceeds with the stack operation. If a FAILED or no response is returned, the operation fails. Any output data from the custom resource is stored in the pre-signed URL location. The template developer can retrieve that data by using the Fn::GetAtt (p. 2285) function. Amazon Simple Notification Service-backed Custom Resources When you associate an Amazon SNS topic with a custom resource, you use Amazon SNS notifications to trigger custom provisioning logic. With custom resources and Amazon SNS, you can enable scenarios such as adding new resources to a stack and injecting dynamic data into a stack. For example, when you create a stack, AWS CloudFormation can send a create request to a topic that's monitored by an application that's running on an Amazon Elastic Compute Cloud instance. The Amazon SNS notification triggers the application to carry out additional provisioning tasks, such as retrieve a pool of white-listed Elastic IPs. After it's done, the application sends a response (and any output data) that notifies AWS CloudFormation to proceed with the stack operation. Walkthrough: Using Amazon Simple Notification Service to Create Custom Resources This walkthrough will step through the custom resource process, explaining the sequence of events and messages sent and received as a result of custom resource stack creation, updates, and deletion. Step 1: Stack Creation 1. The template developer creates an AWS CloudFormation stack that contains a custom resource; in the template example below, we use the custom resource type name Custom::SeleniumTester for the custom resource MySeleniumTest. The custom resource type is declared with a service token, optional provider-specific properties, and optional Fn::GetAtt (p. 2285) attributes that are defined by the custom resource provider. These API Version 2010-05-15 434 AWS CloudFormation User Guide Amazon Simple Notification Service-backed Custom Resources properties and attributes can be used to pass information from the template developer to the custom resource provider and vice-versa. Custom resource type names must be alphanumeric and can have a maximum length of 60 characters. The following example shows a template that has both custom properties and return attributes: { "AWSTemplateFormatVersion" : "2010-09-09", "Resources" : { "MySeleniumTest" : { "Type": "Custom::SeleniumTester", "Version" : "1.0", "Properties" : { "ServiceToken": "arn:aws:sns:us-west-2:123456789012:CRTest", "seleniumTester" : "SeleniumTest()", "endpoints" : [ "http://mysite.com", "http://myecommercesite.com/", "http:// search.mysite.com" ], "frequencyOfTestsPerHour" : [ "3", "2", "4" ] } } }, "Outputs" : { "topItem" : { "Value" : { "Fn::GetAtt" : ["MySeleniumTest", "resultsPage"] } }, "numRespondents" : { "Value" : { "Fn::GetAtt" : ["MySeleniumTest", "lastUpdate"] } } } } Note The names and values of the data accessed with Fn::GetAtt are returned by the custom resource provider during the provider's response to AWS CloudFormation. If the custom resource provider is a third-party, then the template developer must obtain the names of these return values from the custom resource provider. 2. AWS CloudFormation sends an Amazon SNS notification to the resource provider with a "RequestType" : "Create" that contains information about the stack, the custom resource properties from the stack template, and an S3 URL for the response. The SNS topic that is used to send the notification is embedded in the template in the ServiceToken property. To avoid using a hard-coded value, a template developer can use a template parameter so that the value is entered at the time the stack is launched. The following example shows a custom resource Create request which includes a custom resource type name, Custom::SeleniumTester, created with a LogicalResourceId of MySeleniumTester: { "RequestType" : "Create", "ResponseURL" : "http://pre-signed-S3-url-for-response", "StackId" : "arn:aws:cloudformation:us-west-2:123456789012:stack/stack-name/guid", "RequestId" : "unique id for this create request", "ResourceType" : "Custom::SeleniumTester", "LogicalResourceId" : "MySeleniumTester", "ResourceProperties" : { "seleniumTester" : "SeleniumTest()", "endpoints" : [ "http://mysite.com", "http://myecommercesite.com/", "http:// search.mysite.com" ], "frequencyOfTestsPerHour" : [ "3", "2", "4" ] } API Version 2010-05-15 435 AWS CloudFormation User Guide Amazon Simple Notification Service-backed Custom Resources } 3. The custom resource provider processes the data sent by the template developer and determines whether the Create request was successful. The resource provider then uses the S3 URL sent by AWS CloudFormation to send a response of either SUCCESS or FAILED. Depending on the response type, different response fields will be expected by AWS CloudFormation. Refer to the Responses section in the reference topic for the RequestType that is being processed. In response to a create or update request, the custom resource provider can return data elements in the Data (p. 449) field of the response. These are name/value pairs, and the names correspond to the Fn::GetAtt attributes used with the custom resource in the stack template. The values are the data that is returned when the template developer calls Fn::GetAtt on the resource with the attribute name. The following is an example of a custom resource response: { } "Status" : "SUCCESS", "PhysicalResourceId" : "Tester1", "StackId" : "arn:aws:cloudformation:us-west-2:123456789012:stack/stack-name/guid", "RequestId" : "unique id for this create request", "LogicalResourceId" : "MySeleniumTester", "Data" : { "resultsPage" : "http://www.myexampledomain/test-results/guid", "lastUpdate" : "2012-11-14T03:30Z", } The StackId, RequestId, and LogicalResourceId fields must be copied verbatim from the request. 4. AWS CloudFormation declares the stack status as CREATE_COMPLETE or CREATE_FAILED. If the stack was successfully created, the template developer can use the output values of the created custom resource by accessing them with Fn::GetAtt (p. 2285). For example, the custom resource template used for illustration used Fn::GetAtt to copy resource outputs into the stack outputs: "Outputs" : { "topItem" : { "Value" : { "Fn::GetAtt" : ["MySeleniumTest", "resultsPage"] } }, "numRespondents" : { "Value" : { "Fn::GetAtt" : ["MySeleniumTest", "lastUpdate"] } } } For detailed information about the request and response objects involved in Create requests, see Create (p. 450) in the Custom Resource Reference (p. 446). Step 2: Stack Updates To update an existing stack, you must submit a template that specifies updates for the properties of resources in the stack, as shown in the example below. AWS CloudFormation updates only the resources that have changes specified in the template. For more information about updating stacks, see AWS CloudFormation Stacks Updates (p. 118). API Version 2010-05-15 436 AWS CloudFormation User Guide Amazon Simple Notification Service-backed Custom Resources You can update custom resources that require a replacement of the underlying physical resource. When you update a custom resource in an AWS CloudFormation template, AWS CloudFormation sends an update request to that custom resource. If a custom resource requires a replacement, the new custom resource must send a response with the new physical ID. When AWS CloudFormation receives the response, it compares the PhysicalResourceId between the old and new custom resources. If they are different, AWS CloudFormation recognizes the update as a replacement and sends a delete request to the old resource, as shown in Step 3: Stack Deletion (p. 438). Note If you didn't make changes to the custom resource, AWS CloudFormation won't send requests to it during a stack update. 1. The template developer initiates an update to the stack that contains a custom resource. During an update, the template developer can specify new Properties in the stack template. The following is an example of an Update to the stack template using a custom resource type: { "AWSTemplateFormatVersion" : "2010-09-09", "Resources" : { "MySeleniumTest" : { "Type": "Custom::SeleniumTester", "Version" : "1.0", "Properties" : { "ServiceToken": "arn:aws:sns:us-west-2:123456789012:CRTest", "seleniumTester" : "SeleniumTest()", "endpoints" : [ "http://mysite.com", "http://myecommercesite.com/", "http:// search.mysite.com", "http://mynewsite.com" ], "frequencyOfTestsPerHour" : [ "3", "2", "4", "3" ] } } }, "Outputs" : { "topItem" : { "Value" : { "Fn::GetAtt" : ["MySeleniumTest", "resultsPage"] } }, "numRespondents" : { "Value" : { "Fn::GetAtt" : ["MySeleniumTest", "lastUpdate"] } } } } 2. AWS CloudFormation sends an Amazon SNS notification to the resource provider with a "RequestType" : "Update" that contains similar information to the Create call, except that the OldResourceProperties field contains the old resource properties, and ResourceProperties contains the updated (if any) resource properties. The following is an example of an Update request: { "RequestType" : "Update", "ResponseURL" : "http://pre-signed-S3-url-for-response", "StackId" : "arn:aws:cloudformation:us-west-2:123456789012:stack/stack-name/guid", "RequestId" : "uniqueid for this update request", "LogicalResourceId" : "MySeleniumTester", "ResourceType" : "Custom::SeleniumTester" "PhysicalResourceId" : "Tester1", "ResourceProperties" : { "seleniumTester" : "SeleniumTest()", API Version 2010-05-15 437 AWS CloudFormation User Guide Amazon Simple Notification Service-backed Custom Resources "endpoints" : [ "http://mysite.com", "http://myecommercesite.com/", "http:// search.mysite.com", "http://mynewsite.com" ], "frequencyOfTestsPerHour" : [ "3", "2", "4", "3" ] } "OldResourceProperties" : { "seleniumTester" : "SeleniumTest()", "endpoints" : [ "http://mysite.com", "http://myecommercesite.com/", "http:// search.mysite.com" ], "frequencyOfTestsPerHour" : [ "3", "2", "4" ] } } 3. The custom resource provider processes the data sent by AWS CloudFormation. The custom resource performs the update and sends a response of either SUCCESS or FAILED to the S3 URL. AWS CloudFormation then compares the PhysicalResourceIDs of old and new custom resources. If they are different, AWS CloudFormation recognizes that the update requires a replacement and sends a delete request to the old resource. The following example demonstrates the custom resource provider response to an Update request. { } "Status" : "SUCCESS", "StackId" : "arn:aws:cloudformation:us-west-2:123456789012:stack/stack-name/guid", "RequestId" : "uniqueid for this update request", "LogicalResourceId" : "MySeleniumTester", "PhysicalResourceId" : "Tester2" The StackId, RequestId, and LogicalResourceId fields must be copied verbatim from the request. 4. AWS CloudFormation declares the stack status as UPDATE_COMPLETE or UPDATE_FAILED. If the update fails, the stack rolls back. If the stack was successfully updated, the template developer can access any new output values of the created custom resource with Fn::GetAtt. For detailed information about the request and response objects involved in Update requests, see Update (p. 455) in the Custom Resource Reference (p. 446). Step 3: Stack Deletion 1. The template developer deletes a stack that contains a custom resource. AWS CloudFormation gets the current properties specified in the stack template along with the SNS topic, and prepares to make a request to the custom resource provider. 2. AWS CloudFormation sends an Amazon SNS notification to the resource provider with a "RequestType" : "Delete" that contains current information about the stack, the custom resource properties from the stack template, and an S3 URL for the response. Whenever you delete a stack or make an update that removes or replaces the custom resource, AWS CloudFormation compares the PhysicalResourceId between the old and new custom resources. If they are different, AWS CloudFormation recognizes the update as a replacement and sends a delete request for the old resource (OldPhysicalResource), as shown in the following example of a Delete request. { "RequestType" : "Delete", "ResponseURL" : "http://pre-signed-S3-url-for-response", "StackId" : "arn:aws:cloudformation:us-west-2:123456789012:stack/stack-name/guid", "RequestId" : "unique id for this delete request", API Version 2010-05-15 438 AWS CloudFormation User Guide AWS Lambda-backed Custom Resources "ResourceType" : "Custom::SeleniumTester", "LogicalResourceId" : "MySeleniumTester", "PhysicalResourceId" : "Tester1", "ResourceProperties" : { "seleniumTester" : "SeleniumTest()", "endpoints" : [ "http://mysite.com", "http://myecommercesite.com/", "http:// search.mysite.com", "http://mynewsite.com" ], "frequencyOfTestsPerHour" : [ "3", "2", "4", "3" ] } } DescribeStackResource, DescribeStackResources, and ListStackResources display the user-defined name if it has been specified. 3. The custom resource provider processes the data sent by AWS CloudFormation and determines whether the Delete request was successful. The resource provider then uses the S3 URL sent by AWS CloudFormation to send a response of either SUCCESS or FAILED. To successfully delete a stack with a custom resource, the custom resource provider must respond successfully to a delete request. The following is an example of a custom resource provider response to a Delete request: { } "Status" : "SUCCESS", "StackId" : "arn:aws:cloudformation:us-west-2:123456789012:stack/stack-name/guid", "RequestId" : "unique id for this delete request", "LogicalResourceId" : "MySeleniumTester", "PhysicalResourceId" : "Tester1" The StackId, RequestId, and LogicalResourceId fields must be copied verbatim from the request. 4. AWS CloudFormation declares the stack status as DELETE_COMPLETE or DELETE_FAILED. For detailed information about the request and response objects involved in Delete requests, see Delete (p. 453) in the Custom Resource Reference (p. 446). See Also • AWS CloudFormation Custom Resource Reference (p. 446) • AWS::CloudFormation::CustomResource (p. 674) • Fn::GetAtt (p. 2285) AWS Lambda-backed Custom Resources When you associate a Lambda function with a custom resource, the function is invoked whenever the custom resource is created, updated, or deleted. AWS CloudFormation calls a Lambda API to invoke the function and to pass all the request data (such as the request type and resource properties) to the function. The power and customizability of Lambda functions in combination with AWS CloudFormation enable a wide range of scenarios, such as dynamically looking up AMI IDs during stack creation, or implementing and using utility functions, such as string reversal functions. Topics • Walkthrough: Looking Up Amazon Machine Image IDs (p. 440) API Version 2010-05-15 439 AWS CloudFormation User Guide AWS Lambda-backed Custom Resources Walkthrough: Looking Up Amazon Machine Image IDs AWS CloudFormation templates that declare an Amazon Elastic Compute Cloud (Amazon EC2) instance must also specify an Amazon Machine Image (AMI) ID, which includes an operating system and other software and configuration information used to launch the instance. The correct AMI ID depends on the instance type and region in which you're launching your stack. And IDs can change regularly, such as when an AMI is updated with software updates. Normally, you might map AMI IDs to specific instance types and regions. To update the IDs, you manually change them in each of your templates. By using custom resources and AWS Lambda (Lambda), you can create a function that gets the IDs of the latest AMIs for the region and instance type that you're using so that you don't have to maintain mappings. This walkthrough shows you how to create a custom resource and associate a Lambda function with it to look up AMI IDs. Note that the walkthrough assumes that you understand how to use custom resources and Lambda. For more information, see Custom Resources (p. 432) or the AWS Lambda Developer Guide. Walkthrough Overview For this walkthrough, you'll create a stack with a custom resource, a Lambda function, and an EC2 instance. The walkthough provides sample code and a sample template that you'll use to create the stack. The sample template uses the custom resource type to invoke and send input values to the Lambda function. When you use the template, AWS CloudFormation invokes the function and sends information to it, such as the request type, input data, and a pre-signed Amazon Simple Storage Service (Amazon S3) URL. The function uses that information to look up the AMI ID, and then sends a response to the presigned URL. After AWS CloudFormation gets a response in the pre-signed URL location, it proceeds with creating the stack. When AWS CloudFormation creates the instance, it uses the Lambda function's response to specify the instance's AMI ID. The following list summarizes the process. You need AWS Identity and Access Management (IAM) permissions to use all the corresponding services, such as Lambda, Amazon EC2, and AWS CloudFormation. Note AWS CloudFormation is a free service; however, you are charged for the AWS resources, such as the Lambda function and EC2 instance, that you include in your stacks at the current rate for each. For more information about AWS pricing, see the detail page for each product at http:// aws.amazon.com. 1. Save the sample Lambda package in an Amazon Simple Storage Service (Amazon S3) bucket. (p. 441) The sample package contains everything that's required to create the Lambda function. You must save the package in a bucket that's in the same region in which you will create your stack. 2. Use the sample template to create a stack. (p. 441) The stack demonstrates how you associate the Lambda function with a custom resource and how to use the results from the function to specify an AMI ID. The stack also creates an IAM role (execution role), which Lambda uses to make calls to Amazon EC2. 3. Delete the stack. (p. 446) Delete the stack to clean up all the stack resources that you created so that you aren't charged for unnecessary resources. API Version 2010-05-15 440 AWS CloudFormation User Guide AWS Lambda-backed Custom Resources Step 1: Downloading and Saving the Sample Package in Amazon S3 When you create a stack with a Lambda function, you must specify the location of the Amazon S3 bucket that contains the function's source code. The bucket must be in the same region in which you create your stack. This walkthrough provides a sample package (a .zip file) that's required to create the Lambda function. A Lambda package contains the source code for the function and required libraries. For this walkthrough, the function doesn't require additional libraries. The function takes an instance's architecture and region as inputs from an AWS CloudFormation custom resource request and returns the latest AMI ID to a pre-signed Amazon S3 URL. To download and save the package in Amazon S3 1. Download the sample package from Amazon S3. When you save the file, use the same file name as the sample, amilookup.zip or amilookup-win.zip. Look up Linux AMI IDs https://s3.amazonaws.com/cloudformation-examples/lambda/amilookup.zip Look up Windows AMI IDs https://s3.amazonaws.com/cloudformation-examples/lambda/amilookup-win.zip 2. Open the Amazon S3 console at https://console.aws.amazon.com/s3/home. 3. Choose or create a bucket that's located in the same region in which you'll create your AWS CloudFormation stack. Record the bucket name. You'll save the sample package in this bucket. For more information about creating a bucket, see Creating a Bucket in the Amazon Simple Storage Service Console User Guide. 4. Upload the sample package to the bucket that you chose or created. For more information about uploading objects, see Uploading Objects in the Amazon Simple Storage Service Console User Guide. With the package in Amazon S3, you can now specify its location in the Lambda resource declaration of the AWS CloudFormation template. The next step demonstrates how you declare the function and invoke it by using a custom resource. You'll also see how to use the results of the function to specify the AMI ID of an EC2 instance. Step 2: Creating the Stack To create the sample Amazon EC2 stack, you'll use a sample template that includes a Lambda function, an IAM execution role, a custom resource that invokes the function, and an EC2 instance that uses the results from the function. During stack creation, the custom resource invokes the Lambda function and waits until the function sends a response to the pre-signed Amazon S3 URL. In the response, the function returns the ID of the latest AMI that corresponds to the EC2 instance type and region in which you are creating the instance. The data from the function's response is stored as an attribute of the custom resource, which is used to specify the AMI ID of the EC2 instance. The following snippets explain relevant parts of the sample template to help you understand how to associate a Lambda function with a custom resource and how to use the function's response. To view the entire sample template, see: Linux template https://s3.amazonaws.com/cloudformation-examples/lambda/LambdaAMILookupSample.template API Version 2010-05-15 441 AWS CloudFormation User Guide AWS Lambda-backed Custom Resources Windows template https://s3.amazonaws.com/cloudformation-examples/lambda/LambdaAMILookupSamplewin.template Stack Template Snippets To create the Lambda function, you declare the AWS::Lambda::Function resource, which requires the function's source code, handler name, runtime environment, and execution role ARN. Example JSON Syntax "AMIInfoFunction": { "Type": "AWS::Lambda::Function", "Properties": { "Code": { "S3Bucket": { "Ref": "S3Bucket" }, "S3Key": { "Ref": "S3Key" } }, "Handler": { "Fn::Join" : [ "", [{ "Ref": "ModuleName" },".handler"] ] }, "Runtime": "nodejs4.3", "Timeout": "30", "Role": { "Fn::GetAtt" : ["LambdaExecutionRole", "Arn"] } } } Example YAML Syntax AMIInfoFunction: Type: AWS::Lambda::Function Properties: Code: S3Bucket: !Ref S3Bucket S3Key: !Ref S3Key Handler: !Sub "${ModuleName}.handler" Runtime: nodejs4.3 Timeout: 30 Role: !GetAtt LambdaExecutionRole.Arn The Code property specifies the Amazon S3 location (bucket name and file name) where you uploaded the sample package. The sample template uses input parameters ("Ref": "S3Bucket" and "Ref": "S3Key") to set the bucket and file names so that you are able to specify the names when you create the stack. Similarly, the handler name, which corresponds to the name of the source file (the JavaScript file) in the .zip package, also uses an input parameter ("Ref": "ModuleName"). Because the source file is JavaScript code, the runtime is specified as nodejs4.3. For this walkthrough, the execution time for the function exceeds the default value of 3 seconds, so the timeout is set to 30 seconds. If you don't specify a sufficiently long timeout, Lambda might cause a timeout before the function can complete, causing stack creation to fail. The execution role, which is declared elsewhere in the template, is specified by using the Fn::GetAtt intrinsic function in the Role property. The execution role grants the Lambda function permission to send logs to AWS and to call the EC2 DescribeImages API. The following snippet shows the role and policy that grant the appropriate permission: Example JSON Syntax "LambdaExecutionRole": { "Type": "AWS::IAM::Role", "Properties": { API Version 2010-05-15 442 AWS CloudFormation User Guide AWS Lambda-backed Custom Resources } } "AssumeRolePolicyDocument": { "Version": "2012-10-17", "Statement": [{ "Effect": "Allow", "Principal": {"Service": ["lambda.amazonaws.com"]}, "Action": ["sts:AssumeRole"] }] }, "Path": "/", "Policies": [{ "PolicyName": "root", "PolicyDocument": { "Version": "2012-10-17", "Statement": [{ "Effect": "Allow", "Action": ["logs:CreateLogGroup","logs:CreateLogStream","logs:PutLogEvents"], "Resource": "arn:aws:logs:*:*:*" }, { "Effect": "Allow", "Action": ["ec2:DescribeImages"], "Resource": "*" }] } }] Example YAML Syntax LambdaExecutionRole: Type: AWS::IAM::Role Properties: AssumeRolePolicyDocument: Version: '2012-10-17' Statement: - Effect: Allow Principal: Service: - lambda.amazonaws.com Action: - sts:AssumeRole Path: "/" Policies: - PolicyName: root PolicyDocument: Version: '2012-10-17' Statement: - Effect: Allow Action: - logs:CreateLogGroup - logs:CreateLogStream - logs:PutLogEvents Resource: arn:aws:logs:*:*:* - Effect: Allow Action: - ec2:DescribeImages Resource: "*" For both the Linux and Windows templates, the custom resource invokes the Lambda function that is associated with it. To associate a function with a custom resource, you specify the Amazon Resource Name (ARN) of the function for the Service