AWS Certified Cloud Practitioner
Post 21 of 25
84%
Complete
AWS Cloud Practitioner #21: CloudFormation - Infrastructure as Code
Aprende CloudFormation: templates, stacks, automatización de infrastructure y beneficios de IaC.
🎯 Lo que Aprenderás Hoy
- Explicar Infrastructure as Code (IaC)
- Comprender CloudFormation templates y stacks
- Identificar beneficios de automatización
- Comparar manual vs. IaC deployment
¿Qué es Infrastructure as Code?
IaC: Gestionar infrastructure usando código (no clicks en console).
Manual (Console):
1. Login a AWS Console
2. Click "Launch Instance"
3. Select AMI, instance type, network, storage
4. Configure security groups
5. Review and launch
6. Repeat para cada environment (dev, staging, prod)
IaC (CloudFormation):
1. Write template (código)
2. aws cloudformation create-stack
3. AWS crea todos los resources automáticamente
4. Reuse template para dev, staging, prodAWS CloudFormation
¿Qué es? Servicio para provisionar AWS resources usando templates.
Template (YAML/JSON):
Define qué resources crear
(EC2, VPC, RDS, S3, etc.)
Stack:
Collection of resources creados desde template
Benefits:
✅ Repeatable (deploy mismo ambiente multiple veces)
✅ Version control (templates en Git)
✅ Rollback automático (si error)
✅ Free (solo pagas por resources creados)Template Anatomy
# CloudFormation template (YAML)
AWSTemplateFormatVersion: '2010-09-09'
Description: 'Web application infrastructure'
Parameters:
InstanceType:
Type: String
Default: t2.micro
AllowedValues: [t2.micro, t2.small, t2.medium]
Description: EC2 instance type
Resources:
# VPC
MyVPC:
Type: AWS::EC2::VPC
Properties:
CidrBlock: 10.0.0.0/16
EnableDnsHostnames: true
Tags:
- Key: Name
Value: MyVPC
# Subnet
PublicSubnet:
Type: AWS::EC2::Subnet
Properties:
VpcId: !Ref MyVPC
CidrBlock: 10.0.1.0/24
MapPublicIpOnLaunch: true
# Security Group
WebServerSG:
Type: AWS::EC2::SecurityGroup
Properties:
GroupDescription: Allow HTTP
VpcId: !Ref MyVPC
SecurityGroupIngress:
- IpProtocol: tcp
FromPort: 80
ToPort: 80
CidrIp: 0.0.0.0/0
# EC2 Instance
WebServer:
Type: AWS::EC2::Instance
Properties:
ImageId: ami-0c55b159cbfafe1f0
InstanceType: !Ref InstanceType
SubnetId: !Ref PublicSubnet
SecurityGroupIds:
- !Ref WebServerSG
UserData:
Fn::Base64: |
#!/bin/bash
yum update -y
yum install -y httpd
systemctl start httpd
Outputs:
WebServerPublicIP:
Description: Public IP of web server
Value: !GetAtt WebServer.PublicIp
Export:
Name: WebServerIPTemplate Sections
1. Parameters:
User inputs (instance type, key name, etc.)
2. Resources (REQUIRED):
AWS resources to create
EC2, VPC, RDS, S3, etc.
3. Outputs:
Values to export
IP addresses, ARNs, etc.
4. Mappings:
Key-value lookup
Example: AMI ID por region
5. Conditions:
Conditional resource creation
Example: Create load balancer solo si prod
6. Metadata:
Additional info sobre templateCreating Stack
# Deploy stack
aws cloudformation create-stack \
--stack-name my-web-app \
--template-body file://template.yaml \
--parameters ParameterKey=InstanceType,ParameterValue=t2.micro
# Check status
aws cloudformation describe-stacks \
--stack-name my-web-app
# Output:
{
"StackStatus": "CREATE_IN_PROGRESS"
# Later: "CREATE_COMPLETE"
}
# Get outputs
aws cloudformation describe-stacks \
--stack-name my-web-app \
--query 'Stacks[0].Outputs'
# Output:
[{
"OutputKey": "WebServerPublicIP",
"OutputValue": "54.123.45.67"
}]Stack Updates
Change template → Update stack
Example:
Change InstanceType: t2.micro → t2.small
Update:
aws cloudformation update-stack \
--stack-name my-web-app \
--template-body file://template-updated.yaml
CloudFormation:
1. Compares current vs. new template
2. Determines changes needed
3. Creates change set
4. Executes changes
5. Rollback si falla
Types of updates:
- No interruption: Metadata change
- Some interruption: Property change (restart)
- Replacement: New resource created, old deletedStack Deletion
# Delete stack
aws cloudformation delete-stack \
--stack-name my-web-app
# All resources deleted automáticamente:
- EC2 instance terminated
- Security group deleted
- Subnet deleted
- VPC deleted
# Order matters:
CloudFormation deletes en orden correcto
(Dependencies handled automatically)
Protection:
Enable termination protection:
aws cloudformation update-termination-protection \
--stack-name my-web-app \
--enable-termination-protection
Cannot delete until protection disabledBenefits of IaC
1. Consistency:
Manual: Cada deploy diferente (human error)
IaC: Mismo template = mismo resultado
2. Speed:
Manual: 1 hora para setup VPC, subnets, instances
IaC: 5 minutos (automated)
3. Version Control:
Templates en Git
Track changes, rollback, code review
4. Documentation:
Template ES la documentation
Shows exactly qué está deployed
5. Disaster Recovery:
Infrastructure destroyed → Redeploy template
Back online en minutos
6. Multi-Environment:
Dev, staging, prod: Same template, different parameters
7. Cost Tracking:
Tags automáticos por stack
Easy cost allocation
8. Rollback:
Update fails → Automatic rollback
Prev known-good stateBest Practices
1. Use version control:
Templates en Git
Branching strategy
2. Parameterize:
Don't hardcode values
Use Parameters para flexibility
3. Modular templates:
Separate templates:
- network.yaml (VPC, subnets)
- compute.yaml (EC2, ASG)
- database.yaml (RDS)
Use nested stacks o cross-stack references
4. Naming conventions:
Consistent resource names
Include environment (prod-vpc, dev-vpc)
5. Use outputs:
Export values para otros stacks
!ImportValue en otros templates
6. DeletionPolicy:
Protect critical resources
DeletionPolicy: Retain (don't delete RDS)
7. Test:
Test templates en dev antes de prod
Use change sets (preview changes)
8. Documentation:
Comment templates
README explaining purposeCloudFormation vs. Terraform
| Aspecto | CloudFormation | Terraform |
|---|---|---|
| Provider | AWS only | Multi-cloud |
| Language | JSON/YAML | HCL |
| State | AWS managed | Local/Remote (S3) |
| Cost | Free | Free (Open Source) |
| Learning | Easier para AWS | Steeper learning curve |
Use CloudFormation when:
✅ AWS only
✅ Want AWS-native solution
✅ Free tier important
Use Terraform when:
✅ Multi-cloud (AWS + Azure + GCP)
✅ More mature tooling
✅ Larger community📝 Preparación para el Examen
Puntos Clave
CloudFormation:
- 📌 IaC: Infrastructure as code
- 📌 Template: YAML/JSON defining resources
- 📌 Stack: Collection of resources
- 📌 Free: Only pay for resources created
Benefits:
- 📌 Repeatable: Same template = same result
- 📌 Version control: Templates en Git
- 📌 Automated rollback: If update fails
- 📌 Multi-environment: Reuse templates
Template:
- 📌 Resources: Required section
- 📌 Parameters: User inputs
- 📌 Outputs: Export values
Preguntas de Práctica
Pregunta 1:
¿Qué es un Stack en CloudFormation?
A) Collection of templates B) Collection of resources created from template C) CloudFormation pricing tier D) Stack overflow error
Respuesta: B) Collection of resources created from template
Stack = group of AWS resources provisioned from CloudFormation template.
Pregunta 2:
¿Qué formato soporta CloudFormation templates?
A) Solo JSON B) Solo YAML C) JSON o YAML D) XML
Respuesta: C) JSON o YAML
CloudFormation soporta ambos JSON y YAML para templates. YAML es más común (más legible).
🎓 Resumen
- IaC: Infrastructure as code (automation)
- CloudFormation: AWS service para IaC
- Template: Define resources (YAML/JSON)
- Stack: Resources created from template
- Benefits: Repeatable, versionable, rollback
⏭️ Próximo Post
Post #22: CloudWatch - Monitoring y Logs
Tags: #AWS #CloudPractitioner #CloudFormation #IaC #Automation #Infrastructure #Certification
Related Articles
AWS Cloud Practitioner #1: De Servidores Físicos a la Nube
Aprende qué es cloud computing y las diferencias entre IaaS, PaaS y SaaS con una metodología bottom-up que construye tu conocimiento paso a paso.
AWS Cloud Practitioner #2: Infraestructura Global AWS - Regions, AZs y Edge Locations
Descubre cómo AWS distribuye su infraestructura globalmente y aprende a elegir la región correcta para tus aplicaciones usando metodología bottom-up.
AWS Cloud Practitioner #3: Superpoderes de la Nube - Elasticity, Scalability y HA
Comprende las ventajas clave de cloud computing: elasticity, scalability, high availability y agility. Aprende cómo AWS implementa estos conceptos.
AWS Cloud Practitioner #4: Well-Architected Framework - Los 6 Pilares
Aprende los 6 pilares del AWS Well-Architected Framework: Operational Excellence, Security, Reliability, Performance Efficiency, Cost Optimization y Sustainability.