AMAZON WEB SERVICES CLOUDFORMATION GUIDE
Summary by Damian Ndunda © 2019
TABLE OF CONTENTS
AMAZON WEB SERVICES CLOUDFORMATION GUIDE. 1
AWS CLOUDFORMATION INTRODUCTION.. 5
AMAZON AND CLOUD COMPUTING.. 7
AWS CLOUDFORMATION CONCEPTS. 8
HOW DOES AWS CLOUDFORMATION WORK?. 14
UPDATING A STACK WITH CHANGE SETS. 15
Creating the VPC EndPoint for AWS CloudFormation. 16
AWS CLOUDFORMATION LIMITS TABLE. 18
GETTING STARTED WITH AWS CLOUDFORMATION.. 21
Step 2: Make sure you have prepared any required items for the stack. 25
Step 4: Monitor the progress of stack creation. 26
Step 5: Use your stack resources. 27
What is an AWS CloudFormation Template?. 28
Resource Properties and Using Resources Together. 29
Receiving User Input Using Input Parameters. 40
Specifying Conditional Values Using Mappings. 43
Constructed Values and Output Values. 47
WALKTHROUGH: UPDATING A STACK. 54
AWS CLOUDFORMATION
INTRODUCTION
AWS CloudFormation gives developers and systems administrators an easy way to create and manage a collection of related AWS resources, provisioning and updating them in an orderly and predictable fashion. One can use AWS CloudFormation’s sample templates or create their own templates to describe the AWS resources, and any associated dependencies or runtime parameters, required to run your application.
One can deploy and update a template and its associated collection of resources (called a stack) using the AWS Management Console, AWS CloudFormation command line tools, or CloudFormation API. AWS CloudFormation is available at no additional charge, and one pays only for the AWS resources needed to run their applications.
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.
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. 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. When you provision your infrastructure with AWS CloudFormation, the AWS CloudFormation template describes exactly what resources are provisioned and their settings.
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.
AWS CLOUDFORMATION CONCEPTS
When you use AWS CloudFormation, you work with templates and stacks.
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
Example JSON
{
"AWSTemplateFormatVersion" : "2010-09-09",
"Description" : "A sample template",
"Resources" : {
"MyEC2Instance" : {
"Type" : "AWS::EC2::Instance",
"Properties" : {
"ImageId" : "ami-0ff8a91507f77f867",
"InstanceType" : "t2.micro",
"KeyName" : "testkey",
"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-0ff8a91507f77f867"
InstanceType: t2.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-0ff8a91507f77f867",
"InstanceType" : "t2.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-0ff8a91507f77f867"
InstanceType: t2.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
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.
You can work with stacks by using the AWS CloudFormation console, API, or AWS CLI.
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 a 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.
HOW DOES AWS CLOUDFORMATION WORK?
The following diagram summarizes the AWS CloudFormation workflow for creating stacks.
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.
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, 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.
If stack creation fails, AWS CloudFormation rolls back your changes by deleting the resources that it created.
UPDATING A STACK WITH CHANGE SETS
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.
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.
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.
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 , if you're updating a resource that doesn't support updates, or if you have insufficient permissions 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.
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, 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 to retain those resources.
Creating the VPC EndPoint for AWS CloudFormation
To create the VPC endpoint for the AWS CloudFormation service, use the Creating an Interface Endpoint procedure in the Amazon VPC User Guide to create the following endpoint:
com.amazonaws.region.cloudformation
region represents the region identifier for an AWS region supported by AWS CloudFormation, such as us-east-2 for the US East (Ohio) Reg
BEFORE YOU BEGIN
Before you configure VPC endpoints for AWS CloudFormation, be aware of the following considerations.
• When using the VPC endpoint feature, grant access to AWS CloudFormation-specific S3 buckets for resources in a VPC that must respond to a custom resource request or a wait condition. 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. 482) request or a wait condition (p. 322). 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.
• VPC endpoints currently do not support cross-region requests—ensure that you create your endpoint in the same region in which you plan to issue your API calls to AWS CloudFormation.
• VPC endpoints only support Amazon-provided DNS through Route 53. If you want to use your own DNS, you can use conditional DNS forwarding. For more information, see DHCP Options Sets in the Amazon VPC User Guide.
•
The security group attached to the VPC endpoint must allow incoming connections
on port 443 from the private subnet of the VPC.
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 TABLE
Limit |
Description |
Value |
Tuning Strategy |
cfn-signal wait condition data (p. 3602) |
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 |
Maximum amount of data that a custom resource provider can pass. |
4,096 bytes |
|
Mappings |
Maximum number of mappings that you can declare in your AWS CloudFormation template. |
100 mappings |
To specify more mappings, separate your template into multiple templates by using, for example, nested stacks. |
Mapping attributes |
Maximum number of mapping attributesfor 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 |
Maximum size of each mapping name. |
255 characters |
|
Outputs |
Maximum number of outputs that you can declare in your AWS CloudFormation template. |
60 outputs |
|
Output name ( |
Maximum size of an output name. |
255 characters |
|
Parameters |
Maximum number of parameters that you can declare in your AWS CloudFormation template. |
60 parameters |
To specify more parameters, you can use mappings or lists in order to assign multiple values to a single parameter. |
Parameter name |
Maximum size of a parameter name. |
255 characters |
|
Parameter value |
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 |
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. |
Resources in concurrent stack operations |
Maximum number of resources you can have involved in stack operations (create, update, or delete operations) in your region at a given time. |
Use the DescribeAccountLimits API to determine the current limit for an account in a specific region. |
|
Resource name |
Maximum size of a resource name. |
255 characters |
|
Stacks |
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 |
Maximum number of AWS CloudFormation stack sets you can create in your administrator account. |
100 stack sets |
To create more stack sets, delete stack sets that you don't need or request an increase in the maximum number of stack sets in your AWS account. For more information, see AWS Service Limits in the AWS General Reference. |
Stack instances |
Maximum number of stack instances you can create per stack set. |
2000 stack instances per stack set |
To create more stack instances, delete stack instances that you don't need or request an increase in the maximum number of stack instances in your AWS account. For more information, see AWS Service Limits in the AWS General Reference. |
StackSets instance operations |
Maximum number of stack instance operations you can run in each region at the same time, per administrator account. |
3500 operations |
This limit applies per region, and is regardless of the number of stack sets involved. It includes stack instances affected by StackSet creation and update operations, as well as creating, updating, or deleting stack instances directly. |
Template body size in a request |
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. Or upload the template to an Amazon S3 bucket. |
Template body size in an Amazon S3 object |
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. |
Template description |
Maximum size of a template description. |
1,024 bytes |
|
Limit |
Description |
Value |
Tuning Strategy |
GETTING STARTED WITH AWS CLOUDFORMATION
In the following walkthrough, we'll use a sample template to launch, update, and delete a stack.
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.
GET STARTED
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.
Step 1: Pick a template
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.
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 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"}}
]
}
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'
...
Step 2: Make sure you have prepared any required items for the stack
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.
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.
Step 3: Create the stack
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.
Step 4: Monitor the progress of stack creation
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
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.
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
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.
Step 6: Clean Up
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.
LEARN TEMPLATE BASICS
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. The only required toplevel object is the Resources object, which must declare at least one resource.
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.
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
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.
To view the properties for each resource type, see the topics in AWS Resource and Property Types Reference
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 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.
The following template contains an AWS::EC2::Instance 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'
ToPort: '22'
CidrIp: 0.0.0.0/0
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
In the example above, the KeyName property of the AWS::EC2::Instance 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.
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
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
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. 3575) 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"
}
}
}
}
}
}
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. 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
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",
"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
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.
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).
If you set the NoEcho attribute to true, CloudFormation returns the parameter value masked as asterisks (*****) for any calls that describe the stack or stack events. 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.
Important
Rather than embedding sensitive information directly in your AWS CloudFormation templates, we strongly suggest you do one of the following:
• Use input parameters to pass in information whenever you create or update a stack, using the NoEcho property to obfuscate the parameter value.
• Use dynamic parameters in the stack template to reference sensitive information that is stored and managed outside of CloudFormation, such as in the Systems Manager Parameter Store or Secrets Manager.
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.
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"
}
}
},
"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. 3572) 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.
Tip
The AWS::Region pseudo parameter enables you to get the region where the stack is created.Some resources, such as AWS::EC2::Instance, AWS::AutoScaling::AutoScalingGroup, and AWS::ElasticLoadBalancing::LoadBalancer, have a property that specifies availability zones. You can use the Fn::GetAZs function (p. 3577) 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"
}
}
}
}
}
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"
]
]
},
"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
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 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
Optional attributes that can be used with any resource:
• DependsOn attribute (p. 3534) enables you to specify that one resource must be created after another.
• DeletionPolicy attribute (p. 3532) enables you to specify how AWS CloudFormation should handle the deletion of a resource.
• Metadata (p. 3539) attribute enables you to specify structured data with a resource. AWS::CloudFormation::Stack 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.
We will walk through the following steps:
1. Create the Initial Stack (p. 55)—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. 56)—update one of the files in the application and deploy the software using AWS CloudFormation.
3. Update the Instance Type (p. 58)—change the instance type of the underlying Amazon EC2 instance.
4. Update the AMI on an Amazon EC2 instance (p. 60)—change the Amazon Machine Image (AMI) forthe Amazon EC2 instance in your stack.
5. Add a Key Pair to an Instance (p. 62)—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. 62)—add and remove resources from the stack, converting it to an auto-scaled, load-balanced application by updating the template.
A Simple Application
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 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" : ["", [
"<?php\n",
"echo '<h1>AWS CloudFormation sample PHP application</h1>';\n",
"echo '<p>", { "Ref" : "WelcomeMessage" },
"</p>';\n",
"?>\n"
]]},
"mode" : "000644",
"owner" : "apache",
"group" : "apache"
},
},
:
"services" : {
"sysvinit" : {
"httpd" : { "enabled" : "true",
"ensureRunning" : "true" }
}
}
}
}
},
"Properties":
{
:
"UserData" : { "Fn::Base64" : { "Fn::Join" :
["", [
"#!/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",
:
]]}}
}
},
REFERENCES
Amazon Inc (2019) AWS CloudFormation: User Guide, Amazon Web Services, Inc.
Amazon Inc (2019) AWS Command Line Interface: User Guide, Amazon Web Services, Inc.
Home/ Info/ Products/ BIG TECH Metaverse Metaverse Vs. Virtual Reality PC Buyers Guide/ IEEE 802 Standards Social Media Platforms Technology Videos/ Computer & IT Certifications Processor Generations Memory DDR3 Vs. DDR4 SSD Vs. HDD SAS vs. SATA HTML 5G Android Tips and Tricks STEM Business Intelligence Tools Web Intelligence Quantum Computing Artificial Intelligence (AI) Robotics Internet of Things (IOT) Web Of Things (WoT) Renewable Energy Nano Technology Cleantech Windows Run Commands Hiren's Boot CD Android Vs. IOS Mac Vs. PC Mac Keyboard Shortcuts Linux CLi Commands Venus Project/ Computer Security and Law Techno Lingo Encyclopedias Search Engines Glossary Online Jobs Contact
Active Components Passive Components Test Electrical Components Electronics Classification
AWS Certification Google Certification Oracle Certifications cisco certifications Huawei Certification Microsoft Certifications Linux Certification Business Certifications
Google-Cloud-Platform-Guide Amazon-Web-Services-Guide Global-Cloud-Infrastructure-Of-AWS Amazon-Web-Services-Cli-Guide AWS-Cloudformation Devops Microsoft-Azure Oracle-Cloud Digitalocean-Cloud Openstack-Cloud IaC CloudFormation Anatomy Security Topics
Certified Enterprise Blockchain Professional (CEBP) Web 3.0 Satoshi Nakamoto Cryptocurrency Dark Web Ethereum NFT Merkle Tree El-Salvador eNaira Challenges Of Crypto To Cash
Web C++ JAVA Python Python Glossary Angular.js Scala
Copyright BICT Solutions Privacy Policy. | Terms and Conditions apply | All rights reserved.