AWS SAM CLI — Complete Tutorial from Basics to Advanced

AWS SAM CLI is a command-line tool used to create, build, test, debug, package, deploy, monitor, sync, and delete serverless applications on AWS. SAM stands for Serverless Application Model. AWS SAM itself is an open-source infrastructure-as-code framework built on top of AWS CloudFormation, and the SAM CLI is the developer tool you run locally. (AWS Documentation)

In simple words:

AWS SAM = the serverless framework/template syntax
AWS SAM CLI = the command-line tool used to work with SAM projects


1. What is AWS SAM CLI?

AWS SAM CLI helps you work with serverless applications that commonly include:

  • AWS Lambda
  • Amazon API Gateway
  • Amazon DynamoDB
  • Amazon SQS
  • Amazon SNS
  • Amazon EventBridge
  • AWS Step Functions / durable workflows
  • Lambda layers
  • Lambda container images
  • IAM permissions
  • CloudFormation stacks

AWS SAM templates use simplified syntax for serverless resources. During deployment, SAM transforms that template into CloudFormation resources. (AWS Documentation)

For example, instead of writing a very large CloudFormation template for Lambda + API Gateway, SAM lets you write a smaller AWS::Serverless::Function resource.


2. Why use AWS SAM CLI?

Use AWS SAM CLI because it gives you a practical local-to-cloud workflow:

sam init
sam build
sam local invoke
sam local start-api
sam deploy --guided
sam logs
sam delete

AWS describes the core SAM CLI workflow as creating, building, testing, deploying, and syncing serverless applications. (AWS Documentation)

The big advantages are:

BenefitExplanation
Local testingRun Lambda functions and API Gateway-style endpoints locally before deploying.
Infrastructure as codeDefine Lambda, API Gateway, DynamoDB, permissions, outputs, and parameters in template.yaml.
Faster developmentUse sam sync --watch to push local changes quickly to a development stack.
CloudFormation compatibilitySAM becomes CloudFormation during deployment, so you still get stacks, change sets, rollback, outputs, and drift-style IaC benefits.
Beginner-friendly serverlessLess boilerplate than raw CloudFormation for common Lambda/API workloads.
CI/CD supportSAM can generate pipeline configuration and bootstrap deployment resources.

3. Common AWS SAM CLI use cases

AWS SAM is useful for:

  1. REST APIs / HTTP APIs
    Example: API Gateway route /hello invokes a Lambda function.
  2. Event-driven processing
    Example: S3 upload triggers Lambda; SQS message triggers Lambda; EventBridge schedule triggers Lambda.
  3. Serverless CRUD apps
    Example: API Gateway + Lambda + DynamoDB.
  4. Background jobs
    Example: scheduled reports, file processing, async queue workers.
  5. Local Lambda testing
    Example: invoke a Lambda function with a fake S3/SQS/API Gateway event.
  6. Multi-environment deployments
    Example: dev, staging, and prod stacks with different parameters.
  7. CI/CD deployment pipelines
    Example: GitHub Actions, GitLab CI, Bitbucket Pipelines, AWS CodePipeline.
  8. Migration from console-created serverless apps
    AWS mentions SAM as useful when moving console-created Lambda/API Gateway resources into infrastructure as code. (AWS Documentation)

4. AWS SAM vs AWS SAM CLI vs CloudFormation vs CDK

ToolWhat it isBest for
AWS SAMServerless IaC frameworkDeclarative serverless apps
AWS SAM CLILocal CLI toolBuild, test, deploy, sync, debug
CloudFormationGeneral AWS IaC serviceAny AWS infrastructure
AWS CDKProgrammatic IaCDevelopers who prefer TypeScript/Python/Java/etc.
Serverless FrameworkThird-party frameworkMulti-cloud or plugin-heavy workflows

Use SAM when you want CloudFormation-compatible IaC with a simpler serverless syntax. AWS says SAM is useful when you want simplified serverless development while keeping CloudFormation power. (AWS Documentation)


5. Prerequisites

Before using AWS SAM CLI, you need:

  1. An AWS account
  2. IAM credentials or IAM Identity Center access
  3. AWS CLI installed
  4. AWS credentials configured
  5. AWS SAM CLI installed
  6. Docker installed, if you want local Lambda-like containers or sam build --use-container (AWS Documentation)

AWS recommends temporary credentials where possible instead of long-term access keys. (AWS Documentation)


6. Install AWS CLI

Install AWS CLI first, then configure credentials.

Check installation:

aws --version

Configure credentials using the standard AWS CLI flow:

aws configure

You will be asked for:

AWS Access Key ID
AWS Secret Access Key
Default region name
Default output format

Example:

aws configure

Suggested default output format:

json

Check whether AWS credentials work:

aws sts get-caller-identity

If this returns your AWS account/user/role info, your AWS CLI credentials are working.


7. Install Docker

Docker is needed for the best local testing experience. AWS SAM can use Docker to provide a local environment similar to AWS Lambda. Docker is required for local testing and for sam build --use-container. (AWS Documentation)

Check Docker:

docker --version
docker ps

If docker ps fails, Docker may not be running.


8. Install AWS SAM CLI

Linux

Example official installer flow:

unzip aws-sam-cli-linux-x86_64.zip -d sam-installation
sudo ./sam-installation/install
sam --version

AWS provides separate installers for Linux x86_64 and arm64. (AWS Documentation)

macOS

For macOS, AWS provides .pkg installers for Intel and Apple Silicon. AWS notes that the old AWS-managed Homebrew installer aws/tap/aws-sam-cli is no longer maintained by AWS. (AWS Documentation)

Verify:

which sam
sam --version

Windows

Install the Windows MSI package, then open a new PowerShell or Command Prompt and run:

sam --version

AWS documents Windows installation using MSI files. (AWS Documentation)


9. Verify the full setup

Run:

aws --version
sam --version
docker --version
aws sts get-caller-identity

Expected result:

  • aws --version shows AWS CLI version
  • sam --version shows SAM CLI version
  • docker --version shows Docker version
  • aws sts get-caller-identity returns AWS account identity

10. Basic AWS SAM project structure

When you run:

sam init

SAM creates a project directory. AWS says sam init creates a SAM template, organized folder structure, and Lambda function configuration. (AWS Documentation)

Typical structure:

sam-app/
├── README.md
├── events/
│   └── event.json
├── hello_world/
│   ├── app.py
│   └── requirements.txt
├── tests/
├── template.yaml
└── samconfig.toml

Important files:

File/folderPurpose
template.yamlMain SAM infrastructure template
hello_world/Lambda function source code
events/Sample event JSON files for local testing
tests/Unit tests
samconfig.tomlSaved SAM CLI configuration
.aws-sam/Build output directory created by sam build

11. Create your first SAM application

Run:

sam init

You will get an interactive wizard. Choose something like:

Template source: AWS Quick Start Templates
Application template: Hello World Example
Runtime: Python / Node.js / Java / .NET / Go
Package type: Zip

Then enter the project:

cd sam-app

12. Understand template.yaml

A basic SAM template looks like this:

AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Description: Basic AWS SAM application

Globals:
  Function:
    Timeout: 10
    MemorySize: 128
    Runtime: python3.12

Resources:
  HelloWorldFunction:
    Type: AWS::Serverless::Function
    Properties:
      CodeUri: hello_world/
      Handler: app.lambda_handler
      Events:
        HelloApi:
          Type: Api
          Properties:
            Path: /hello
            Method: get

Outputs:
  HelloWorldApi:
    Description: API Gateway endpoint URL
    Value: !Sub "https://${ServerlessRestApi}.execute-api.${AWS::Region}.amazonaws.com/Prod/hello/"

Key parts:

SectionMeaning
TransformRequired SAM transform declaration
GlobalsShared configuration inherited by resources
ResourcesAWS resources to create
AWS::Serverless::FunctionSAM shorthand for Lambda function and event mapping
EventsTriggers for the Lambda function
OutputsValues printed after deployment

SAM templates closely follow CloudFormation templates, but add SAM-specific sections such as the required transform and Globals. (AWS Documentation)


13. Basic Lambda function code

Example Python Lambda handler:

import json

def lambda_handler(event, context):
    return {
        "statusCode": 200,
        "headers": {
            "Content-Type": "application/json"
        },
        "body": json.dumps({
            "message": "Hello from AWS SAM CLI!"
        })
    }

The handler name in template.yaml must match:

Handler: app.lambda_handler

That means:

file: app.py
function: lambda_handler

Tiny mismatch here = classic Lambda faceplant. Ask me how every developer learns this. Painfully.


14. Build the application

Run:

sam build

This prepares the application for local testing or deployment. AWS describes sam build as preparing an application for later developer workflow steps such as local testing or cloud deployment. (AWS Documentation)

After build, SAM creates:

.aws-sam/

You usually do not edit .aws-sam manually.

Use container-based build:

sam build --use-container

Use this when you want dependencies built inside a Lambda-like environment.


15. Invoke Lambda locally

Use a sample event file:

sam local invoke HelloWorldFunction --event events/event.json

Or invoke with an empty event:

sam local invoke HelloWorldFunction

Generate a test event:

sam local generate-event apigateway aws-proxy > events/api-event.json

Then invoke:

sam local invoke HelloWorldFunction --event events/api-event.json

16. Run API Gateway locally

Start local API:

sam local start-api

Then call it:

curl http://127.0.0.1:3000/hello

Use custom port:

sam local start-api --port 4000

Then:

curl http://127.0.0.1:4000/hello

AWS SAM local testing lets you test before uploading to AWS, which helps catch issues earlier and avoid unnecessary deployment/debugging cost. (AWS Documentation)


17. Validate the SAM template

Run:

sam validate

For stricter lint-style validation:

sam validate --lint

Use this before deployment, especially in CI/CD.


18. Deploy for the first time

Use guided deployment:

sam deploy --guided

AWS recommends sam deploy --guided for the first deployment because it prompts for deployment settings and saves them into samconfig.toml. (AWS Documentation)

Typical prompts:

Stack Name: sam-app
AWS Region: us-east-1
Confirm changes before deploy: Y
Allow SAM CLI IAM role creation: Y
Disable rollback: N
Save arguments to configuration file: Y

After this, future deployments are usually:

sam build
sam deploy

19. What happens during deployment?

When you deploy:

  1. SAM packages your Lambda code.
  2. SAM uploads artifacts to S3 or ECR.
  3. SAM creates a CloudFormation change set.
  4. CloudFormation creates or updates your AWS resources.
  5. SAM prints stack outputs.

AWS documents that zip-based Lambda artifacts go to S3, image-based functions go to ECR, and the app is deployed as a CloudFormation stack. (AWS Documentation)


20. Test the deployed API

After deployment, SAM prints outputs. You may see something like:

HelloWorldApi = https://abc123.execute-api.us-east-1.amazonaws.com/Prod/hello/

Test:

curl https://abc123.execute-api.us-east-1.amazonaws.com/Prod/hello/

21. View logs

Basic logs:

sam logs

Logs for a specific function:

sam logs -n HelloWorldFunction

Tail logs:

sam logs -n HelloWorldFunction --tail

Include start time:

sam logs -n HelloWorldFunction --start-time "10min ago"

22. Delete the application

To remove deployed resources:

sam delete

This deletes the CloudFormation stack and related resources that SAM can clean up.


23. The most important everyday workflow

For most developers:

sam init
cd sam-app
sam build
sam local start-api
sam deploy --guided
sam logs --tail
sam delete

For ongoing development:

sam build
sam local invoke HelloWorldFunction
sam deploy

Or for faster cloud development:

sam sync --watch

AWS recommends sam sync for development environments, while production should use sam deploy or CI/CD. (AWS Documentation)


24. samconfig.toml

samconfig.toml stores project-level SAM CLI settings.

Example:

version = 0.1

[default.global.parameters]

stack_name = “sam-app”

[default.build.parameters]

cached = true parallel = true

[default.deploy.parameters]

capabilities = “CAPABILITY_IAM” confirm_changeset = true resolve_s3 = true region = “us-east-1”

SAM config files are usually named samconfig, live at the project root near template.yaml, and commonly use TOML, though YAML/YML is also supported. (AWS Documentation)

Use a different environment:

sam deploy --config-env dev
sam deploy --config-env prod

Example multi-environment config:

version = 0.1

[dev.deploy.parameters]

stack_name = “myapp-dev” region = “us-east-1” capabilities = “CAPABILITY_IAM” resolve_s3 = true

[prod.deploy.parameters]

stack_name = “myapp-prod” region = “us-east-1” capabilities = “CAPABILITY_IAM” resolve_s3 = true confirm_changeset = true

Deploy dev:

sam deploy --config-env dev

Deploy prod:

sam deploy --config-env prod

25. Add environment variables

In template.yaml:

Globals:
  Function:
    Runtime: python3.12
    Timeout: 10
    Environment:
      Variables:
        STAGE: dev
        LOG_LEVEL: info

Inside Python:

import os

stage = os.environ.get("STAGE", "local")

For local testing, create env.json:

{
  "HelloWorldFunction": {
    "STAGE": "local",
    "LOG_LEVEL": "debug"
  }
}

Run:

sam local invoke HelloWorldFunction --env-vars env.json

26. Add API Gateway routes

Example with two routes:

Resources:
  GetUsersFunction:
    Type: AWS::Serverless::Function
    Properties:
      CodeUri: users/
      Handler: app.get_users
      Runtime: python3.12
      Events:
        GetUsersApi:
          Type: Api
          Properties:
            Path: /users
            Method: get

  CreateUserFunction:
    Type: AWS::Serverless::Function
    Properties:
      CodeUri: users/
      Handler: app.create_user
      Runtime: python3.12
      Events:
        CreateUserApi:
          Type: Api
          Properties:
            Path: /users
            Method: post

Local test:

sam build
sam local start-api
curl http://127.0.0.1:3000/users

POST test:

curl -X POST http://127.0.0.1:3000/users \
  -H "Content-Type: application/json" \
  -d '{"name":"Rajesh"}'

27. Add DynamoDB

Example table:

Resources:
  UsersTable:
    Type: AWS::DynamoDB::Table
    Properties:
      TableName: !Sub "${AWS::StackName}-users"
      BillingMode: PAY_PER_REQUEST
      AttributeDefinitions:
        - AttributeName: userId
          AttributeType: S
      KeySchema:
        - AttributeName: userId
          KeyType: HASH

Give Lambda permission:

  CreateUserFunction:
    Type: AWS::Serverless::Function
    Properties:
      CodeUri: users/
      Handler: app.create_user
      Runtime: python3.12
      Environment:
        Variables:
          TABLE_NAME: !Ref UsersTable
      Policies:
        - DynamoDBCrudPolicy:
            TableName: !Ref UsersTable

SAM supports policy templates and connectors to simplify permissions between resources. AWS recommends connectors and policy templates where supported because they reduce the amount of IAM expertise needed. (AWS Documentation)


28. Add SQS event trigger

Resources:
  OrdersQueue:
    Type: AWS::SQS::Queue

  ProcessOrderFunction:
    Type: AWS::Serverless::Function
    Properties:
      CodeUri: orders/
      Handler: app.lambda_handler
      Runtime: python3.12
      Events:
        OrdersQueueEvent:
          Type: SQS
          Properties:
            Queue: !GetAtt OrdersQueue.Arn
            BatchSize: 10
      Policies:
        - SQSPollerPolicy:
            QueueName: !GetAtt OrdersQueue.QueueName

29. Add scheduled EventBridge trigger

Resources:
  DailyJobFunction:
    Type: AWS::Serverless::Function
    Properties:
      CodeUri: jobs/
      Handler: app.lambda_handler
      Runtime: python3.12
      Events:
        DailySchedule:
          Type: Schedule
          Properties:
            Schedule: rate(1 day)

30. Lambda layers

Layer:

Resources:
  CommonLayer:
    Type: AWS::Serverless::LayerVersion
    Properties:
      LayerName: common-utils
      Description: Shared Python utilities
      ContentUri: layers/common/
      CompatibleRuntimes:
        - python3.12

  MyFunction:
    Type: AWS::Serverless::Function
    Properties:
      CodeUri: app/
      Handler: app.lambda_handler
      Runtime: python3.12
      Layers:
        - !Ref CommonLayer

Typical layer folder:

layers/
└── common/
    └── python/
        └── my_utils.py

31. Container image Lambda with SAM

Instead of zip package:

Resources:
  ImageFunction:
    Type: AWS::Serverless::Function
    Properties:
      PackageType: Image
      Timeout: 30
    Metadata:
      Dockerfile: Dockerfile
      DockerContext: ./image-function
      DockerTag: python3.12-v1

Build:

sam build

Deploy:

sam deploy --guided

SAM deploy uploads zip artifacts to S3 and image artifacts to ECR as needed. (AWS Documentation)


32. Faster development with sam sync

First deploy normally:

sam build
sam deploy --guided

Then use:

sam sync --watch

This watches local changes and syncs them to AWS. AWS says sam sync --watch builds, deploys, watches local changes, and syncs changes through the quickest available method. (AWS Documentation)

Use this for development stacks only:

sam sync --stack-name myapp-dev --watch

One-time sync:

sam sync --no-watch

33. Remote testing

Invoke deployed function in AWS:

sam remote invoke HelloWorldFunction --stack-name sam-app

With event file:

sam remote invoke HelloWorldFunction \
  --stack-name sam-app \
  --event-file events/event.json

AWS documents sam remote invoke for interacting with Lambda functions already deployed in the AWS Cloud. (AWS Documentation)


34. Shareable remote test events

List remote test events:

sam remote test-event list HelloWorldFunction --stack-name sam-app

Save local event to AWS:

sam remote test-event put HelloWorldFunction \
  --stack-name sam-app \
  --name demo-event \
  --file events/event.json

Invoke using saved event:

sam remote invoke HelloWorldFunction \
  --stack-name sam-app \
  --test-event-name demo-event

AWS documents sam remote test-event subcommands for delete, get, list, and put. (AWS Documentation)


35. CI/CD with SAM pipeline

Bootstrap deployment resources:

sam pipeline bootstrap

Generate pipeline config:

sam pipeline init

AWS says sam pipeline bootstrap sets up infrastructure resources needed for CI/CD deployment, and sam pipeline init generates pipeline configuration for your CI/CD system. (AWS Documentation)

Typical flow:

sam pipeline bootstrap
sam pipeline init
git add .
git commit -m "Add SAM pipeline"
git push

36. Monitoring and troubleshooting

CloudWatch logs

sam logs -n HelloWorldFunction --stack-name sam-app --tail

X-Ray traces

sam traces

Validate template

sam validate --lint

Confirm deployed resources

sam list resources --stack-name sam-app

Confirm stack outputs

sam list stack-outputs --stack-name sam-app

37. All major AWS SAM CLI commands

The official SAM CLI command reference currently includes these commands and subcommand groups. (AWS Documentation)

CommandPurposeExample
sam initCreate new SAM projectsam init
sam buildBuild app artifactssam build
sam validateValidate SAM templatesam validate --lint
sam local generate-eventGenerate sample event payloadssam local generate-event s3 put
sam local invokeInvoke Lambda locallysam local invoke MyFunction
sam local start-apiRun local API Gateway-style serversam local start-api
sam local start-lambdaRun local Lambda endpoint for AWS CLI/SDK testingsam local start-lambda
sam local callbackWork with local durable-function callbackssam local callback --help
sam local executionWork with local durable-function executionssam local execution --help
sam deployDeploy app using CloudFormationsam deploy --guided
sam packagePackage app artifacts manuallysam package
sam syncSync local changes to AWS dev stacksam sync --watch
sam logsFetch/tail CloudWatch logssam logs --tail
sam tracesFetch AWS X-Ray tracessam traces
sam listList stack resources/endpoints/outputssam list resources
sam remote invokeInvoke deployed cloud resourcesam remote invoke MyFunction
sam remote test-eventManage shareable Lambda test eventssam remote test-event list MyFunction
sam remote callbackManage callbacks for remote durable executionssam remote callback --help
sam remote executionInspect/manage remote durable executionssam remote execution --help
sam pipeline bootstrapCreate CI/CD deployment resourcessam pipeline bootstrap
sam pipeline initGenerate CI/CD pipeline configsam pipeline init
sam publishPublish app to Serverless Application Repositorysam publish
sam deleteDelete deployed SAM appsam delete

Useful global commands:

sam --version
sam --help
sam <command> --help

Examples:

sam deploy --help
sam local invoke --help
sam sync --help

38. Practical command cheat sheet

Create app

sam init

Build

sam build
sam build --cached
sam build --parallel
sam build --use-container

Test locally

sam local invoke FunctionName
sam local invoke FunctionName --event events/event.json
sam local start-api
sam local start-api --port 4000
sam local generate-event apigateway aws-proxy

Validate

sam validate
sam validate --lint

Deploy

sam deploy --guided
sam deploy
sam deploy --config-env dev
sam deploy --stack-name my-stack --region us-east-1

Sync

sam sync --watch
sam sync --no-watch
sam sync --stack-name myapp-dev --watch

Logs

sam logs
sam logs -n FunctionName
sam logs -n FunctionName --tail
sam logs -n FunctionName --start-time "10min ago"

Remote invoke

sam remote invoke FunctionName --stack-name my-stack
sam remote invoke FunctionName --stack-name my-stack --event-file events/event.json

List

sam list resources --stack-name my-stack
sam list endpoints --stack-name my-stack
sam list stack-outputs --stack-name my-stack

Pipeline

sam pipeline bootstrap
sam pipeline init

Cleanup

sam delete

39. Best practices

1. Always build before deploy

sam build
sam deploy

AWS specifically notes that sam deploy deploys artifacts from .aws-sam, so after changing original files you should run sam build before deploying. (AWS Documentation)

2. Use sam deploy --guided first

First time:

sam deploy --guided

After that:

sam deploy

3. Use sam sync --watch only for development

Good:

sam sync --watch

Not ideal for production. For production, prefer:

sam deploy

or CI/CD.

4. Use least-privilege IAM

Avoid giving every function broad permissions like:

Policies:
  - AdministratorAccess

Prefer scoped policies:

Policies:
  - DynamoDBReadPolicy:
      TableName: !Ref UsersTable

5. Separate environments

Use separate stacks:

myapp-dev
myapp-staging
myapp-prod

6. Keep secrets out of templates

Do not hardcode passwords/API keys in template.yaml.

Prefer:

  • AWS Secrets Manager
  • AWS Systems Manager Parameter Store
  • Environment variables referencing secure values
  • IAM roles

7. Add outputs

Always output useful deployed URLs/resources:

Outputs:
  ApiUrl:
    Value: !Sub "https://${ServerlessRestApi}.execute-api.${AWS::Region}.amazonaws.com/Prod/"

8. Use sam validate --lint in CI

sam validate --lint

9. Delete unused stacks

sam delete

This avoids surprise AWS charges.


40. Beginner project: API Gateway + Lambda

Step 1: Create project

sam init
cd sam-app

Step 2: Build

sam build

Step 3: Run locally

sam local start-api

Step 4: Test

curl http://127.0.0.1:3000/hello

Step 5: Deploy

sam deploy --guided

Step 6: View logs

sam logs -n HelloWorldFunction --tail

Step 7: Cleanup

sam delete

41. Intermediate project: API Gateway + Lambda + DynamoDB

Architecture:

Client
  ↓
API Gateway
  ↓
Lambda
  ↓
DynamoDB

Template idea:

Resources:
  UsersTable:
    Type: AWS::DynamoDB::Table
    Properties:
      BillingMode: PAY_PER_REQUEST
      AttributeDefinitions:
        - AttributeName: userId
          AttributeType: S
      KeySchema:
        - AttributeName: userId
          KeyType: HASH

  CreateUserFunction:
    Type: AWS::Serverless::Function
    Properties:
      CodeUri: users/
      Handler: app.create_user
      Runtime: python3.12
      Environment:
        Variables:
          TABLE_NAME: !Ref UsersTable
      Policies:
        - DynamoDBCrudPolicy:
            TableName: !Ref UsersTable
      Events:
        CreateUserApi:
          Type: Api
          Properties:
            Path: /users
            Method: post

Deploy:

sam build
sam deploy --guided

42. Advanced project: Async queue worker

Architecture:

API Gateway
  ↓
SubmitOrderFunction
  ↓
SQS Queue
  ↓
ProcessOrderFunction

This pattern is good for long-running or retryable work.

Key benefits:

  • API responds quickly
  • SQS buffers work
  • Lambda processes asynchronously
  • Failed messages can go to a dead-letter queue

43. Common errors and fixes

Error: Docker is not running

Fix:

docker ps

Start Docker Desktop or Docker daemon.

Error: Unable to locate credentials

Fix:

aws configure
aws sts get-caller-identity

Error: Handler not found

Check:

Handler: app.lambda_handler

Must match:

app.py
lambda_handler()

Error: Runtime mismatch

If template says:

Runtime: python3.12

Make sure local build has compatible Python, or use:

sam build --use-container

Error: IAM role creation not allowed

Deploy with:

sam deploy --guided

When prompted:

Allow SAM CLI IAM role creation: Y

The deployment may require:

CAPABILITY_IAM

Error: Stack already exists

Use a different stack name:

sam deploy --guided

or delete the old one:

sam delete

44. Recommended learning path

Follow this order:

  1. Learn Lambda basics.
  2. Learn API Gateway basics.
  3. Install AWS CLI, Docker, and SAM CLI.
  4. Run sam init.
  5. Understand template.yaml.
  6. Run sam build.
  7. Run sam local invoke.
  8. Run sam local start-api.
  9. Deploy with sam deploy --guided.
  10. Read logs with sam logs.
  11. Add DynamoDB.
  12. Add SQS/EventBridge triggers.
  13. Use multiple environments.
  14. Use sam sync --watch.
  15. Add CI/CD with sam pipeline.
  16. Practice cleanup with sam delete.

45. Final mental model

Think of AWS SAM CLI like this:

template.yaml       = What AWS resources should exist
function code       = What your Lambda does
sam build           = Prepare code and dependencies
sam local invoke    = Test Lambda locally
sam local start-api = Test API locally
sam deploy          = Create/update AWS resources
sam logs            = Debug deployed Lambda
sam sync            = Fast dev loop against AWS
sam delete          = Clean up

The normal professional workflow is:

sam init
sam build
sam local invoke
sam local start-api
sam deploy --guided
sam logs --tail
sam sync --watch
sam delete

That’s the core of AWS SAM CLI: local development, infrastructure as code, repeatable deployment, and serverless debugging without living inside the AWS Console all day.

Related Posts

Amazon Q Developer Complete Tutorial: From Basics to Advanced

1. Introduction Amazon Q Developer is AWS’s generative AI assistant for developers, cloud engineers, DevOps engineers, security engineers, and anyone building applications on AWS. It helps you…

Read More

Dynatrace Query Language Tutorial: Complete Step-by-Step DQL Guide from Basics to Advanced Observability Queries

Dynatrace Query Language, or DQL, is the query language used to explore, filter, aggregate, correlate, and visualize data stored in Dynatrace Grail. Dynatrace describes DQL as a…

Read More

Notion MCP Access Control: How to Secure Teamspaces, Permissions, and AI Client Access

A Notion teamspace is not usually “enabled for MCP” by itself.Instead, access is controlled by two layers: So if your IT team approves ChatGPT as an MCP…

Read More

Complete Tutorial: MCP and Notion MCP, Explained Step by Step

Complete Tutorial: MCP and Notion MCP, Explained Step by Step MCP means Model Context Protocol. Think of it as a standard “connector language” that lets AI tools…

Read More

HashiCorp Vault: Step-by-Step Tutorial: Vault CLI on Linux — KV Secrets, Userpass Auth, Policy, and CRUD

This lab uses Vault CLI on Linux and demonstrates the full flow: Vault’s kv command works with both KV v1 and KV v2, but for KV v2…

Read More

Low-Level Authentication Flow Design for Student, Trainer, and Consultant Services Using Keycloak

Yes — the clean low-level flow should use Keycloak as the central Identity Provider, and Student / Trainer / Consultant services should never handle passwords directly. Recommended…

Read More