Skip to content

feat: allow explicit listing of function ids for local start-lambda command#8392

Merged
vicheey merged 11 commits into
developfrom
feat-allow-specifying-functions-local-start-command
Nov 11, 2025
Merged

feat: allow explicit listing of function ids for local start-lambda command#8392
vicheey merged 11 commits into
developfrom
feat-allow-specifying-functions-local-start-command

Conversation

@vicheey

@vicheey vicheey commented Nov 3, 2025

Copy link
Copy Markdown
Contributor

Summary

Which issue(s) does this change fix?

Enables developers to specify a subset of Lambda functions from the template when starting local development servers.

Why is this change necessary?

This is for improving development efficiency by reducing resource usage and startup time for large SAM applications.
When working with SAM templates containing many Lambda functions, developers often only need to test a few functions at a time. Currently, sam local start-lambda initialize containers for ALL functions in the template when using --warm-containers EAGER, which:

  • Consumes unnecessary system resources (memory, CPU, disk)
  • Increases startup time
  • Makes local development slower and less efficient

This change allows developers to specify exactly which functions they want to work with, similar to how they can already target specific functions with sam local invoke.

How does it address the issue?

Adds function name filtering capability to sam local start-lambda commands so that users can now run sam local start-lambda Function1 Function2

CLI Changes

  1. InvokeContext (invoke_context.py):
    • Accepts function_logical_ids parameter
    • Validates function names exist in template
    • Passes function logical id list to function and API providers
  2. SamFunctionProvider (sam_function_provider.py):
    • Filters functions during extraction based on provided names
    • Matches against function_id, name, and FunctionName property
    • Maintains filter during template refresh in warm container mode

Testing

  • Added unit tests for modified components
  • Added integration tests for both start-lambda and start-api commands with explicit function list
  • Tests cover validation, filtering, warm/cold containers, and error cases
  • Updated existing unit tests to work with new parameter

What side effects does this change have?

Additive Feature

  • Reduced memory and CPU usage when working with subset of functions
  • Faster startup time for local development servers
  • Better developer experience for large SAM applications
  • Function name validation happens at startup (fails fast with clear error)
  • File watcher still monitors entire template (necessary for detecting structural changes)
  • Only specified functions have containers initialized and code watched

Backward compatibility

  • Additive feature and fully backward compatible - existing workflows unchanged

Mandatory Checklist

Integration Tests

PRs will only be reviewed after checklist is complete


Help Document Update sam local start-lambda --help

🕐 15:01:41 ❯ samdev local start-lambda --help                                                                                                    
2025-11-10 15:02:00 Attaching import module proxy for analyzing dynamic imports
Usage: samdev local start-lambda [OPTIONS] [FUNCTION_LOGICAL_IDS]...

  Emulate AWS serverless functions locally.

Description:
    
  Programmatically invoke your Lambda function locally using the AWS CLI or SDKs.
  Start a local endpoint that emulates the AWS Lambda service, and one can run their automated
  tests against this local Lambda endpoint. Invokes to this endpoint can be sent using the AWS CLI or
  SDK and they will in turn locally execute the Lambda function specified in the request.


  This command may not require access to AWS credentials.
                                    

Examples:

    Setup:
                                        
        Start the local lambda endpoint for all functions
                                        
        $ samdev local start-lambda     
                                        
        Start the local lambda endpoint for one function
                                        
        $ samdev local start-lambda HelloWorldFunction
                                        
                                        
        Start the local lambda endpoint for multiple functions
                                        
        $ samdev local start-lambda HelloWorldFunctionOne HelloWorldFunctionTwo
                                        

    Invoke local Lambda endpoint:
                                        
        Use the AWS CLI.                
        $ aws lambda invoke --function-name HelloWorldFunction --endpoint-url http://127.0.0.1:3001 --no-verify-ssl out.txt
                                        
                                        
        Use AWS SDK in automated tests.
                                        
        
        self.lambda_client = boto3.client('lambda',
                                          endpoint_url="http://127.0.0.1:3001",
                                          use_ssl=False,
                                          verify=False,
                                          config=Config(signature_version=UNSIGNED,
                                                        read_timeout=0,
                                                        retries={'max_attempts': 0}))
        self.lambda_client.invoke(FunctionName="HelloWorldFunction")
        
                                        

Required Options:
                                    
                                    
    -t,--template,--template-file   AWS SAM template which references built artifacts for resources in the template. (if
                                    applicable)  [default: template.[yaml|yml|json]]
                                    

Template Options:
                                    
                                    
    --parameter-overrides STRING,LIST
                                    String that contains AWS CloudFormation parameter overrides encoded as key=value
                                    pairs.
                                    

AWS Credential Options:
                                    
                                    
    --region TEXT                   Set the AWS Region of the service. (e.g. us-east-1)
                                    
    --profile TEXT                  Select a specific profile from your credential file to get AWS credentials.
                                    

Container Options:
                                    
                                    
    --host TEXT                     Local hostname or IP address to bind to (default: '127.0.0.1')
                                    
    -p, --port INTEGER              Local port number to listen on (default: '3001')
                                    
    -n, --env-vars PATH             JSON file containing values for Lambda function's environment variables.
                                    
    --warm-containers [EAGER|LAZY]  Optional. Specifies how AWS SAM CLI manages 
                                    containers for each function.
                                    Two modes are available:
                                    EAGER: Containers for all functions are 
                                    loaded at startup and persist between 
                                    invocations.
                                    LAZY:  Containers are only loaded when each 
                                    function is first invoked. Those containers 
                                    persist for additional invocations.
                                    
    --container-env-vars PATH       JSON file containing additional environment variables to be set within the container
                                    when used in a debugging session locally.
                                    
    --debug-function TEXT           Optional. Specifies the Lambda Function logicalId to apply debug options to when
                                    --warm-containers is specified. This parameter applies to --debug-port, --debugger-
                                    path, and --debug-args.
                                    
    -d, --debug-port INTEGER        When specified, Lambda function container will start in debug mode and will expose
                                    this port on localhost.
                                    
    --debugger-path TEXT            Host path to a debugger that will be mounted into the Lambda container.
                                    
    --debug-args TEXT               Additional arguments to be passed to the debugger.
                                    
    -v, --docker-volume-basedir TEXT
                                    Specify the location basedir where the SAM template exists. If Docker is running on
                                    a remote machine, Path of the SAM template must be mounted on the Docker machine and
                                    modified to match the remote machine.
                                    
    --skip-pull-image               Skip pulling down the latest Docker image for Lambda runtime.
                                    
    --docker-network TEXT           Name or ID of an existing docker network for AWS Lambda docker containers to connect
                                    to, along with the default bridge network. If not specified, the Lambda containers
                                    will only connect to the default bridge docker network.
                                    
    --force-image-build             Force rebuilding the image used for invoking functions with layers.
                                    
    --shutdown                      Emulate a shutdown event after invoke completes, to test extension handling of
                                    shutdown behavior.
                                    
    --container-host TEXT           Host of locally emulated Lambda container. This option is useful when the container
                                    runs on a different host than AWS SAM CLI. For example, if one wants to run AWS SAM
                                    CLI in a Docker container on macOS, this option could specify `host.docker.internal`
                                    [default: localhost]
                                    
    --container-host-interface TEXT
                                    IP address of the host network interface that container ports should bind to. Use
                                    0.0.0.0 to bind to all interfaces.  [default: 127.0.0.1]
                                    
    --add-host LIST                 Passes a hostname to IP address mapping to the Docker container's host file. This
                                    parameter can be passed multiple times.Example:--add-host example.com:127.0.0.1
                                    
    -ii, --invoke-image TEXT        Container image URIs for invoking functions or starting api and function. One can
                                    specify the image URI used for the local function invocation (--invoke-image
                                    public.ecr.aws/sam/build-nodejs20.x:latest). One can also specify for each
                                    individual function with (--invoke-image Function1=public.ecr.aws/sam/build-
                                    nodejs20.x:latest). If a function does not have invoke image specified, the default
                                    AWS SAM CLI emulation image will be used.
                                    
    --no-memory-limit               Removes the Memory limit during emulation. With this parameter, the underlying
                                    container will run without a --memory parameter
                                    

Artifact Location Options:
                                    
                                    
    -l, --log-file TEXT             File to capture output logs.
                                    
    --layer-cache-basedir DIRECTORY
                                    Specify the location basedir where the lambda layers used by the template will be
                                    downloaded to.
                                    

Extension Options:
                                    
                                    
    --hook-name TEXT                Hook package id to extend AWS SAM CLI commands functionality.
                                    
                                    Example: `terraform` to extend AWS SAM CLI commands functionality to support
                                    terraform applications.
                                    
                                    Available Hook Names: ['terraform']
                                    
    --skip-prepare-infra / --prepare-infra
                                    Skip preparation stage when there are no infrastructure changes. Only used in
                                    conjunction with --hook-name.
                                    

Configuration Options:
    Learn more about configuration files at:
                                    
    https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-cli-config.html. 
                                    
                                    
    --config-env TEXT               Environment name specifying default parameter values in the configuration file.
                                    [default: default]
                                    
    --config-file TEXT              Configuration file containing default parameter values.  [default: samconfig.toml]
                                    
    --save-params                   Save the parameters provided via the command line to the configuration file.
                                    

Terraform Hook Options:
                                    
                                    
    --terraform-plan-file PATH      Used for passing a custom plan file when executing the Terraform hook.
                                    

Beta Options:
                                    
                                    
    --beta-features / --no-beta-features
                                    Enable/Disable beta features.
                                    

Other Options:
                                    
                                    
    --debug                         Turn on debug logging to print debug message generated by AWS SAM CLI and display
                                    timestamps.
                                    
    -h, --help                      Show this message and exit.
                                    

Help Document Update sam local start-api --help

🕐 15:02:01 ❯ samdev local start-api --help   
2025-11-10 15:03:57 Attaching import module proxy for analyzing dynamic imports
Usage: samdev local start-api [OPTIONS]

  Run & test AWS serverless functions locally as a HTTP API.

Description:
    
  Allows one to run their Serverless application locally for quick development & testing.
  When run in a directory that contains Serverless functions and an AWS SAM template, it will create a local HTTP
  server hosting all of template's functions. When accessed (via browser, cli etc), it will launch a Docker container
  locally to invoke the function. 
  
  It will read the CodeUri property of AWS::Serverless::Function resource to find the path in the file system 
  containing the Lambda Function code. This could be the project's root directory for interpreted
  languages like Node & Python, or a build directory that stores your compiled artifacts or a JAR file. If one uses
  a interpreted language, local changes will be available immediately in Docker container on every invoke. For more
  compiled languages or projects requiring complex packing support, it is recommended to run custom building solution
  and point AWS SAM CLI to the directory or file containing build artifacts.

  This command may not require access to AWS credentials.
                                    

Examples:

    Setup:
                                        
        Start the local lambda with Amazon API Gateway endpoint
                                        
        $ samdev local start-api        

    Invoke local Lambda endpoint:
                                        
        Invoke Lambda function locally using curl
                                        
        $ curl http://127.0.0.1:3000/hello
                                        

Required Options:
                                    
                                    
    -t,--template,--template-file   AWS SAM template which references built artifacts for resources in the template. (if
                                    applicable)  [default: template.[yaml|yml|json]]
                                    

Template Options:
                                    
                                    
    --parameter-overrides STRING,LIST
                                    String that contains AWS CloudFormation parameter overrides encoded as key=value
                                    pairs.
                                    

AWS Credential Options:
                                    
                                    
    --region TEXT                   Set the AWS Region of the service. (e.g. us-east-1)
                                    
    --profile TEXT                  Select a specific profile from your credential file to get AWS credentials.
                                    

Container Options:
                                    
                                    
    --host TEXT                     Local hostname or IP address to bind to (default: '127.0.0.1')
                                    
    -p, --port INTEGER              Local port number to listen on (default: '3000')
                                    
    --ssl-cert-file PATH            Path to SSL certificate file (default: None)
                                    
    --ssl-key-file PATH             Path to SSL key file (default: None)
                                    
    -n, --env-vars PATH             JSON file containing values for Lambda function's environment variables.
                                    
    --container-env-vars PATH       JSON file containing additional environment variables to be set within the container
                                    when used in a debugging session locally.
                                    
    -d, --debug-port INTEGER        When specified, Lambda function container will start in debug mode and will expose
                                    this port on localhost.
                                    
    --debugger-path TEXT            Host path to a debugger that will be mounted into the Lambda container.
                                    
    --debug-args TEXT               Additional arguments to be passed to the debugger.
                                    
    --debug-function TEXT           Optional. Specifies the Lambda Function logicalId to apply debug options to when
                                    --warm-containers is specified. This parameter applies to --debug-port, --debugger-
                                    path, and --debug-args.
                                    
    -v, --docker-volume-basedir TEXT
                                    Specify the location basedir where the SAM template exists. If Docker is running on
                                    a remote machine, Path of the SAM template must be mounted on the Docker machine and
                                    modified to match the remote machine.
                                    
    --skip-pull-image               Skip pulling down the latest Docker image for Lambda runtime.
                                    
    --docker-network TEXT           Name or ID of an existing docker network for AWS Lambda docker containers to connect
                                    to, along with the default bridge network. If not specified, the Lambda containers
                                    will only connect to the default bridge docker network.
                                    
    --force-image-build             Force rebuilding the image used for invoking functions with layers.
                                    
    --no-memory-limit               Removes the Memory limit during emulation. With this parameter, the underlying
                                    container will run without a --memory parameter
                                    
    --warm-containers [EAGER|LAZY]  Optional. Specifies how AWS SAM CLI manages 
                                    containers for each function.
                                    Two modes are available:
                                    EAGER: Containers for all functions are 
                                    loaded at startup and persist between 
                                    invocations.
                                    LAZY:  Containers are only loaded when each 
                                    function is first invoked. Those containers 
                                    persist for additional invocations.
                                    
    --shutdown                      Emulate a shutdown event after invoke completes, to test extension handling of
                                    shutdown behavior.
                                    
    --container-host TEXT           Host of locally emulated Lambda container. This option is useful when the container
                                    runs on a different host than AWS SAM CLI. For example, if one wants to run AWS SAM
                                    CLI in a Docker container on macOS, this option could specify `host.docker.internal`
                                    [default: localhost]
                                    
    --container-host-interface TEXT
                                    IP address of the host network interface that container ports should bind to. Use
                                    0.0.0.0 to bind to all interfaces.  [default: 127.0.0.1]
                                    
    --add-host LIST                 Passes a hostname to IP address mapping to the Docker container's host file. This
                                    parameter can be passed multiple times.Example:--add-host example.com:127.0.0.1
                                    
    -ii, --invoke-image TEXT        Container image URIs for invoking functions or starting api and function. One can
                                    specify the image URI used for the local function invocation (--invoke-image
                                    public.ecr.aws/sam/build-nodejs20.x:latest). One can also specify for each
                                    individual function with (--invoke-image Function1=public.ecr.aws/sam/build-
                                    nodejs20.x:latest). If a function does not have invoke image specified, the default
                                    AWS SAM CLI emulation image will be used.
                                    
    --disable-authorizer            Disable custom Lambda Authorizers from being parsed and invoked.
                                    

Artifact Location Options:
                                    
                                    
    -l, --log-file TEXT             File to capture output logs.
                                    
    --layer-cache-basedir DIRECTORY
                                    Specify the location basedir where the lambda layers used by the template will be
                                    downloaded to.
                                    
    -s, --static-dir TEXT           Any static assets (e.g. CSS/Javascript/HTML) files located in this directory will be
                                    presented at /
                                    

Extension Options:
                                    
                                    
    --hook-name TEXT                Hook package id to extend AWS SAM CLI commands functionality.
                                    
                                    Example: `terraform` to extend AWS SAM CLI commands functionality to support
                                    terraform applications.
                                    
                                    Available Hook Names: ['terraform']
                                    
    --skip-prepare-infra / --prepare-infra
                                    Skip preparation stage when there are no infrastructure changes. Only used in
                                    conjunction with --hook-name.
                                    

Configuration Options:
    Learn more about configuration files at:
                                    
    https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-cli-config.html. 
                                    
                                    
    --config-env TEXT               Environment name specifying default parameter values in the configuration file.
                                    [default: default]
                                    
    --config-file TEXT              Configuration file containing default parameter values.  [default: samconfig.toml]
                                    
    --save-params                   Save the parameters provided via the command line to the configuration file.
                                    

Terraform Hook Options:
                                    
                                    
    --terraform-plan-file PATH      Used for passing a custom plan file when executing the Terraform hook.
                                    

Beta Options:
                                    
                                    
    --beta-features / --no-beta-features
                                    Enable/Disable beta features.
                                    

Other Options:
                                    
                                    
    --debug                         Turn on debug logging to print debug message generated by AWS SAM CLI and display
                                    timestamps.
                                    
    -h, --help                      Show this message and exit.

By submitting this pull request, I confirm that my contribution is made under the terms of the Apache 2.0 license.

@vicheey
vicheey marked this pull request as ready for review November 3, 2025 21:06
@vicheey
vicheey requested a review from a team as a code owner November 3, 2025 21:06
@vicheey vicheey changed the title feat: allow explicit listing of function ids for local start-* command feat: allow explicit listing of function ids for local start-lambda command Nov 4, 2025
@vicheey
vicheey force-pushed the feat-allow-specifying-functions-local-start-command branch from c100003 to 3b5fbbb Compare November 4, 2025 01:28
Comment thread samcli/commands/local/cli_common/invoke_context.py Outdated
Comment thread samcli/commands/local/cli_common/invoke_context.py Outdated
Comment thread samcli/commands/local/cli_common/invoke_context.py
Comment thread samcli/commands/local/cli_common/user_exceptions.py Outdated
Comment thread samcli/commands/local/start_lambda/cli.py
Comment thread samcli/lib/providers/sam_function_provider.py
Comment thread samcli/lib/providers/sam_function_provider.py
Comment thread tests/integration/local/start_lambda/test_start_lambda.py Outdated
Comment thread tests/integration/local/start_lambda/test_start_lambda.py Outdated
tobixlea
tobixlea previously approved these changes Nov 5, 2025
Comment thread samcli/commands/local/cli_common/invoke_context.py Outdated
Comment thread samcli/commands/local/cli_common/invoke_context.py Outdated
Comment thread samcli/commands/local/cli_common/invoke_context.py
Comment thread samcli/commands/local/cli_common/user_exceptions.py Outdated
Comment thread samcli/commands/local/start_lambda/cli.py
Comment thread samcli/commands/local/start_lambda/cli.py
Comment thread samcli/lib/providers/sam_function_provider.py
@tobixlea
tobixlea requested review from licjun and tobixlea November 6, 2025 19:05
Comment thread samcli/lib/providers/sam_function_provider.py
Comment thread tests/integration/local/start_lambda/test_start_lambda.py Outdated
Comment thread tests/integration/local/start_lambda/test_start_lambda.py Outdated
Comment thread tests/integration/local/start_lambda/test_start_lambda.py Outdated
Comment thread tests/unit/commands/local/cli_common/test_invoke_context.py Outdated
Comment thread tests/unit/commands/local/cli_common/test_invoke_context.py Outdated
Comment thread tests/unit/commands/local/cli_common/test_invoke_context.py Outdated
Comment thread tests/unit/commands/local/lib/test_sam_function_provider.py
@vicheey
vicheey requested a review from valerena November 11, 2025 17:11
licjun
licjun previously approved these changes Nov 11, 2025
tobixlea
tobixlea previously approved these changes Nov 11, 2025
Comment thread tests/integration/local/start_lambda/test_start_lambda.py Outdated
@vicheey
vicheey dismissed stale reviews from tobixlea and licjun via 72aacfb November 11, 2025 20:01
@vicheey
vicheey requested a review from licjun November 11, 2025 20:46
@vicheey
vicheey requested a review from tobixlea November 11, 2025 20:46
@vicheey
vicheey added this pull request to the merge queue Nov 11, 2025
Merged via the queue into develop with commit 6b6b270 Nov 11, 2025
42 checks passed
@vicheey
vicheey deleted the feat-allow-specifying-functions-local-start-command branch November 13, 2025 19:00
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants