Mastering CloudFormation Templates
Introduction to Json:
JSON is a human-readable format for storing and transmitting data.
Basic structure:
In Json Each property will be separated by comma …..
Example:
{
"key": value
}
Example:
Json with Array :
to write Json with Array we use []… that represents list of objects .
- here student array contains ……>strings
- Grades array contains ………> numbers .
Nested Json :
In below Example students is the nested object .
Nested JSON Objects: JSON objects within other JSON objects.
- The
school
object contains nested objects foraddress
andstudents
. - The
students
array contains objects representing individual students. - Each student object contains another nested object for
grades
.
CloudFormation:
Make sure to install the below plugin in your visual studio code for auto code .
Aws CloudFormation is a service in aws to manage aws infrastructure .
Just create a new file and write “start” and hit enter you will see below template
View of a AWS CloudFormation Template:
for creating a resource we can use resource block .
lets create a vpc .
to create a resource just type resource name in resource block .for example to create a resource vpc . i will just type VPC
as shown in below we need to give the name for resource for example “DevVPC” and give a CIDR Block
How to add tags for this resource?
in order to add tag just type tags under tags block it will add tags automatically and we can change as we needed .
Parameters:
Parameters enable you to input custom values to your template each time you create or update a stack.
to add a parameter just type parameter in parameter block
we will get a parameter section like this as below .
lets create a instance of type t2.micro.
here we are giving default value as t2.medium .
the advantage of allowing parameters property will help us to select the instance type that we want while creating the stack.
defining a DBpassword .
if we dont want to show a password type by user we have a property “NoEcho” we are set to true with other properties of parameter with min and max values .
CloudFormation Template Using AWS Secrets Manager
Explanation:
!Sub
(Substitution Function)
The !Sub
function replaces variables in the string with their actual values at runtime.
- In this case,
${SecretName}
is replaced with the actual parameter value (MySecurePassword
).
{{resolve:secretsmanager:${SecretName}:SecretString}}
- This is an intrinsic function that fetches a secret value from AWS Secrets Manager at runtime.
${SecretName}
resolves to"MySecurePassword"
, which was set in theParameters
section.SecretString
fetches the actual password or secret stored under"MySecurePassword"
.
How it Works in CloudFormation:
- During stack deployment, AWS retrieves the secret from Secrets Manager.
- The value of the secret (e.g.,
"65276587325872"
) is substituted in place of{{resolve:secretsmanager:${SecretName}:SecretString}}
. - The final resolved value is used for
KeyName
, or any other property where it's referenced.
this is for key pair .
How to Handle Passwords Securely?
Instead of KeyName
, using resolve:secretsmanager
makes sense for database passwords, API keys, or credentials, like this:
Steps to Securely Use RDS Passwords in CloudFormation
Store the RDS Credentials in AWS Secrets Manager.
Now, use CloudFormation to create the RDS database, fetching credentials securely:
How This Works
- AWS Secrets Manager securely stores credentials.
- CloudFormation dynamically fetches:
username
:"admin"
password
:"SuperSecureP@ssw0rd
Credentials are never exposed in the CloudFormation stack or logs.
Syntax of resolve
The general syntax for resolve
in AWS CloudFormation.
{{resolve:service-name:resource-name:attribute}}
service-name
→ The AWS service where the value is stored (e.g.,secretsmanager
,ssm
).resource-name
→ The name or ARN of the resource (e.g.,MyDBSecret
).attribute
→ The specific key or value to retrieve (e.g.,SecretString:password
).
When to Use resolve
?
✅ Fetching secrets securely from AWS Secrets Manager
✅ Fetching parameters from AWS SSM Parameter Store
✅ Keeping sensitive values hidden in CloudFormation logs
✅ Avoiding hardcoding passwords in templates
What is !Sub
in CloudFormation?
!Sub
(short for "Substitute") is a CloudFormation intrinsic function used for string interpolation—meaning it replaces variables within a string at runtime.
It is commonly used to construct dynamic values by combining text and parameter, resource, or function references.
Referencing parameters :
instead of hardcoding value in resource we can refer the value in a resource section through parameters with “ref” function.
previously we have given 10.0.0.0/24 cidr for the vpc now we are giving 10.0.0.0/16 means when we launch the staack it just updates the values it wont recreate it again.
Mappings :
Mappings in AWS CloudFormation are used to create simple “lookup tables” for different sets of key-value pairs.
Findinmap() function :
- first argument is mapping name .
- second argument is parameter name .
- third is value of the mapping .
Example 1: Region-Specific AMI IDs
Explanation for { “Ref”: “AWS::Region” }
- Intrinsic Function: The
Ref
intrinsic function is used to refer to parameters, resources, or pseudo parameters in a CloudFormation template. - Pseudo Parameter:
AWS::Region
is a pseudo parameter provided by CloudFormation. It returns the AWS region where the stack is being deployed.
Fn::FindInMap
takes three arguments:
- The name of the mapping:
"RegionMap"
. - The first key, which is dynamically set by
{ "Ref": "AWS::Region" }
to the current AWS region. - The second key, which is the specific attribute we want from the mapping:
"AMI"
.
Example2:
This example demonstrates how to use mappings for environment-specific settings such as configurations for Development
, Staging
, and Production
.
- Mappings Section:
RegionMap
defines different AMI IDs for different regions.EnvironmentConfig
defines instance types and counts for different environments.
Using Mappings:
Fn::FindInMap
is used to fetch the appropriate value from the mappings.- In
MyEC2Instance
, the AMI ID is dynamically set based on the region. - In
MyAutoScalingGroup
, the instance type and count are set based on the specified environment. - Parameters:
- The
Environment
parameter allows the user to select the environment type (Development, Staging, Production)
Example2 :
Environment-Based Configuration
Explanation: Uses the EnvType
parameter to determine instance type and SSH key.
Example 3:
Pricing Tier Configuration
Explanation: Uses Tier
to determine the EBS volume size.
outputs:
outputs section helps us to view output of a resource elements like instance id , vpcid .
Example:
we can break a stack as layers like vpc layer , network layer , infra layer for this we can go for cross stack .
Example 2 for outputs :
Explanation:
${AWS::StackName}
dynamically inserts the stack name.
Example3 :
we can use FN:: sub in properties also
Using Fn::Sub
to Format an S3 Bucket Name
Generates an S3 bucket name using the AWS Account ID and Region.
Cross Stacks:
the function “sub” will give us the reference to another stack.
Stack 1: Resource Stack
This stack defines an S3 bucket. We’ll export the bucket name so it can be used in another stack.
The Export
section in the CloudFormation template's Outputs
section is used to make the value available for other stacks to import. When you specify an export, you're giving the output a unique name that other stacks can reference.
Example:
Export:
- Name: The unique name for this export (
"MyS3BucketName"
). This name can be used by other CloudFormation stacks to import the value.
Example:
Stack 2: Reference Stack :
This stack references the S3 bucket defined in Stack 1 and uses its name, for example, in an S3 bucket policy.
Import the Export: In another stack (e.g., stack2.json
), you can import this value using the Fn::ImportValue
intrinsic function.
Example:
By using the Export
and Fn::ImportValue
, you can share resources and values across multiple CloudFormation stacks, enabling modular and reusable infrastructure as code.
Key Rules for Export
- Exports must be in the
Outputs
section. - Export names must be unique within a region per AWS account.
- An exported value cannot be updated unless it is first removed from dependent stacks.
- You cannot delete a stack that exports values if another stack is still importing them.
Conditions:
Conditions in AWS CloudFormation templates allow you to create resources only when certain conditions are true. Here are some simple examples of how to use conditions in CloudFormation templates using JSON.
Example 1: Basic Condition
This example shows how to use a condition to create a resource only if the environment is production.
Example2:
Using Fn::Or
with Conditions:
This example shows how to create a resource if the environment is either production or development.
these info is enough for writing the cloudFormation Templates .