⏱️4 min read · 860 words
Terraform é o padrão da indústria para Infraestrutura como Código (IaC). Em 2026, todas as equipes de DevOps usam o Terraform para provisionar e gerenciar a infraestrutura em nuvem de forma declarativa. Este guia vai desde o primeiro recurso até módulos de nível de produção e gerenciamento de estado.
📋 Table of Contents
Por que Terraform?
- Agnóstico de provedor— funciona com AWS, GCP, Azure, Kubernetes e mais de 3.000 provedores
- Declarativo– descreva o que você deseja, não como criá-lo
- Gestão estadual— rastreia a infraestrutura real versus seu código
- Planeje antes de aplicar– visualize as alterações antes de fazê-las
- Módulos— componentes de infraestrutura reutilizáveis e compartilháveis
Instalação e configuração
# Install Terraform (macOS)
brew install terraform
# Install via tfenv (version manager)
brew install tfenv
tfenv install 1.9.0
tfenv use 1.9.0
# Verify
terraform --version
# Install providers (runs automatically on init)
terraform init
Conceitos Básicos
# main.tf — basic structure
# Provider — which cloud to use
terraform {
required_version = ">= 1.9"
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 5.0"
}
}
}
provider "aws" {
region = var.aws_region
}
# Variables
variable "aws_region" {
type = string
description = "AWS region"
default = "us-east-1"
}
variable "instance_type" {
type = string
default = "t3.micro"
}
# Resource — actual infrastructure
resource "aws_instance" "web" {
ami = "ami-0c55b159cbfafe1f0"
instance_type = var.instance_type
tags = {
Name = "web-server"
Environment = var.environment
}
}
# Output
output "instance_ip" {
value = aws_instance.web.public_ip
description = "Public IP of web server"
}
Fluxo de trabalho do Terraform
# 1. Initialize — download providers
terraform init
# 2. Format — auto-format code
terraform fmt
# 3. Validate — check syntax
terraform validate
# 4. Plan — preview changes
terraform plan
terraform plan -out=tfplan # save plan to file
# 5. Apply — create/update infrastructure
terraform apply
terraform apply tfplan # apply saved plan
# 6. Destroy — remove all resources
terraform destroy
# Targeted operations
terraform plan -target=aws_instance.web
terraform apply -target=module.networking
Exemplo real: AWS Web Stack
# VPC
resource "aws_vpc" "main" {
cidr_block = "10.0.0.0/16"
enable_dns_hostnames = true
enable_dns_support = true
tags = { Name = "${var.project}-vpc" }
}
# Public subnet
resource "aws_subnet" "public" {
count = 2
vpc_id = aws_vpc.main.id
cidr_block = "10.0.${count.index}.0/24"
availability_zone = data.aws_availability_zones.available.names[count.index]
map_public_ip_on_launch = true
tags = { Name = "${var.project}-public-${count.index}" }
}
# Security group
resource "aws_security_group" "web" {
name = "${var.project}-web-sg"
vpc_id = aws_vpc.main.id
ingress {
from_port = 80
to_port = 80
protocol = "tcp"
cidr_blocks = ["0.0.0.0/0"]
}
ingress {
from_port = 443
to_port = 443
protocol = "tcp"
cidr_blocks = ["0.0.0.0/0"]
}
egress {
from_port = 0
to_port = 0
protocol = "-1"
cidr_blocks = ["0.0.0.0/0"]
}
}
# Application Load Balancer
resource "aws_lb" "web" {
name = "${var.project}-alb"
internal = false
load_balancer_type = "application"
security_groups = [aws_security_group.web.id]
subnets = aws_subnet.public[*].id
}
Módulos — Infraestrutura Reutilizável
# modules/rds/main.tf
variable "db_name" { type = string }
variable "db_user" { type = string }
variable "db_password" {
type = string
sensitive = true
}
variable "subnet_ids" { type = list(string) }
variable "sg_ids" { type = list(string) }
resource "aws_db_instance" "main" {
identifier = var.db_name
engine = "postgres"
engine_version = "16.2"
instance_class = "db.t3.medium"
allocated_storage = 20
db_name = var.db_name
username = var.db_user
password = var.db_password
db_subnet_group_name = aws_db_subnet_group.main.name
vpc_security_group_ids = var.sg_ids
backup_retention_period = 7
skip_final_snapshot = false
deletion_protection = true
storage_encrypted = true
tags = { Name = var.db_name }
}
output "endpoint" { value = aws_db_instance.main.endpoint }
# Use module in root
module "database" {
source = "./modules/rds"
db_name = "myapp"
db_user = var.db_user
db_password = var.db_password
subnet_ids = module.networking.private_subnet_ids
sg_ids = [aws_security_group.db.id]
}
Estado Remoto — Colaboração em Equipe
# Store state in S3 (never commit terraform.tfstate to git!)
terraform {
backend "s3" {
bucket = "mycompany-terraform-state"
key = "production/terraform.tfstate"
region = "us-east-1"
encrypt = true
dynamodb_table = "terraform-state-lock" # prevents concurrent applies
}
}
Espaços de trabalho – vários ambientes
# Create workspaces for dev/staging/prod
terraform workspace new dev
terraform workspace new staging
terraform workspace new prod
terraform workspace list
# * dev
# staging
# prod
terraform workspace select prod
terraform plan
# Reference workspace in code
locals {
instance_type = terraform.workspace == "prod" ? "t3.large" : "t3.micro"
}
Fontes de dados
# Look up existing resources
data "aws_vpc" "existing" {
filter {
name = "tag:Name"
values = ["production-vpc"]
}
}
data "aws_ami" "ubuntu" {
most_recent = true
owners = ["099720109477"] # Canonical
filter {
name = "name"
values = ["ubuntu/images/hvm-ssd/ubuntu-*-22.04-amd64-server-*"]
}
}
resource "aws_instance" "web" {
ami = data.aws_ami.ubuntu.id
subnet_id = data.aws_vpc.existing.id
}
Melhores Práticas
- Nunca se comprometa
terraform.tfstate— use estado remoto (S3, Terraform Cloud) - Use
terraform planantes de cada aplicação– revisar alterações - Bloquear versões do provedor —
version = "~> 5.0"evita surpresas - Usar módulos— Infraestrutura DRY para dev/staging/prod
- Marque todos os recursos —
Environment,Project,Owner - Armazene segredos no AWS Secrets Manager– não em variáveis do Terraform
- Use
-targetcom moderação– pode deixar o estado inconsistente
O Terraform agora é essencial para qualquer trabalho de infraestrutura em nuvem. Comece com instâncias simples do EC2, desenvolva VPC, RDS e ALB e, em seguida, extraia módulos reutilizáveis. O estado remoto e os espaços de trabalho permitem a colaboração em equipe e o gerenciamento de vários ambientes.
🔗 Share this article
✍️ Leave a Comment