How to add custom names Lambda function, API gateway, and Stage name in SAM template

Viewed 1073

I am trying my hands on SAM templates. Here I am trying to figure out how can I add custom names within the template. As when I package and Deploy the Template it creates the lambda function with an added alphanumeric value. API gateway name will be the stack name and it will be deployed in "Prod" and "Stage" Stage with in the API gateway.

Is there a way to have my own custom names.

Here is my sample code for the SAM template:

AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Description: An AWS Serverless Specification template describing your function.
Resources:
  GetAllUser:
    Type: AWS::Serverless::Function
    Properties:
      CodeUri: code/
      Handler: getAllUser.lambda_handler
      Timeout: 5
      Runtime: python3.8
      Role: lambda_execution
      MemorySize: 128
      Events:
        GetAllUser:
          Type: Api
          Properties:
            Path: /get-all-user
            Method: get
            

could any one help me with this?

1 Answers

For creating a name for your lambda you can specify directly AWS::Serverless::Function

AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Description: An AWS Serverless Specification template describing your function.
Resources:
  GetAllUser:
    Type: AWS::Serverless::Function
    Properties:
      FunctionName: "MyFunctionName"
      CodeUri: code/
      Handler: getAllUser.lambda_handler
      Timeout: 5
      Runtime: python3.8
      Role: lambda_execution
      MemorySize: 128
      Events:
        GetAllUser:
          Type: Api
          Properties:
            Path: /get-all-user
            Method: get

As for other names like StageName and ApiGateway Name, you need to use AWS::Serverless::Api

AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Description: AWS SAM template with a simple API definition
Resources:
  ApiGatewayApi:
    Type: AWS::Serverless::Api
    Properties:
      StageName: prod
      Name: myapi
  ApiFunction: # Adds a GET api endpoint at "/" to the ApiGatewayApi via an Api event
    Type: AWS::Serverless::Function
    Properties:
      FunctionName: myfunction
      Events:
        ApiEvent:
          Type: Api
          Properties:
            Path: /
            Method: get
            RestApiId:
              Ref: ApiGatewayApi
      Runtime: python3.7
      Handler: index.handler
      InlineCode: |
        def handler(event, context):
            return {'body': 'Hello World!', 'statusCode': 200}
Related