CI/CD y Deploy en AWS
6.12.5kata 5 de 5

Infrastructure Stacks

Separación de entornos, aislamiento de recursos y overrides por parámetros

Un stack de infraestructura es un conjunto nombrado de recursos de AWS desplegados como unidad. La regla fundamental es: un stack por entorno (dev, staging, prod). Esto garantiza que cambios en el stack de staging no afecten producción, que las credenciales sean completamente separadas, y que puedas destruir el stack de dev sin riesgo.

Los parámetros son la forma de personalizar el mismo template para distintos entornos. En lugar de tres templates casi idénticos (uno por env), tienes un template con Parámetros y Mappings. El parámetro `Env=staging` inyecta diferentes tamaños de instancia, nombres de bucket, y límites de capacidad. La fuente de verdad es única; el template se adapta.

Los recursos NO deben compartirse entre entornos. Un bucket S3 compartido entre staging y producción significa que un deploy de staging puede sobreescribir datos de producción. Cada stack debe tener sus propios buckets, tablas DynamoDB, endpoints SageMaker, y roles IAM. El costo adicional de duplicar recursos es insignificante comparado con el riesgo de contaminación.

Los Outputs del stack son los valores que otros stacks pueden importar. Un stack de infraestructura base exporta el VPC ID, los IDs de subnets, y el ARN del bucket de datos. Los stacks de aplicación importan esos valores sin hardcodearlos. Esto crea una jerarquía: cambios en la infraestructura base se propagan automáticamente a los stacks que la consumen.

structure.txt
# === template.yaml: parametrized for all environments ===
AWSTemplateFormatVersion: '2010-09-09'

Parameters:
  Env:
    Type: String
    AllowedValues: [dev, staging, prod]
  ModelMemory:
    Type: Number
    Default: 512

Mappings:
  EnvConfig:
    dev:
      LambdaMemory: 256
      DynamoCapacity: 1
      LogRetentionDays: 7
    staging:
      LambdaMemory: 512
      DynamoCapacity: 5
      LogRetentionDays: 30
    prod:
      LambdaMemory: 1024
      DynamoCapacity: 10
      LogRetentionDays: 365

Resources:
  # Each env gets its own bucket (no shared resources)
  DataBucket:
    Type: AWS::S3::Bucket
    Properties:
      BucketName: !Sub 'ml-data-${Env}-${AWS::AccountId}'

  ProcessingFunction:
    Type: AWS::Lambda::Function
    Properties:
      FunctionName: !Sub 'ml-processor-${Env}'
      MemorySize: !FindInMap [EnvConfig, !Ref Env, LambdaMemory]

  ResultsTable:
    Type: AWS::DynamoDB::Table
    Properties:
      TableName: !Sub 'ml-results-${Env}'
      ProvisionedThroughput:
        ReadCapacityUnits: !FindInMap [EnvConfig, !Ref Env, DynamoCapacity]
        WriteCapacityUnits: !FindInMap [EnvConfig, !Ref Env, DynamoCapacity]

Outputs:
  BucketName:
    Value: !Ref DataBucket
    Export:
      Name: !Sub '${Env}-data-bucket'  # importable by other stacks
  FunctionArn:
    Value: !GetAtt ProcessingFunction.Arn
    Export:
      Name: !Sub '${Env}-processor-arn'

# === Deploy commands for each environment ===
# aws cloudformation deploy --stack-name ml-pipeline-dev
#   --template-file template.yaml
#   --parameter-overrides Env=dev
#   --capabilities CAPABILITY_NAMED_IAM

# aws cloudformation deploy --stack-name ml-pipeline-staging
#   --template-file template.yaml
#   --parameter-overrides Env=staging

# aws cloudformation deploy --stack-name ml-pipeline-prod
#   --template-file template.yaml
#   --parameter-overrides Env=prod

# Import output from another stack:
# OtherResource:
#   Properties:
#     BucketName: !ImportValue 'prod-data-bucket'

Debugging lab

Detecta y corrige el error en el código.

0/3 tests passing0%
  1. 01

    # Same S3 bucket name for all environments Resources: DataBucket: Type: AWS::S3::Bucket Properties: BucketName: ml-data-bucket # staging and prod share the same bucket!

  2. 02

    # Three separate templates with duplicated config # dev-template.yaml: LambdaMemory: 256 # staging-template.yaml: LambdaMemory: 512 # prod-template.yaml: LambdaMemory: 1024 # Any change must be applied to all 3 manually

  3. 03

    # Stack with no Outputs: other stacks hardcode resource names Resources: DataBucket: Type: AWS::S3::Bucket # No Outputs defined # In another stack: BucketName: ml-data-prod # hardcoded, breaks if name changes