AWS CDK Programático
Constructs, permisos automáticos y abstracciones de alto nivel
AWS CDK (Cloud Development Kit) permite definir infraestructura con código real: Python, TypeScript, Java, Go. En lugar de 500 líneas de YAML, escribes clases y métodos que representan infraestructura. CDK genera el template de CloudFormation automáticamente (cdk synth) y lo despliega (cdk deploy). El beneficio principal es que puedes usar loops, condicionales, funciones y módulos — imposibles en YAML declarativo.
Los Constructs son los bloques de construcción de CDK. Un Construct L1 (CfnFunction) es un mapeo directo a CloudFormation. Un Construct L2 (aws_lambda.Function) abstrae los detalles: genera el IAM role automáticamente, configura log groups, y expone métodos como `grant_invoke()`. Un Construct L3 (patterns) es una combinación de servicios: `LambdaRestApi` crea Lambda + API Gateway + IAM en una línea.
Los métodos `grant_*` de CDK manejan IAM automáticamente. `table.grant_read_write_data(function)` genera exactamente la policy necesaria para que esa función lea y escriba esa tabla específica, nada más. Esto evita el antipatrón de crear policies con wildcard resource ('*') por comodidad. CDK calcula los ARNs específicos en tiempo de síntesis.
CDK mantiene un bootstrap stack en tu cuenta AWS (CDKToolkit) que provee un bucket S3 para assets y un ECR repo para imágenes Docker. Debes ejecutar `cdk bootstrap` una vez por cuenta/región antes de poder hacer deploy. Los assets (código Lambda, imágenes Docker) se suben al bucket de bootstrap automáticamente durante `cdk deploy`.
from constructs import Construct
from aws_cdk import (
Stack, App, Duration, RemovalPolicy,
aws_lambda as _lambda,
aws_dynamodb as dynamodb,
aws_s3 as s3,
aws_sqs as sqs,
aws_lambda_event_sources as event_sources,
)
class MLPipelineStack(Stack):
def __init__(self, scope: Construct, id: str, env_name: str, **kwargs):
super().__init__(scope, id, **kwargs)
# S3 bucket (L2 construct — higher level than CfnBucket)
data_bucket = s3.Bucket(
self, 'DataBucket',
bucket_name=f'ml-data-{env_name}-{self.account}',
removal_policy=RemovalPolicy.RETAIN, # don't delete on cdk destroy
versioned=True
)
# DynamoDB table
results_table = dynamodb.Table(
self, 'ResultsTable',
partition_key=dynamodb.Attribute(
name='job_id', type=dynamodb.AttributeType.STRING
),
billing_mode=dynamodb.BillingMode.PAY_PER_REQUEST,
removal_policy=RemovalPolicy.RETAIN
)
# SQS Queue for decoupling
queue = sqs.Queue(
self, 'ProcessingQueue',
visibility_timeout=Duration.seconds(300)
)
# Lambda function — CDK creates IAM role automatically
processor = _lambda.Function(
self, 'Processor',
runtime=_lambda.Runtime.PYTHON_3_11,
handler='index.handler',
code=_lambda.Code.from_asset('lambda_code/'), # uploads to S3
memory_size=512,
timeout=Duration.minutes(5),
environment={'TABLE_NAME': results_table.table_name}
)
# Grant permissions (CDK handles IAM policy generation)
data_bucket.grant_read(processor) # s3:GetObject on this bucket
results_table.grant_read_write_data(processor) # DynamoDB read+write
queue.grant_consume_messages(processor) # sqs:ReceiveMessage + delete
# Wire SQS → Lambda event source
processor.add_event_source(
event_sources.SqsEventSource(queue, batch_size=10)
)
# App entry point
app = App()
MLPipelineStack(app, 'MLPipeline-staging', env_name='staging')
MLPipelineStack(app, 'MLPipeline-prod', env_name='prod')
app.synth()
# Commands:
# cdk synth -> preview generated CloudFormation template
# cdk diff -> show what will change
# cdk deploy -> deploy to AWS
# cdk destroy -> delete stack (respects RemovalPolicy.RETAIN)Debugging lab
Detecta y corrige el error en el código.
- 01
# CDK: Lambda function without proper permissions processor = _lambda.Function(self, 'Processor', ...) table = dynamodb.Table(self, 'Table', ...) # Lambda tries to read DynamoDB but has no permission
- 02
# CDK: using low-level L1 construct (verbose, loses CDK benefits) from aws_cdk import aws_cloudformation as cfn role = cfn.CfnResource(self, 'Role', type='AWS::IAM::Role', properties={'AssumeRolePolicyDocument': {...}} )
- 03
# CDK deploy on new account/region without bootstrap cdk deploy MLPipeline-prod # Error: MLPipeline-prod requires bootstrapped environment