cloud · temario
6.13tema 13 de 16

IaC en AWS

CloudFormation, CDK y Terraform en AWS

Infrastructure as Code (IaC) significa describir tu infraestructura en archivos de texto versionados en git, no haciendo clic en consolas. AWS ofrece dos caminos nativos: CloudFormation (JSON/YAML, declarativo, propietario de AWS) y AWS CDK (Python/TypeScript, programático, genera CloudFormation). Terraform (HashiCorp) es agnóstico a proveedores pero requiere más setup. El principio es el mismo: código define infraestructura, CI/CD despliega.

CloudFormation describe stacks: colecciones nombradas de recursos. Un stack por aplicación, staging o región. El template (JSON o YAML) enumera Recursos (EC2, Lambda, DynamoDB, etc.), Parámetros de entrada, Outputs (qué expone el stack) y Mappings (lookup tables). CloudFormation gestiona dependencias: si un Lambda depende de un IAM role, CloudFormation lo crea primero. Si eliminas el stack, CloudFormation elimina (o retiene, si le dices) todos los recursos.

AWS CDK es programático: escribís código Python/TypeScript que genera templates CloudFormation. En lugar de escribir 500 líneas YAML, escribís clases que representan infraestructura. Ejemplo: CDK crea automáticamente el IAM role que un Lambda necesita; CloudFormation puro te obliga a escribirlo. CDK también maneja condicionales, loops y reutilización de código, imposibles en YAML.

Terraform es agnóstico: un mismo set de archivos .tf puede desplegar en AWS, GCP, Azure, DataDog, GitHub. El modelo es: define estado deseado, Terraform calcula cambios (plan), aplicas cambios (apply). El archivo terraform.tfstate almacena el estado actual; si lo pierdes, Terraform intenta reconciliar. Terraform es más complejo que CloudFormation CDK, pero más poderoso si trabajas multi-cloud.

Drift ocurre cuando alguien cambia infraestructura fuera de IaC: edita un Security Group en la consola, apaga un EC2 directamente. CloudFormation puede detectar drift (detect-stack-drift), pero no lo repara automáticamente. La regla es: TODO cambio de infraestructura va por IaC, nunca por consola. Si lo hiciste por consola, vuelve atrás y hazlo por IaC.

Los errores comunes son: (1) no versionear templates (si están en consola, nadie sabe qué cambió), (2) hardcodear valores (IPs, ARNs, nombres) en lugar de usar Parámetros/Outputs, (3) no usar stacks separados para staging/prod (un cambio en staging afecta prod accidentalmente), (4) ignorar drift (la realidad en AWS difiere de lo que dice el código), y (5) eliminar stacks para 'limpiar' sin antes mover datos críticos.

structure.txt
# === CLOUDFORMATION TEMPLATE (YAML) ===
AWSTemplateFormatVersion: '2010-09-09'
Description: 'ML Pipeline Infrastructure'

Parameters:
  EnvironmentName:
    Type: String
    AllowedValues: [dev, staging, prod]
  LambdaMemory:
    Type: Number
    Default: 512

Mappings:
  EnvironmentConfig:
    dev:
      InstanceType: t3.micro
      Retries: 1
    prod:
      InstanceType: t3.large
      Retries: 3

Resources:
  LambdaExecutionRole:
    Type: AWS::IAM::Role
    Properties:
      AssumeRolePolicyDocument:
        Version: '2012-10-17'
        Statement:
          - Effect: Allow
            Principal:
              Service: lambda.amazonaws.com
            Action: sts:AssumeRole
      ManagedPolicyArns:
        - arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole

  MLProcessingFunction:
    Type: AWS::Lambda::Function
    Properties:
      FunctionName: !Sub 'ml-processor-${EnvironmentName}'
      Runtime: python3.11
      Handler: index.handler
      Role: !GetAtt LambdaExecutionRole.Arn
      MemorySize: !Ref LambdaMemory
      Code:
        ZipFile: |
          import json
          def handler(event, context):
              return {'statusCode': 200, 'body': 'OK'}

  ProcessingQueue:
    Type: AWS::SQS::Queue
    Properties:
      QueueName: !Sub 'ml-queue-${EnvironmentName}'
      VisibilityTimeout: 300
      MessageRetentionPeriod: 86400

  ProcessingDatabase:
    Type: AWS::DynamoDB::Table
    Properties:
      TableName: !Sub 'ml-results-${EnvironmentName}'
      BillingMode: PAY_PER_REQUEST
      AttributeDefinitions:
        - AttributeName: job_id
          AttributeType: S
      KeySchema:
        - AttributeName: job_id
          KeyType: HASH

Outputs:
  LambdaArn:
    Value: !GetAtt MLProcessingFunction.Arn
    Export:
      Name: !Sub '${EnvironmentName}-lambda-arn'
  QueueUrl:
    Value: !Ref ProcessingQueue
  DatabaseName:
    Value: !Ref ProcessingDatabase

# === DEPLOY CLOUDFORMATION ===
# aws cloudformation create-stack \
# --stack-name ml-pipeline-prod \
# --template-body file://template.yaml \
# --parameters ParameterKey=EnvironmentName,ParameterValue=prod \
#             ParameterKey=LambdaMemory,ParameterValue=1024 \
# --capabilities CAPABILITY_NAMED_IAM

# === AWS CDK (Python) ===
from constructs import Construct
from aws_cdk import (
    Stack, App, CfnOutput,
    aws_lambda as _lambda,
    aws_dynamodb as dynamodb,
    aws_sqs as sqs,
    aws_iam as iam,
)

class MLPipelineStack(Stack):
    def __init__(self, scope: Construct, id: str, env_name: str, **kwargs):
        super().__init__(scope, id, **kwargs)

        # IAM Role (CDK creates automatically)
        role = iam.Role(
            self, 'LambdaRole',
            assumed_by=iam.ServicePrincipal('lambda.amazonaws.com')
        )

        # Lambda Function
        processor = _lambda.Function(
            self, 'Processor',
            runtime=_lambda.Runtime.PYTHON_3_11,
            handler='index.handler',
            code=_lambda.Code.from_asset('lambda_code'),
            memory_size=512,
            role=role
        )

        # DynamoDB Table
        table = dynamodb.Table(
            self, 'Results',
            partition_key=dynamodb.Attribute(
                name='job_id',
                type=dynamodb.AttributeType.STRING
            ),
            billing_mode=dynamodb.BillingMode.PAY_PER_REQUEST
        )

        # SQS Queue
        queue = sqs.Queue(self, 'ProcessingQueue')

        # Grant permissions
        table.grant_read_write_data(processor)
        queue.grant_send_messages(processor)

        # Export outputs
        CfnOutput(self, 'LambdaArn', value=processor.function_arn)
        CfnOutput(self, 'TableName', value=table.table_name)

# === DEPLOY CDK ===
# cdk synth
# cdk deploy --require-approval=never

# === TERRAFORM (HCL) ===
terraform {
  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 5.0"
    }
  }
}

variable "environment" {
  type = string
}

resource "aws_lambda_function" "processor" {
  function_name = "ml-processor-${var.environment}"
  runtime       = "python3.11"
  handler       = "index.handler"
  role          = aws_iam_role.lambda_role.arn
  filename      = "lambda.zip"
}

# === DETECT DRIFT (CloudFormation) ===
# aws cloudformation detect-stack-drift \
# --stack-name ml-pipeline-prod

Katas (5)

Debugging lab

Detecta y corrige el error en el código.

0/6 tests passing0%
  1. 6.13.5.1

    # Create Lambda + DynamoDB by clicking in AWS console # No version control, no template

  2. 6.13.5.2

    LambdaMemory: 512 LambdaTimeout: 30 DatabaseName: 'production-db' # hardcoded values, can't change per environment

  3. 6.13.5.3

    # Lambda created, but no IAM role defined # CloudFormation can't infer permissions

  4. 6.13.5.4

    # Delete stack to 'clean up' aws cloudformation delete-stack --stack-name my-app-prod # Data in DynamoDB is deleted too!

  5. 6.13.5.5

    # Someone modified Security Group in AWS console # CloudFormation template still says old config # Infrastructure = reality, but code ≠ reality

  6. 6.13.5.6

    # CDK code without proper permissions: processor.grant_read(table) # missing write # Lambda tries to write and fails