Versioning y Deploy con IaC
Git versioning, CI/CD con IaC y procedimientos de rollback
Los templates de IaC deben versionarse en git como cualquier código: cada cambio en un template es un commit, con mensaje descriptivo, revisado en PR. El historial de git es el historial de cambios de infraestructura. `git blame template.yaml` te dice quién cambió el security group el martes pasado y con qué justificación.
Un pipeline de CI/CD para IaC sigue el mismo patrón que para aplicaciones: push → validar template (cfn-lint, terraform validate) → plan/changeset en staging → desplegar en staging → plan/changeset en prod → aprobación manual → desplegar en prod. La validación del template antes de desplegar detecta errores de sintaxis, tipos incorrectos de propiedades, y referencias a recursos que no existen.
El rollback de IaC se hace volviendo al commit anterior y redespliegando. Si el template actual causó un problema, `git revert HEAD` genera un nuevo commit que revierte los cambios, y el pipeline lo redespliega. En CloudFormation, puedes usar `rollback-stack` que vuelve a la última versión estable sin necesidad de git. En Terraform, `terraform apply` con el estado anterior (si tienes versiones en S3) es equivalente.
Los módulos de Terraform y los Constructs de CDK son el mecanismo de reutilización de IaC. En lugar de copiar 50 líneas de configuración de Lambda en cada stack, defines un módulo `lambda_function` con los parámetros variables y lo reutilizas. Los cambios al módulo se propagan a todos los stacks que lo usan, similar a una librería de código.
# === CI/CD pipeline for IaC (GitHub Actions) ===
name: IaC Deployment
on:
push:
branches: [main]
paths: ['infrastructure/**'] # only when infra changes
jobs:
validate:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Validate CloudFormation template
run: |
pip install cfn-lint
cfn-lint infrastructure/template.yaml # syntax + best practices
aws cloudformation validate-template \
--template-body file://infrastructure/template.yaml
deploy-staging:
needs: validate
steps:
- name: Create changeset for staging
run: |
aws cloudformation create-change-set \
--stack-name ml-pipeline-staging \
--change-set-name deploy-$(git rev-parse --short HEAD) \
--template-body file://infrastructure/template.yaml \
--parameter-overrides Env=staging
- name: Execute changeset
run: |
aws cloudformation execute-change-set \
--stack-name ml-pipeline-staging \
--change-set-name deploy-$(git rev-parse --short HEAD)
deploy-prod:
needs: deploy-staging
environment: production # requires manual approval
steps:
- name: Deploy to production
run: |
aws cloudformation deploy \
--stack-name ml-pipeline-prod \
--template-file infrastructure/template.yaml \
--parameter-overrides Env=prod \
--capabilities CAPABILITY_NAMED_IAM
# === Rollback procedure ===
# Option 1: CloudFormation native rollback
# aws cloudformation rollback-stack --stack-name ml-pipeline-prod
# Option 2: Git revert + redeploy
# git revert HEAD # creates new commit reverting last change
# git push origin main # triggers CI/CD with old template
# Option 3: Deploy specific git tag
# git checkout v1.2.3 infrastructure/template.yaml
# git commit -m 'revert: rollback to v1.2.3 for incident ABC'
# git push origin main
# === Reusable CDK Construct (module equivalent) ===
class MLLambdaConstruct(Construct):
"""Reusable Lambda + DynamoDB + CloudWatch pattern"""
def __init__(self, scope, id, env_name, memory=512):
super().__init__(scope, id)
self.table = dynamodb.Table(self, 'Table', ...)
self.function = _lambda.Function(self, 'Function',
memory_size=memory, ...)
self.table.grant_read_write_data(self.function)
# Reuse in multiple stacks:
class AppStack(Stack):
def __init__(self, scope, id, env_name):
processor = MLLambdaConstruct(self, 'Processor', env_name, memory=512)
trainer = MLLambdaConstruct(self, 'Trainer', env_name, memory=2048)Debugging lab
Detecta y corrige el error en el código.
- 01
# IaC template not in git, stored only in S3 console uploads # No history of who changed what or when # Incident: security group was opened to 0.0.0.0/0, no one knows when
- 02
# Rollback by editing production template directly under pressure # Edit template.yaml in console/editor, deploy immediately # Changes are unreviewed, possibly break other things
- 03
# IaC deployed manually from developer laptop aws cloudformation deploy --stack-name ml-pipeline-prod --template-file template.yaml # No validation, no changeset, no approval, no audit trail