Terraform State
tfstate, plan/apply, state locking y gestión multi-cloud
Terraform trabaja con un modelo de estado: el archivo `terraform.tfstate` registra el estado actual de la infraestructura tal como Terraform la conoce. Cuando ejecutas `terraform plan`, Terraform compara el estado deseado (tus archivos .tf) con el estado actual (tfstate) y calcula los cambios necesarios. Si el tfstate no existe, Terraform asume que nada existe y recrea todo.
El tfstate es el registro de verdad de Terraform: mapea cada recurso en tus archivos .tf con el recurso real en AWS (por ID). Perder el tfstate es catastrófico: Terraform ya no sabe qué recursos creó y puede duplicar o crear conflictos. Por eso el tfstate debe guardarse remotamente en S3 con versionado habilitado, nunca en el repositorio git.
El state locking evita que dos personas apliquen cambios simultáneamente. Con un backend S3 + DynamoDB, Terraform adquiere un lock en DynamoDB antes de cualquier operación de write (plan con -lock=true, apply, destroy). Si alguien más ya tiene el lock, Terraform espera. Sin locking, dos personas pueden aplicar cambios conflictivos y corromper el estado.
Terraform es multi-cloud por diseño: el mismo lenguaje HCL describe recursos en AWS, GCP, Azure, GitHub, Datadog, y cientos de proveedores. Esto es su principal ventaja sobre CloudFormation (AWS-only). La desventaja es complejidad adicional: debes gestionar proveedores, versiones, y el tfstate separado por workspace.
# main.tf — backend configuration with S3 + DynamoDB lock
terraform {
required_version = '>= 1.6'
required_providers {
aws = {
source = 'hashicorp/aws'
version = '~> 5.0'
}
}
# Remote state in S3 (never commit tfstate to git)
backend 's3' {
bucket = 'my-terraform-state-bucket'
key = 'ml-pipeline/terraform.tfstate'
region = 'us-east-1'
encrypt = true # encrypt state at rest
dynamodb_table = 'terraform-locks' # state locking
}
}
provider 'aws' {
region = var.aws_region
}
# variables.tf
variable 'environment' {
type = string
description = 'Deployment environment'
validation {
condition = contains(['dev', 'staging', 'prod'], var.environment)
error_message = 'environment must be dev, staging, or prod'
}
}
variable 'aws_region' {
type = string
default = 'us-east-1'
}
# resources.tf
resource 'aws_lambda_function' 'processor' {
function_name = 'ml-processor-${var.environment}'
runtime = 'python3.11'
handler = 'index.handler'
role = aws_iam_role.lambda_role.arn # reference another resource
filename = 'lambda.zip'
}
resource 'aws_dynamodb_table' 'results' {
name = 'ml-results-${var.environment}'
billing_mode = 'PAY_PER_REQUEST'
hash_key = 'job_id'
attribute {
name = 'job_id'
type = 'S'
}
}
# outputs.tf
output 'lambda_arn' {
value = aws_lambda_function.processor.arn
description = 'Processor Lambda ARN'
}
# --- Workflow ---
# terraform init -> download providers, configure backend
# terraform plan -var='environment=staging' -> preview changes
# terraform apply -var='environment=staging' -> apply changes
# terraform destroy -> destroy all resources
# Workspaces for environment separation:
# terraform workspace new staging
# terraform workspace select prod
# terraform workspace listDebugging lab
Detecta y corrige el error en el código.
- 01
# Terraform state stored locally and committed to git # .gitignore does NOT exclude terraform.tfstate # Team member commits: git add terraform.tfstate
- 02
# Two developers apply changes simultaneously (no locking) # Developer A: terraform apply (adds Lambda) # Developer B: terraform apply (removes DynamoDB) # Both use local tfstate, result is corrupted
- 03
# Resource created manually in AWS console, not in Terraform # Terraform plan shows it as 'to create' (will fail: already exists) terraform plan # + aws_s3_bucket.data_bucket # resource exists but tfstate doesn't know