AWS - CloudFormation
Learn how to declare AWS infrastructure as code with CloudFormation
Translated by Claude Opus 4.5
AI-generated content may be inaccurate or misleading.
Theory
What is CloudFormation?
CloudFormation is a way to declare AWS infrastructure as code. You can create or delete AWS infrastructure resources that have been predefined in code. A similar service is Terraform, and these are collectively called IaC (Infrastructure as Code).
Template
A file that defines infrastructure resources to be created in code. JSON and YAML formats can be used.
Creation Order
- Upload the template to CloudFormation
- Execute the stack creation command in CloudFormation
- AWS automatically creates resources in the order written in the template
Deletion Order
- Execute the stack deletion command in CloudFormation
- AWS automatically deletes the infrastructure resources
Hands-on Lab
Stack Creation
Parameters:
KeyName:
Description: Name of an existing EC2 KeyPair to enable SSH access to the instances. Linked to AWS Parameter
Type: AWS::EC2::KeyPair::KeyName
ConstraintDescription: must be the name of an existing EC2 KeyPair.
LatestAmiId:
Description: (DO NOT CHANGE)
Type: "AWS::SSM::Parameter::Value<AWS::EC2::Image::Id>"
Default: "/aws/service/ami-amazon-linux-latest/amzn2-ami-hvm-x86_64-gp2"
AllowedValues:
- /aws/service/ami-amazon-linux-latest/amzn2-ami-hvm-x86_64-gp2
Resources:
MyInstance:
Type: AWS::EC2::Instance
Properties:
ImageId: !Ref LatestAmiId
InstanceType: t2.micro
KeyName: !Ref KeyName
Tags:
- Key: Name
Value: WebServer
SecurityGroups:
- !Ref MySG
UserData:
Fn::Base64: !Sub |
#!/bin/bash
yum install httpd -y
systemctl start httpd && systemctl enable httpd
echo "<h1>Test Web Server</h1>" > /var/www/html/index.html
MySG:
Type: AWS::EC2::SecurityGroup
Properties:
GroupDescription: Enable HTTP access via port 80 and SSH access via port 22
SecurityGroupIngress:
- IpProtocol: tcp
FromPort: 80
ToPort: 80
CidrIp: 0.0.0.0/0
- IpProtocol: tcp
FromPort: 22
ToPort: 22
CidrIp: 0.0.0.0/0Save the above code as test_lab1.yaml and proceed with the following steps
- Access the CloudFormation Console and click Create stack
- Select Prepared template -> Upload a template file
- Specify an arbitrary stack name (CF-TEST)
- KeyName: Select the key pair you are using
Verify Created Resources
- Access the EC2 Console
- Instances -> Instances
- Check the WebServer instance IP
- Verify SSH and HTTP access
Stack Deletion
- Access the CloudFormation Console
- Stacks tab
- Select the created stack (CF-TEST)
- Click Delete
Verify Deleted Resources
- Access the EC2 Console
- Instances -> Instances
- Check the WebServer instance status (Terminated)
Published:
Modified: