This chapter covers AWS CloudFormation, a core Infrastructure as Code (IaC) service that enables you to model and provision AWS resources using templates. For the CLF-C02 exam, this objective falls under Domain 3: Cloud Technology Services, which carries approximately 24% of the exam weight. Understanding CloudFormation is crucial because it tests your knowledge of automated deployment, resource orchestration, and the benefits of IaC versus manual provisioning. You won't need to write templates on the exam, but you must understand what CloudFormation does, its key components (stacks, templates, change sets), and how it differs from other services like AWS Elastic Beanstalk and AWS OpsWorks.
Jump to a section
Imagine you're a construction manager tasked with building 100 identical houses. You could hire workers to build each house manually, measuring and cutting wood on-site, which is slow and error-prone. Alternatively, you create a detailed blueprint that specifies every nail, beam, and window. You hand that blueprint to a construction crew, and they build each house exactly the same way, every time. If you need to change the window size, you update the blueprint once, and all future houses use the new window. AWS CloudFormation is that blueprint for your cloud infrastructure. Instead of manually clicking through the AWS Management Console to create EC2 instances, security groups, and load balancers, you write a template (the blueprint) in JSON or YAML. CloudFormation reads that template and automatically provisions and configures all the resources in the correct order, handling dependencies and rollbacks on failure. Just as a blueprint ensures consistency across houses, CloudFormation ensures your infrastructure is reproducible, version-controlled, and auditable.
What is AWS CloudFormation and What Problem Does It Solve?
AWS CloudFormation is a service that allows you to define your entire AWS infrastructure as a text file (a template) and then provision it automatically. The problem it solves is the complexity and error-prone nature of manually creating and managing AWS resources. Without CloudFormation, administrators often use the AWS Management Console, CLI commands, or scripts to create resources one by one. This manual approach leads to configuration drift, inconsistent environments, and difficulty replicating infrastructure across regions or accounts. CloudFormation treats infrastructure as code, enabling version control, peer review, and automated deployments.
How It Works: The Mechanism
CloudFormation uses templates written in JSON or YAML. A template describes the AWS resources you want to create, their properties, and dependencies. When you submit a template, CloudFormation creates a "stack" — a collection of resources managed as a single unit. The service automatically determines the correct order to create, update, or delete resources based on dependencies. For example, if your template includes an EC2 instance and a security group that references it, CloudFormation creates the security group first.
Key components of a template: - AWSTemplateFormatVersion: (optional) Specifies the template format version. - Description: A text description of the template. - Parameters: Input values you supply at stack creation (e.g., instance type, key pair). - Mappings: Static lookup tables (e.g., mapping region to AMI ID). - Conditions: Conditions that control whether certain resources are created. - Resources: (Required) The AWS resources to create (e.g., EC2 instances, S3 buckets, IAM roles). - Outputs: Values returned after stack creation (e.g., the public IP of an EC2 instance).
Example snippet of a CloudFormation template (YAML):
AWSTemplateFormatVersion: '2010-09-09'
Description: A simple EC2 instance
Parameters:
InstanceType:
Type: String
Default: t2.micro
AllowedValues: [t2.micro, t2.small, t2.medium]
Resources:
MyEC2Instance:
Type: 'AWS::EC2::Instance'
Properties:
InstanceType: !Ref InstanceType
ImageId: ami-0abcdef1234567890
SecurityGroups:
- !Ref MySecurityGroup
MySecurityGroup:
Type: 'AWS::EC2::SecurityGroup'
Properties:
GroupDescription: Enable SSH access
SecurityGroupIngress:
- IpProtocol: tcp
FromPort: 22
ToPort: 22
CidrIp: 0.0.0.0/0
Outputs:
InstanceIP:
Description: Public IP of the instance
Value: !GetAtt MyEC2Instance.PublicIpWhen you create a stack, CloudFormation performs the following steps: 1. Validate the template syntax. 2. Check for circular dependencies. 3. Create resources in the correct order, waiting for each to complete before proceeding. 4. If any resource creation fails, CloudFormation rolls back the entire stack (by default), deleting any resources that were created successfully. This ensures you don't have orphaned resources.
Key Concepts: Stacks, Change Sets, and Stack Sets
Stack: A collection of AWS resources managed as a single unit. You can create, update, and delete stacks. Deleting a stack deletes all resources within it.
Change Set: Before updating a stack, you can create a change set to preview the changes CloudFormation will make. This allows you to see which resources will be added, modified, or deleted before applying the update.
Stack Set: A feature that allows you to create, update, or delete stacks across multiple accounts and regions with a single template. Stack sets use service-linked roles and are useful for multi-account governance.
Pricing
CloudFormation itself is free. You only pay for the AWS resources created (e.g., EC2 instances, S3 buckets). There is no additional charge for using CloudFormation. However, there are limits: you can have up to 200 stacks per region per account (soft limit, can be increased), and each template can be up to 51,200 bytes (50 KB) when using an S3 URL.
Comparison to On-Premises and Alternatives
In on-premises environments, infrastructure is typically provisioned manually or through scripts like Ansible, Chef, or Puppet. These tools are configuration management tools, not infrastructure provisioning tools. CloudFormation is specific to AWS and focuses on provisioning resources, not configuring software on those resources. For software configuration, you would use tools like AWS OpsWorks (which supports Chef/Puppet) or AWS Systems Manager. AWS Elastic Beanstalk is a higher-level service that automates deployment of applications but abstracts away the underlying infrastructure — you don't control individual resources directly. CloudFormation gives you fine-grained control.
When to Use CloudFormation vs Alternatives
Use CloudFormation when you need to provision and manage AWS resources in a repeatable, version-controlled manner. It's ideal for infrastructure-as-code, disaster recovery, and multi-environment deployments.
Use AWS Elastic Beanstalk when you want to quickly deploy web applications without managing the underlying infrastructure (e.g., EC2, load balancers, scaling). Beanstalk uses CloudFormation internally.
Use AWS OpsWorks when you need configuration management with Chef or Puppet, especially for existing on-premises workflows.
Use Terraform (third-party) if you need multi-cloud support or prefer HashiCorp's workflow.
On the CLF-C02 exam, you will be tested on the purpose of CloudFormation, its benefits (automation, consistency, rollback), and how it differs from Elastic Beanstalk and OpsWorks.
Write a CloudFormation Template
Begin by defining your infrastructure in a JSON or YAML template. You can write it from scratch or use the AWS CloudFormation Designer (a visual tool) to drag and drop resources. The template must include at least one resource under the Resources section. You can also define parameters to make the template reusable (e.g., accept environment name, instance type). AWS provides sample templates for common architectures like a web application with an ELB and Auto Scaling group. Ensure your template adheres to the CloudFormation schema; invalid templates will be rejected.
Create a Stack Using the Template
In the AWS Management Console, navigate to CloudFormation and choose 'Create Stack'. Upload your template file or paste it inline. Specify a stack name (unique within your account and region). Provide values for any parameters (e.g., instance type). Configure stack options like tags, IAM roles, and rollback behavior (default is to roll back on failure). CloudFormation will then validate the template and begin provisioning resources. You can monitor progress in the Events tab.
Monitor Stack Creation Events
As CloudFormation creates resources, it logs events in real-time. Each event shows the logical ID (from the template), physical ID (actual AWS resource ID), resource type, and status (e.g., CREATE_IN_PROGRESS, CREATE_COMPLETE, CREATE_FAILED). If a resource fails, CloudFormation triggers a rollback, and you'll see events for deleting resources. The stack status will become ROLLBACK_COMPLETE. You can view the error message to troubleshoot (e.g., insufficient permissions, invalid AMI ID).
Update the Stack with a Change Set
To update your infrastructure, modify the template (e.g., change instance type or add a new resource). Instead of applying directly, create a change set. The change set shows a summary of additions, modifications, and deletions. Review it carefully because some changes (like replacing an EC2 instance) cause downtime. Once you approve, CloudFormation executes the change set, updating resources in the correct order. You can also execute updates directly without a change set, but change sets are safer.
Delete the Stack to Clean Up
When you no longer need the infrastructure, delete the stack. CloudFormation will delete all resources that were created as part of the stack, in the correct order (e.g., delete security groups after EC2 instances). This prevents orphaned resources and reduces costs. You can also protect stacks from accidental deletion by enabling termination protection on the stack.
Scenario 1: Multi-Environment Web Application
A startup runs a web application with separate environments for development, testing, and production. They use CloudFormation templates to define the entire stack: VPC, public/private subnets, Auto Scaling group, Application Load Balancer, and RDS database. Each environment uses the same template but different parameter values (e.g., instance type t2.micro for dev, t2.medium for prod). This ensures environments are identical in configuration, reducing the 'it works on my machine' problem. The team stores templates in a Git repository, enabling code review and versioning. When a developer needs a new environment, they run a CloudFormation create-stack command. Cost is controlled because dev stacks use smaller instances and can be shut down overnight. A common mistake is forgetting to delete stacks, leading to unexpected charges; the team uses AWS Config rules to flag stacks running longer than 30 days.
Scenario 2: Disaster Recovery with Cross-Region Replication
A financial services company must maintain a disaster recovery (DR) environment in a different AWS region. They use CloudFormation Stack Sets to deploy the same infrastructure (EC2, RDS, Lambda) to both primary and DR regions from a single template. The template includes parameters for region-specific AMI IDs using Mappings. The DR stack is kept in a stopped state (e.g., RDS in standby, EC2 stopped) to minimize costs. In a disaster, they update the stack to start resources and change Route 53 failover. Without CloudFormation, manually recreating infrastructure in another region would take hours and risk configuration errors. The biggest risk is template drift — if someone manually modifies resources in the primary region, the template becomes out of sync. To mitigate this, they use AWS Config to detect changes and enforce that all changes go through CloudFormation.
Scenario 3: Compliance and Auditing
A healthcare company must comply with HIPAA. They use CloudFormation to enforce security baselines. Their templates always include encryption at rest for EBS volumes and RDS, restrict security group ingress to specific IPs, and enable CloudTrail logging. Any deviation from the template is flagged. They also use CloudFormation Guard (a policy-as-code tool) to validate templates before deployment. If a developer tries to create an unencrypted resource, the template is rejected. This approach ensures that all infrastructure is compliant from the start. A common pitfall is that CloudFormation does not automatically enforce compliance during updates — you must re-validate templates. Additionally, if a resource is created outside CloudFormation (e.g., via Console), it is not managed and may violate compliance.
What CLF-C02 Tests on This Objective
Domain 3 (Cloud Technology Services) includes the objective: "Identify the purposes of and relationships between AWS Cloud services." For CloudFormation, the exam tests your understanding of what CloudFormation is, its benefits (automation, consistency, rollback), and how it differs from other deployment services like Elastic Beanstalk and OpsWorks. You will NOT be asked to read or write CloudFormation templates. Instead, you need to know:
CloudFormation is an Infrastructure as Code (IaC) service.
It uses templates (JSON/YAML) to define resources.
A stack is a collection of resources created from a template.
Change sets allow you to preview changes before updating a stack.
CloudFormation handles dependencies and rollback automatically.
It is free; you only pay for the resources created.
Common Wrong Answers and Why
"CloudFormation is a configuration management tool like Chef." – Wrong. CloudFormation provisions infrastructure, not software configuration. Configuration management is done by OpsWorks or Systems Manager.
"CloudFormation can only be used through the AWS Management Console." – Wrong. It can be used via Console, CLI, SDKs, and even integrated into CI/CD pipelines.
"CloudFormation templates can only be written in JSON." – Wrong. Both JSON and YAML are supported.
"CloudFormation automatically backs up your data." – Wrong. CloudFormation does not handle backups; it only provisions resources. Use AWS Backup for backups.
Tricky Distinctions
CloudFormation vs Elastic Beanstalk: Elastic Beanstalk is a PaaS (Platform as a Service) that automates deployment of applications. It uses CloudFormation internally but abstracts the infrastructure. CloudFormation gives you full control over resources.
CloudFormation vs OpsWorks: OpsWorks is a configuration management service that uses Chef or Puppet. It works on existing infrastructure (EC2 instances). CloudFormation provisions the infrastructure itself.
CloudFormation vs Terraform: Terraform is a third-party IaC tool that supports multiple cloud providers. CloudFormation is AWS-native and integrates deeply with AWS services.
Decision Rule for Exam Questions
If a question asks about "automated provisioning of AWS resources using templates" or "infrastructure as code," the answer is CloudFormation. If it mentions "deploying a web application without managing servers," think Elastic Beanstalk. If it mentions "configuration management with Chef," think OpsWorks. For questions about "previewing changes before applying," think Change Sets.
CloudFormation is an Infrastructure as Code (IaC) service that provisions AWS resources using JSON/YAML templates.
A stack is a collection of resources created from a single template; deleting a stack deletes all resources in it.
Change sets allow you to preview changes before updating a stack, reducing risk of unintended modifications.
CloudFormation is free; you only pay for the underlying resources (EC2, S3, etc.).
Templates can include parameters, mappings, conditions, and outputs for flexibility and reuse.
CloudFormation automatically handles resource dependencies, creating resources in the correct order.
On failure, CloudFormation rolls back the stack by default, deleting any resources that were created.
CloudFormation differs from Elastic Beanstalk (PaaS) and OpsWorks (configuration management); each serves a distinct purpose.
Stack Sets enable deploying stacks across multiple accounts and regions from a single template.
The maximum template size is 51,200 bytes (50 KB) when using an S3 URL; larger templates must be uploaded to S3 first.
CloudFormation integrates with AWS CodePipeline, AWS Config, and other services for CI/CD and compliance.
Common exam scenario: use CloudFormation to replicate infrastructure across regions for disaster recovery.
These come up on the exam all the time. Here's how to tell them apart.
AWS CloudFormation
Infrastructure as Code service
You define all resources explicitly in a template
Full control over AWS resources (VPC, subnets, etc.)
Requires manual setup of application deployment
Suitable for complex, custom architectures
AWS Elastic Beanstalk
Platform as a Service (PaaS)
You deploy application code; infrastructure is abstracted
Limited control; Beanstalk manages resources automatically
Built-in application deployment and scaling
Best for standard web applications with minimal customization
Mistake
CloudFormation is a configuration management tool like Ansible or Chef.
Correct
CloudFormation is an infrastructure provisioning tool, not a configuration management tool. It creates AWS resources (EC2, RDS, etc.) but does not install software or configure operating systems. For configuration management, use AWS OpsWorks or Systems Manager.
Mistake
CloudFormation templates can only be written in JSON.
Correct
CloudFormation supports both JSON and YAML formats. You can choose either. YAML is often preferred for readability, but JSON is also widely used.
Mistake
CloudFormation is a paid service; you are charged per stack.
Correct
CloudFormation itself is free. You only pay for the AWS resources that CloudFormation creates (e.g., EC2 instances, S3 buckets). There is no additional charge for using CloudFormation.
Mistake
CloudFormation can only be used via the AWS Management Console.
Correct
CloudFormation can be accessed via the AWS Management Console, AWS CLI, AWS SDKs, and through AWS CloudFormation API. It can be integrated into CI/CD pipelines using tools like AWS CodePipeline.
Mistake
CloudFormation automatically handles backups of your data.
Correct
CloudFormation does not manage backups. It provisions resources like EC2 instances and RDS databases, but you must configure backups separately (e.g., using AWS Backup or automated snapshots).
CloudFormation is an Infrastructure as Code (IaC) service that gives you granular control over every AWS resource in your stack. You define resources like EC2, VPC, and RDS explicitly in a template. Elastic Beanstalk is a Platform as a Service (PaaS) that automates the deployment of applications. You just upload your code, and Beanstalk handles provisioning of resources like load balancers and Auto Scaling groups automatically. Beanstalk uses CloudFormation internally but abstracts it away. For the exam, remember: CloudFormation = infrastructure control; Elastic Beanstalk = quick app deployment.
Yes, AWS CloudFormation itself is free of charge. You only pay for the AWS resources that CloudFormation creates, such as EC2 instances, S3 buckets, or RDS databases. There are no additional fees for using CloudFormation. However, be mindful of the resources you provision; if you forget to delete a stack, you'll continue to incur charges for those resources.
By default, CloudFormation performs a rollback. If any resource fails to create, CloudFormation automatically deletes all resources that were successfully created during that stack operation. This ensures you don't have orphaned resources. You can disable rollback by setting the 'DisableRollback' option to true, but this is not recommended because it leaves partial infrastructure. The stack status will show 'ROLLBACK_COMPLETE' or 'ROLLBACK_FAILED' if the rollback itself fails.
No, CloudFormation only manages resources that were created as part of a stack. Resources created manually or via other tools are not tracked or managed by CloudFormation. However, you can import existing resources into a CloudFormation stack using the 'resource import' feature, which allows you to bring existing resources under CloudFormation management without recreating them.
Stack Sets extend the functionality of stacks by allowing you to create, update, or delete stacks across multiple accounts and regions with a single template. This is useful for organizations that need consistent infrastructure across their organization, such as deploying a baseline VPC in all accounts. Stack Sets use service-managed permissions or self-managed permissions and require appropriate IAM roles.
The maximum size for a CloudFormation template is 51,200 bytes (50 KB) when you upload it directly to the CloudFormation service. If your template exceeds this limit, you must upload it to an S3 bucket and provide the S3 URL to CloudFormation. There is no size limit when using an S3 URL, but the template must be valid JSON or YAML.
CloudFormation automatically determines the order of resource creation, update, and deletion based on dependencies. For example, if an EC2 instance references a security group, CloudFormation creates the security group first. You can also explicitly add a 'DependsOn' attribute to a resource to specify a dependency that CloudFormation might not automatically detect. This ensures resources are created in the correct order.
You've just covered AWS CloudFormation — now see how well it sticks with free CLF-C02 practice questions. Full explanations included, no account needed.
Done with this chapter?