Pular para o conteúdo principal

Lab : CloudFormation

Objetivo​

Criar templates CloudFormation para implantar uma infraestrutura completa de forma reprodutível.

Parte 1 : Template Básico​

Exercício 1.1 : Security Group​

Crie um template para um Security Group permitindo HTTP e SSH:

AWSTemplateFormatVersion: "2010-09-09"
Description: Security Group para servidor web

Resources:
WebServerSG:
Type: _______________
Properties:
GroupDescription: _______________
SecurityGroupIngress:
- IpProtocol: ___
FromPort: ___
ToPort: ___
CidrIp: _______________
- IpProtocol: ___
FromPort: ___
ToPort: ___
CidrIp: _______________
💡 Solução
AWSTemplateFormatVersion: "2010-09-09"
Description: Security Group para servidor web

Resources:
WebServerSG:
Type: AWS::EC2::SecurityGroup
Properties:
GroupDescription: Allow HTTP and SSH access
SecurityGroupIngress:
- IpProtocol: tcp
FromPort: 80
ToPort: 80
CidrIp: 0.0.0.0/0
- IpProtocol: tcp
FromPort: 22
ToPort: 22
CidrIp: 0.0.0.0/0

Exercício 1.2 : Adição de Parâmetros​

Melhore o template com parâmetros:

Parameters:
SSHLocation:
Type: _______________
Default: _______________
Description: IP range for SSH access
AllowedPattern: _______________
ConstraintDescription: Must be valid CIDR

Environment:
Type: String
AllowedValues:
- ___
- ___
- ___
💡 Solução
Parameters:
SSHLocation:
Type: String
Default: 0.0.0.0/0
Description: IP range for SSH access
AllowedPattern: (\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})/(\d{1,2})
ConstraintDescription: Must be valid CIDR (e.g., 10.0.0.0/24)

Environment:
Type: String
Default: dev
AllowedValues:
- dev
- staging
- prod
Description: Environment type

Depois, no Security Group:

SecurityGroupIngress:
- IpProtocol: tcp
FromPort: 22
ToPort: 22
CidrIp: !Ref SSHLocation

Parte 2 : Instância EC2​

Exercício 2.1 : Template EC2 Completo​

AWSTemplateFormatVersion: "2010-09-09"
Description: Web Server com EC2

Parameters:
Environment:
Type: String
Default: dev
AllowedValues: [dev, staging, prod]

InstanceType:
Type: String
Default: t3.micro
AllowedValues: [t3.micro, t3.small, t3.medium]

KeyName:
Type: AWS::EC2::KeyPair::KeyName
Description: EC2 Key Pair

Mappings:
RegionAMI:
us-east-1:
AMI: ami-0c55b159cbfafe1f0
eu-west-1:
AMI: ami-0d729a60

Resources:
# Complete os recursos
WebServerSG:
Type: _______________
# ...

WebServer:
Type: _______________
Properties:
ImageId: _______________
InstanceType: _______________
KeyName: _______________
SecurityGroupIds:
- _______________
Tags:
- Key: Name
Value: _______________
UserData:
Fn::Base64: |
#!/bin/bash
# Complete o script

Outputs:
PublicIP:
Value: _______________
WebURL:
Value: _______________
💡 Solução Completa
AWSTemplateFormatVersion: "2010-09-09"
Description: Web Server com EC2

Parameters:
Environment:
Type: String
Default: dev
AllowedValues: [dev, staging, prod]

InstanceType:
Type: String
Default: t3.micro
AllowedValues: [t3.micro, t3.small, t3.medium]

KeyName:
Type: AWS::EC2::KeyPair::KeyName
Description: EC2 Key Pair

Mappings:
RegionAMI:
us-east-1:
AMI: ami-0c55b159cbfafe1f0
eu-west-1:
AMI: ami-0d729a60

Resources:
WebServerSG:
Type: AWS::EC2::SecurityGroup
Properties:
GroupDescription: Allow HTTP and SSH
SecurityGroupIngress:
- IpProtocol: tcp
FromPort: 80
ToPort: 80
CidrIp: 0.0.0.0/0
- IpProtocol: tcp
FromPort: 22
ToPort: 22
CidrIp: 0.0.0.0/0
Tags:
- Key: Name
Value: !Sub "${Environment}-web-sg"
- Key: Environment
Value: !Ref Environment

WebServer:
Type: AWS::EC2::Instance
Properties:
ImageId: !FindInMap [RegionAMI, !Ref "AWS::Region", AMI]
InstanceType: !Ref InstanceType
KeyName: !Ref KeyName
SecurityGroupIds:
- !Ref WebServerSG
Tags:
- Key: Name
Value: !Sub "${Environment}-web-server"
- Key: Environment
Value: !Ref Environment
UserData:
Fn::Base64: !Sub |
#!/bin/bash
yum update -y
yum install -y httpd
systemctl start httpd
systemctl enable httpd
echo "<h1>Environment: ${Environment}</h1>" > /var/www/html/index.html
echo "<p>Instance Type: ${InstanceType}</p>" >> /var/www/html/index.html

Outputs:
InstanceId:
Description: Instance ID
Value: !Ref WebServer

PublicIP:
Description: Public IP
Value: !GetAtt WebServer.PublicIp

WebURL:
Description: Website URL
Value: !Sub "http://${WebServer.PublicIp}"

Parte 3 : VPC Completa​

Exercício 3.1 : Arquitetura VPC​

Crie um template para esta arquitetura:

┌─────────────────────────────────────────────────────────────┐
│ VPC 10.0.0.0/16 │
│ │
│ ┌─────────────────────┐ ┌─────────────────────┐ │
│ │ Public Subnet │ │ Private Subnet │ │
│ │ 10.0.1.0/24 │ │ 10.0.2.0/24 │ │
│ │ │ │ │ │
│ │ ┌───────────┐ │ │ ┌───────────┐ │ │
│ │ │ EC2 │ │ │ │ EC2 │ │ │
│ │ │ (web) │ │ │ │ (app) │ │ │
│ │ └───────────┘ │ │ └───────────┘ │ │
│ │ │ │ │ │
│ └─────────────────────┘ └─────────────────────┘ │
│ │
└─────────────────────────────────────────────────────────────┘

Template a completar:

Resources:
# VPC
VPC:
Type: AWS::EC2::VPC
Properties:
CidrBlock: _______________
EnableDnsHostnames: true
Tags:
- Key: Name
Value: !Sub "${AWS::StackName}-vpc"

# Internet Gateway
InternetGateway:
Type: _______________

AttachGateway:
Type: AWS::EC2::VPCGatewayAttachment
Properties:
VpcId: _______________
InternetGatewayId: _______________

# Public Subnet
PublicSubnet:
Type: AWS::EC2::Subnet
Properties:
VpcId: _______________
CidrBlock: _______________
MapPublicIpOnLaunch: ___
Tags:
- Key: Name
Value: !Sub "${AWS::StackName}-public"

# Private Subnet
PrivateSubnet:
Type: _______________
# Complete...

# Route Table Public
PublicRouteTable:
Type: AWS::EC2::RouteTable
Properties:
VpcId: !Ref VPC

PublicRoute:
Type: AWS::EC2::Route
Properties:
RouteTableId: _______________
DestinationCidrBlock: _______________
GatewayId: _______________

PublicSubnetRouteAssociation:
Type: AWS::EC2::SubnetRouteTableAssociation
Properties:
SubnetId: _______________
RouteTableId: _______________
💡 Solução
AWSTemplateFormatVersion: "2010-09-09"
Description: VPC com subnets pública e privada

Parameters:
Environment:
Type: String
Default: dev

Resources:
VPC:
Type: AWS::EC2::VPC
Properties:
CidrBlock: 10.0.0.0/16
EnableDnsHostnames: true
EnableDnsSupport: true
Tags:
- Key: Name
Value: !Sub "${AWS::StackName}-vpc"

InternetGateway:
Type: AWS::EC2::InternetGateway
Properties:
Tags:
- Key: Name
Value: !Sub "${AWS::StackName}-igw"

AttachGateway:
Type: AWS::EC2::VPCGatewayAttachment
Properties:
VpcId: !Ref VPC
InternetGatewayId: !Ref InternetGateway

PublicSubnet:
Type: AWS::EC2::Subnet
Properties:
VpcId: !Ref VPC
CidrBlock: 10.0.1.0/24
MapPublicIpOnLaunch: true
AvailabilityZone: !Select [0, !GetAZs ""]
Tags:
- Key: Name
Value: !Sub "${AWS::StackName}-public"

PrivateSubnet:
Type: AWS::EC2::Subnet
Properties:
VpcId: !Ref VPC
CidrBlock: 10.0.2.0/24
MapPublicIpOnLaunch: false
AvailabilityZone: !Select [0, !GetAZs ""]
Tags:
- Key: Name
Value: !Sub "${AWS::StackName}-private"

PublicRouteTable:
Type: AWS::EC2::RouteTable
Properties:
VpcId: !Ref VPC
Tags:
- Key: Name
Value: !Sub "${AWS::StackName}-public-rt"

PublicRoute:
Type: AWS::EC2::Route
DependsOn: AttachGateway
Properties:
RouteTableId: !Ref PublicRouteTable
DestinationCidrBlock: 0.0.0.0/0
GatewayId: !Ref InternetGateway

PublicSubnetRouteAssociation:
Type: AWS::EC2::SubnetRouteTableAssociation
Properties:
SubnetId: !Ref PublicSubnet
RouteTableId: !Ref PublicRouteTable

Outputs:
VPCId:
Value: !Ref VPC
Export:
Name: !Sub "${AWS::StackName}-VPCId"

PublicSubnetId:
Value: !Ref PublicSubnet
Export:
Name: !Sub "${AWS::StackName}-PublicSubnetId"

PrivateSubnetId:
Value: !Ref PrivateSubnet
Export:
Name: !Sub "${AWS::StackName}-PrivateSubnetId"

Parte 4 : Troubleshooting​

Exercício 4.1 : Identificar Erros​

Este template contém erros. Encontre-os:

AWSTemplateFormatVersion: "2010-09-09"

Parameters:
InstanceType:
Type: string # Erro 1
Default: t3.micro

Resources:
MyInstance:
Type: AWS::EC2::Instance
Properties:
ImageId: ami-12345678
InstanceType: !Ref instancetype # Erro 2
SecurityGroups:
- !Ref MySG # Erro 3 (ordem)
Tags:
- Key: Name
Value: !Sub ${AWS:StackName}-instance # Erro 4

MySG:
Type: AWS::EC2::SecurityGroup
Properties:
GroupDescription # Erro 5
SecurityGroupIngress:
- IpProtocol: tcp
FromPort: 80
ToPort: 80
💡 Soluções
  1. Erro 1: string → String (maiúscula)
  2. Erro 2: instancetype → InstanceType (respeitar o case do parâmetro)
  3. Erro 3: MySG deve ser definido antes ou usar DependsOn
  4. Erro 4: AWS:StackName → AWS::StackName (dois pontos duplos)
  5. Erro 5: Falta : "Description" após GroupDescription

Template corrigido:

AWSTemplateFormatVersion: "2010-09-09"

Parameters:
InstanceType:
Type: String
Default: t3.micro

Resources:
MySG:
Type: AWS::EC2::SecurityGroup
Properties:
GroupDescription: "Security group for web server"
SecurityGroupIngress:
- IpProtocol: tcp
FromPort: 80
ToPort: 80
CidrIp: 0.0.0.0/0

MyInstance:
Type: AWS::EC2::Instance
Properties:
ImageId: ami-12345678
InstanceType: !Ref InstanceType
SecurityGroupIds:
- !Ref MySG
Tags:
- Key: Name
Value: !Sub "${AWS::StackName}-instance"

Parte 5 : Projeto Final​

Exercício 5.1 : Infraestrutura Completa​

Crie um template para a seguinte arquitetura:

┌─────────────────────────────────────────────────────────────┐
│ Arquitetura Web 3-Camadas │
├─────────────────────────────────────────────────────────────┤
│ │
│ Internet → ALB → EC2 (Auto Scaling) → RDS │
│ │
│ Componentes requeridos: │
│ • VPC com 2 subnets públicas e 2 privadas │
│ • Security Groups (ALB, EC2, RDS) │
│ • Application Load Balancer │
│ • Launch Template + Auto Scaling Group │
│ • RDS MySQL (opcional) │
│ │
│ Parâmetros: │
│ • Environment (dev/staging/prod) │
│ • InstanceType │
│ • MinSize, MaxSize, DesiredCapacity │
│ │
└─────────────────────────────────────────────────────────────┘

Critérios de Validação​

CritérioPontos
Template válido (sem erros)/15
Parâmetros bem definidos/15
VPC corretamente configurada/20
Security Groups restritivos/15
ALB + ASG funcionais/20
Outputs úteis/10
Documentação/comentários/5
Total/100

Entregável Final​

Documento a Produzir​

  1. Template CloudFormation completo (YAML)
  2. Instruções de deploy (comandos CLI)
  3. Esquema da arquitetura
  4. Lista de parâmetros e valores
  5. Testes de validação realizados

Fim do curso! Boa continuação na sua jornada AWS.