Introduction
Until some point of time, there were very few questions asked from Cloudformation templates. Especially in AWS Solution Architect Associate, mostly asked question was “what cost will be incurred by using Cloudformation template”.for other AWS exams like Sysops admin and Developer, there will some more questions.
But now, I noticed that many tricky questions are coming from Cloudformation template. If I remember, in AWS SAA there were more than one question on Cloudformation template.
Its good news that we are getting questions from Cloudformation Template. Its , Indeed, Automation tool. if we start using Cloudformation template, this will make our job easy also get smart in Cloudformation template. But for some people, mostly many of us started using AWS with terraform and other infrastructure provisioning tools and started feeling comfortable.
The best way to learn any AWS concepts is start using them. For example, using AWS services like Redshift , Kenisis needs more work in terms of resource, preparation and time. But Cloudformation template can be used by everyone in most easy way. AWS certified aspriants can start using Cloudformation template for practices like crate EC2, SG, S3 bucket, VPC & Subnet etc.
There are many online documentation available on Cloudformation template online. AWS documentation has lots of articles and blogs on Cloudformation template and its new features. Hence I would like to restrict this page to specify only those points that are potentially possible to come in exams. also, note that in exam one may see more questions than what I mentioned in this page 🙂
Cloudformation template resource attributes
There are 6 resource attributes
- CreationPolicy Attribute
- DeletionPolicy Attribute
- DependsOn Attribute
- Metadata Attribute
- UpdatePolicy Attribute
- UpdateReplacePolicy Attribute
CreationPolicy Attribute
Associate the CreationPolicy
attribute with a resource to prevent its status from reaching create complete until AWS CloudFormation receives a specified number of success signals or the timeout period is exceeded. To signal a resource, user can use the cfn-signal helper script or SignalResource
API. AWS CloudFormation publishes valid signals to the stack events so that you track the number of signals sent.Use the CreationPolicy
attribute when user wants to wait on resource configuration actions before stack creation proceeds
DeletionPolicy Attribute
This attribute needs to be specified if user wants to retain resource while deleting a stack. Note that this capability also applies to stack update operations that lead to resources being deleted from stacks.Retain
property needs to be specified in Cloudformation template if a resource needs to be retained.
To keep certain resources when you delete a stack, use the DeletionPolicy attribute in your AWS CloudFormation template.
When you delete a stack, specify the Retain, Snapshot, or Delete policy option:
- The Retain option keeps the resource in the event of a stack deletion.
- The Snapshot option creates a snapshot of the resource before that resource is deleted.
Note: This option is available only for resources that support snapshots. they are AWS::EC2::Volume,AWS::ElastiCache::CacheCluster,AWS::ElastiCache::ReplicationGroup,AWS::Neptune::DBCluster,AWS::RDS::DBCluster,AWS::RDS::DBInstance,AWS::Redshift::Cluster - The Delete option deletes the resource along with the stack.
Note: This option is the default outcome if you don’t set a DeletionPolicy.
{
"AWSTemplateFormatVersion" : "2010-09-09",
"Resources" : {
"myS3Bucket" : {
"Type" : "AWS::S3::Bucket",
"DeletionPolicy" : "Retain"
}
}
}
DependsOn Attribute
Use this attribute if a resource needs to be installed in a sequence. for example, create RDS followed by EC2
Metadata Attribute
The Metadata attribute enables to associate structured data with a resource. later this can be retrived by describe-stack-resource
UpdatePolicy Attribute
UpdatePolicy can be used to specify how AWS CloudFormation handles updates to the following handles
- AWS::AutoScaling::AutoScalingGroup
- For AWS::AutoScaling::AutoScalingGroup resources, AWS CloudFormation invokes one of three update policies depending on the type of change you make or whether a scheduled action is associated with the Auto Scaling group.
- The
AutoScalingReplacingUpdate
andAutoScalingRollingUpdate
policies apply only when you do one or more of the following:- Change the Auto Scaling group’s
AWS::AutoScaling::LaunchConfiguration
. - Change the Auto Scaling group’s
VPCZoneIdentifier
property - Change the Auto Scaling group’s
LaunchTemplate
property - Update an Auto Scaling group that contains instances that don’t match the current
LaunchConfiguration
.
- Change the Auto Scaling group’s
- If both the
AutoScalingReplacingUpdate
andAutoScalingRollingUpdate
policies are specified, setting theWillReplace
property totrue
givesAutoScalingReplacingUpdate
precedence. - The
AutoScalingScheduledAction
policy applies when you update a stack that includes an Auto Scaling group with an associated scheduled action.
- The
- For AWS::AutoScaling::AutoScalingGroup resources, AWS CloudFormation invokes one of three update policies depending on the type of change you make or whether a scheduled action is associated with the Auto Scaling group.
- AWS::ElastiCache::ReplicationGroup
- For
AWS::ElastiCache::ReplicationGroup
resources, AWS CloudFormation can modify a replication group’s shards by adding or removing shards, rather than replacing the entire resource.
- For
- AWS::Elasticsearch::Domain
- For
AWS::Elasticsearch::Domain
resources, AWS CloudFormation can upgrade an Amazon ES domain to a new version of Elasticsearch without replacing the entire resource.
- For
- AWS::Lambda::Alias resources.
- For
AWS::Lambda::Alias
resources, AWS CloudFormation performs an CodeDeploy deployment when the version changes on the alias.
- For
UpdateReplacePolicy Attribute
Use the UpdateReplacePolicy attribute to retain or (in some cases) backup the existing physical instance of a resource when it is replaced during a stack update operation.UpdateReplacePolicy differs from the DeletionPolicy attribute in that it only applies to resources replaced during stack updates. Use DeletionPolicy for resources deleted when a stack is deleted, or when the resource definition itself is deleted from the template as part of a stack update.You can apply the UpdateReplacePolicy attribute to any resource.
The UpdateReplacePolicy attribute applies to stack updates you perform directly, as well as stack updates performed using change sets.
The following snippet contains an Amazon RDS database instance resource with a Retain
policy for replacement. When this resource is replaced with a new resource with a new physical ID, AWS CloudFormation leaves the old database instance without deleting it.
{
"AWSTemplateFormatVersion" : "2010-09-09",
"Resources" : {
"myDB" : {
"Type" : "AWS::RDS::DBInstance",
"DeletionPolicy" : "Retain",
"UpdateReplacePolicy" : "Retain",
"Properties" : {}
}
}
}
Cloudformation template for Latest AMI
If latest AMI needs to be fetched while executing stack, there are many ways to achive. one may create Lambda script to fetch AMI and output to Cloudformation template. https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/walkthrough-custom-resources-lambda-lookup-amiids.html
user can also query SSM for latest AMI. refer https://aws.amazon.com/blogs/mt/query-for-the-latest-windows-ami-using-systems-manager-parameter-store/
CloudFormation Helper Scripts Reference
AWS CloudFormation provides the following Python helper scripts that you can use to install software and start services on an Amazon EC2 instance that you create as part of your stack:
- cfn-init: Use to retrieve and interpret resource metadata, install packages, create files, and start services.
cfn-init
helper script is mainly used to read template metadata from theAWS::CloudFormation::Init
key. Although this can be used to install software packages in the EC2 instance, you still need to use thecfn-signal
helper script to indicate whether the Amazon EC2 instance and the 3rd party package have been successfully created. - cfn-signal: Use to signal with a CreationPolicy or WaitCondition, so you can synchronize other resources in the stack when the prerequisite resource or application is ready. The cfn-signal helper script signals AWS CloudFormation to indicate whether Amazon EC2 instances have been successfully created or updated. If you install and configure software applications on instances, you can signal AWS CloudFormation when those software applications are ready.You use the cfn-signal script in conjunction with a CreationPolicy or an Auto Scaling group with a WaitOnResourceSignals update policy. When AWS CloudFormation creates or updates resources with those policies, it suspends work on the stack until the resource receives the requisite number of signals or until the timeout period is exceeded. For each valid signal that AWS CloudFormation receives, AWS CloudFormation publishes the signals to the stack events so that you track each signal.
- cfn-get-metadata: Use to retrieve metadata for a resource or path to a specific key.
- cfn-hup: Use to check for updates to metadata and execute custom hooks when changes are detected.
- Refer https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/cfn-helper-scripts-reference.html for more details
A common usage pattern is to use cfn-init and cfn-signal together. The cfn-signal call uses the return status of the call to cfn-init (using the $? shell construct). If the application fails to install, the instance will fail to create and the stack will rollback.
{
"AWSTemplateFormatVersion": "2010-09-09",
"Description": "Simple EC2 instance",
"Resources": {
"MyInstance": {
"Type": "AWS::EC2::Instance",
"Metadata": {
"AWS::CloudFormation::Init": {
"config": {
"files": {
"/tmp/test.txt": {
"content": "Hello world!",
"mode": "000755",
"owner": "root",
"group": "root"
}
}
}
}
},
"Properties": {
"ImageId": "ami-a4c7edb2",
"InstanceType": "t2.micro",
"UserData": {
"Fn::Base64": {
"Fn::Join": [
"",
[
"#!/bin/bash -x\n",
"# Install the files and packages from the metadata\n",
"/opt/aws/bin/cfn-init -v ",
" --stack ",
{
"Ref": "AWS::StackName"
},
" --resource MyInstance ",
" --region ",
{
"Ref": "AWS::Region"
},
"\n",
"# Signal the status from cfn-init\n",
"/opt/aws/bin/cfn-signal -e $? ",
" --stack ",
{
"Ref": "AWS::StackName"
},
" --resource MyInstance ",
" --region ",
{
"Ref": "AWS::Region"
},
"\n"
]
]
}
}
},
"CreationPolicy": {
"ResourceSignal": {
"Timeout": "PT5M"
}
}
}
}
}