AWS SAM and AWS CDK for Developers: Serverless Application Model, Local Testing, Constructs and Infrastructure as Real Code

AWS Developer Associate 55 min min read Updated: Nov 17, 2026 Intermediate
AWS SAM and AWS CDK for Developers: Serverless Application Model, Local Testing, Constructs and Infrastructure as Real Code
Intermediate Topic 2 of 4

Choosing a Tool

ToolStyleBest for
CloudFormationYAML/JSON declarativeThe engine under the others. Direct control
AWS SAMShorthand YAML extension of CloudFormation focused on serverless, plus CLILambda, API Gateway, DynamoDB, Step Functions apps with local testing
AWS CDKReal programming languages (TypeScript, Python, Java, C#, Go) that synthesize to CloudFormationAny AWS infrastructure with loops, functions, reuse and types
Terraform / OpenTofuHCL, multi-cloud, own stateTeams standardizing across clouds

AWS SAM

A SAM template starts with Transform: AWS::Serverless-2016-10-31. Short resource types expand into the full CloudFormation resources (function, role, API, event mappings, permissions).

SAM resourceCreates
AWS::Serverless::FunctionLambda function + role + event source mappings + permissions
AWS::Serverless::Api / HttpApiAPI Gateway REST / HTTP API
AWS::Serverless::SimpleTableDynamoDB table with a single key
AWS::Serverless::StateMachineStep Functions state machine
AWS::Serverless::LayerVersionLambda layer
AWS::Serverless::ApplicationNested application from the Serverless Application Repository
AWS::Serverless::ConnectorGenerates least-privilege permissions between two resources
yaml Transform: AWS::Serverless-2016-10-31 Globals: Function: {Runtime: python3.12, Timeout: 10, MemorySize: 256, Architectures: [arm64]} Resources: Orders: Type: AWS::Serverless::Function Properties: CodeUri: src/ Handler: app.handler AutoPublishAlias: live DeploymentPreference: {Type: Canary10Percent5Minutes, Alarms: [!Ref ErrorAlarm]} # gradual deploy via CodeDeploy Policies: [DynamoDBCrudPolicy: {TableName: !Ref Table}] Events: Api: {Type: HttpApi, Properties: {Path: /orders, Method: POST}} Queue: {Type: SQS, Properties: {Queue: !GetAtt Jobs.Arn, BatchSize: 5}} Nightly: {Type: ScheduleV2, Properties: {ScheduleExpression: "cron(0 2 * * ? *)"}} Table: Type: AWS::Serverless::SimpleTable Properties: {PrimaryKey: {Name: orderId, Type: String}} Jobs: {Type: AWS::SQS::Queue} ErrorAlarm: Type: AWS::CloudWatch::Alarm Properties: Namespace: AWS/Lambda MetricName: Errors Dimensions: [{Name: FunctionName, Value: !Ref Orders}] Statistic: Sum Period: 60 EvaluationPeriods: 1 Threshold: 1 ComparisonOperator: GreaterThanOrEqualToThreshold
  • **Globals** set shared properties for all functions
  • Policy templates (DynamoDBCrudPolicy, S3ReadPolicy, SQSPollerPolicy...) give least-privilege access in one line
  • **AutoPublishAlias publishes a version and moves an alias. DeploymentPreference** uses CodeDeploy to shift traffic gradually (Canary10Percent5Minutes, Linear10PercentEvery1Minute, AllAtOnce) with alarms and automatic rollback and optional pre/post-traffic hook functions
bash sam init # choose a quick start template sam build # install dependencies, prepare artifacts (use --use-container for native builds) sam local invoke Orders -e events/order.json # run a function in a container on your machine sam local start-api # local API on localhost:3000 sam validate --lint sam deploy --guided # first time: saves samconfig.toml sam deploy # later deploys use samconfig.toml sam sync --stack-name orders --watch # fast dev loop: push code changes in seconds (dev only) sam logs --stack-name orders --tail sam traces sam delete
What does sam deploy do? It uploads artifacts to S3, creates a CloudFormation change set, then executes it. SAM is not a separate engine: you can see everything in CloudFormation.

AWS CDK

The Cloud Development Kit lets you define infrastructure with classes, loops, conditions and functions. cdk synth produces a CloudFormation template, and cdk deploy deploys it.

ConceptMeaning
AppThe program entry point. Contains stacks
StackA unit of deployment = one CloudFormation stack
ConstructA reusable cloud component
**L1 (CfnBucket)**Direct, 1:1 CloudFormation resources
**L2 (s3.Bucket)**Curated constructs with sensible defaults, helper methods (grantRead), and security defaults. Most commonly used
L3 (patterns)Multi-resource solutions, for example ApplicationLoadBalancedFargateService
Context and AspectsEnvironment data and cross-cutting rules (apply tags or checks to all resources)
python # app.py (CDK v2, Python) from aws_cdk import App, Stack, Duration, RemovalPolicy, aws_dynamodb as ddb, aws_lambda as _lambda, aws_apigatewayv2 as apigw from aws_cdk.aws_apigatewayv2_integrations import HttpLambdaIntegration from constructs import Construct class OrdersStack(Stack): def __init__(self, scope: Construct, id: str, **kw): super().__init__(scope, id, **kw) table = ddb.Table(self, "Orders", partition_key=ddb.Attribute(name="orderId", type=ddb.AttributeType.STRING), billing_mode=ddb.BillingMode.PAY_PER_REQUEST, point_in_time_recovery=True, removal_policy=RemovalPolicy.RETAIN) fn = _lambda.Function(self, "Fn", runtime=_lambda.Runtime.PYTHON_3_12, handler="app.handler", code=_lambda.Code.from_asset("src"), timeout=Duration.seconds(10), architecture=_lambda.Architecture.ARM_64, environment={"TABLE": table.table_name}) table.grant_read_write_data(fn) # creates the least-privilege IAM policy for you api = apigw.HttpApi(self, "Api") api.add_routes(path="/orders", methods=[apigw.HttpMethod.POST], integration=HttpLambdaIntegration("Int", fn)) app = App() OrdersStack(app, "OrdersStack") app.synth()
bash pm install -g aws-cdk cdk init app --language python cdk bootstrap aws://111111111111/ap-south-1 # one time per account and Region: creates the toolkit stack (S3 bucket, roles) cdk synth # show the CloudFormation template cdk diff # compare with the deployed stack cdk deploy --require-approval broadening # asks for approval when security-sensitive changes appear cdk destroy
  • Bootstrap is required before the first deployment in each account and Region
  • grant* methods write IAM policies for you. This is a big productivity and safety win
  • The CDK assertions library (Template.from_stack) lets you unit test the generated template. Use cdk-nag for security rule checks
  • CDK Pipelines builds self-mutating CI/CD pipelines
  • Use **cdk watch and hotswap** for fast development only

SAM vs CDK Quick Guide

Choose SAM whenChoose CDK when
You build a mostly serverless app and want local invoke and API emulation, simple YAMLYou want loops, abstractions, reuse and type checks, or you manage VPCs, ECS, EKS, pipelines and more
Your team likes declarative templatesYour team prefers writing code in TypeScript or Python

They combine: CDK can include SAM constructs and use sam local against the synthesized template.

Practice Tasks

  1. Create a SAM app with sam init, run it locally and deploy it
  2. Add a canary deployment with an alarm and trigger a rollback by returning an error
  3. Use sam sync --watch to update the function code quickly
  4. Create the same stack in CDK, run cdk diff after a change
  5. Write a CDK assertion test that checks the table has point-in-time recovery enabled

Conclusion

SAM gives short serverless templates, local testing and gradual deployments, then deploys through CloudFormation. CDK lets you define any AWS infrastructure in a programming language using L1, L2 and L3 constructs, needs bootstrapping, and also synthesizes to CloudFormation. Use change sets or cdk diff before production changes.

Quick Summary: tool choice; SAM resources + template; SAM CLI; CDK concepts + code; CDK CLI; SAM vs CDK.

Get Newsletter

Subscibe to our newsletter and we will notify you about the newest updates on Edugators