Lambda functions not building the correct layers locally when running sam local start-api with the layer and the function in different template files

  Kiến thức lập trình

When I try to run sam local start-api and the lambda function and layer are in the same template file it works perfectly:

Resources:
  ApiLayer:
    Type: AWS::Serverless::LayerVersion
    Properties:
      LayerName: api-layer
      ContentUri: src/shared/layers/api/
      CompatibleRuntimes:
        - python3.12
    Metadata:
      BuildMethod: python3.12
      BuildArchitecture: x86_64

  ClientsFunction:
    Type: AWS::Serverless::Function
    Properties:
      Runtime: python3.12
      CodeUri: src/functions/api/clients/
      Handler: app.lambda_handler
      Layers:
        - !Ref ApiLayer

The problem happens when I try to move the layer to a different template file so it can be used by multiple lambda functions.

clients.yaml:

  ClientsFunction:
    Type: AWS::Serverless::Function
    Properties:
      Runtime: python3.12
      CodeUri: src/functions/api/clients/
      Handler: app.lambda_handler
      Layers:
        - !ImportValue ApiLayer

layers.yaml:

Resources:
  ApiLayer:
    Type: AWS::Serverless::LayerVersion
    Properties:
      LayerName: api-layer
      Description: Base environment for API lambda functions
      ContentUri: src/shared/layers/api/
      CompatibleRuntimes:
        - python3.12
    Metadata:
      BuildMethod: python3.12
      BuildArchitecture: x86_64

Outputs:
  ApiLayerArn:
    Description: ARN of the API Layer
    Value: !GetAtt ApiLayer.Arn
    Export:
      Name: ApiLayerArn

When they are in different files the lambda layer is not included in the local container, and the dependencies used by the lambda functions stop working, which makes local tests impossible.

Am I doing something wrong with the templates? I feel like I already tried everything to make it work. Any help would be greatly appreciated!

I already tried running sam build and it didn’t change anything.

I tried passing parameters through the template calls, instead of using imports/exports and it also didn’t change anything.

I also tried to pass the name instead of the arn Value: !Ref ApiLayer but it also didn’t work.

The only way I can run sam local start-api properly is if every lambda function that uses it has a copy of the layer definitions in the local template. Then it recognizes the layer as local: ApiLayer is a local Layer in the template

But I don’t understand why just moving it to a different template breaks the reference, or how to fix it.

Theme wordpress giá rẻ Theme wordpress giá rẻ Thiết kế website Kho Theme wordpress Kho Theme WP Theme WP

LEAVE A COMMENT