Skip to main content

O que é State?

O Terraform usa state para mapear recursos do mundo real para sua configuração. Sem ele, o Terraform não sabe quais recursos foram criados.
{
  "version": 4,
  "terraform_version": "1.6.0",
  "resources": {
    "aws_instance.web": {
      "type": "aws_instance",
      "instances": [{
        "attributes": {
          "id": "i-1234567890abcdef0",
          "public_ip": "54.123.45.67",
          "tags": { "Name": "web-server" }
        }
      }]
    }
  }
}

Remote State

S3 + DynamoDB (AWS)

terraform {
  backend "s3" {
    bucket         = "my-terraform-state"
    key            = "prod/terraform.tfstate"
    region         = "us-east-1"
    encrypt        = true
    dynamodb_table = "terraform-locks"
  }
}
Benefícios:
  • Compartilhado entre equipes
  • Versionado no S3
  • Lock com DynamoDB previne conflitos

Azure Blob Storage

terraform {
  backend "azurerm" {
    resource_group_name  = "my-rg"
    storage_account_name = "mytfstate"
    container_name       = "tfstate"
    key                  = "prod.terraform.tfstate"
  }
}

Google Cloud Storage

terraform {
  backend "gcs" {
    bucket = "my-terraform-state"
    prefix = "prod/state"
  }
}

Terraform Cloud

terraform {
  cloud {
    organization = "my-org"
    
    workspaces {
      name = "my-project-prod"
    }
  }
}

Comandos de State

# Ver estado atual
terraform show
terraform state list

# Listar recursos
terraform state list
terraform state list -id i-1234567890abcdef0

# Mover recurso (renomear)
terraform state mv aws_instance.web aws_instance.api

# Remover recurso do state (não destrói cloud)
terraform state rm aws_instance.old

# Importar recurso existente
terraform import aws_instance.existing i-1234567890abcdef0

# Pull/Push state
terraform state pull > terraform.tfstate
terraform state push terraform.tfstate

# Show resource details
terraform state show aws_instance.web

Importar Recursos

# Importar EC2 instance
terraform import aws_instance.web i-1234567890abcdef0

# Importar para novo recurso
terraform import 'aws_instance.new[0]' i-1234567890abcdef0
# Gerar configuração do recurso importado
terraform state show aws_instance.new > new.tf

Workspaces

# Listar workspaces
terraform workspace list

# Criar workspace
terraform workspace new prod

# Selecionar workspace
terraform workspace select prod

# Mostrar workspace atual
terraform workspace show
# Usar workspace no código
locals {
  environment = terraform.workspace
}

resource "aws_instance" "web" {
  instance_type = terraform.workspace == "prod" ? "t3.large" : "t3.micro"
  
  tags = {
    Environment = terraform.workspace
  }
}

Backend com Lock

DynamoDB Table

aws dynamodb create-table \
  --table-name terraform-locks \
  --attribute-definitions AttributeName=LockID,AttributeType=S \
  --key-schema AttributeName=LockID,KeyType=HASH \
  --billing-mode PAY_PER_REQUEST

Refresh

# Sincronizar state com recursos reais
terraform refresh

# Ou com apply
terraform apply -refresh-only

Dicas e Boas Práticas

  1. Sempre use remote state em produção
  2. Habilite versioning no S3
  3. Use lock para prevenir deploys simultâneos
  4. Nunca edite state manualmente - use terraform state mv
  5. Backup antes de operações críticas
  6. Separe state por ambiente (dev/staging/prod)
  7. Use workspaces ou diretórios separados

Troubleshooting

# Debug logs
TF_LOG=TRACE terraform apply

# Desbloquear state
terraform force-unlock LOCK_ID

# State corrompido - backup e recover
cp terraform.tfstate terraform.tfstate.backup