タイトル : テンプレートを確認(7-11) AWSサーバーレス2025
更新日 : 2025-01-26
カテゴリ : プログラミング
タグ :
aws   
sam   
lambda   
python   

AWS サーバーレス2025

テンプレートを確認しましょう

7から11のテンプレートを確認です

  • DynamoDBの書き方(7より)

    # DynamoDB table to store item: {id: <ID>, name: <NAME>}
    SampleTable:
      Type: AWS::Serverless::SimpleTable
      Properties:
        PrimaryKey:
          Name: id
          Type: String
        ProvisionedThroughput:
          ReadCapacityUnits: 2
          WriteCapacityUnits: 2
  • ストリーミングレスポンスの書き方(9より)

        FunctionUrlConfig:
          AuthType: AWS_IAM
          InvokeMode: RESPONSE_STREAM
  • メソッド、ヘッダー(11より)

    ApiGatewayApi:
      Type: AWS::Serverless::Api
      Properties:
        StageName: Prod
        Cors:
          AllowMethods: "'OPTIONS, POST, GET'"
          AllowHeaders: "'Content-Type'"
          AllowOrigin: "'*'" #DO NOT USE THIS VALUE IN PRODUCTION - https://docs.aws.amazon.com/apigateway/latest/developerguide/http-api-cors.html
    

テンプレート

$ cat template07/template.yaml 
# This is the SAM template that represents the architecture of your serverless application
# https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-template-basics.html

# The AWSTemplateFormatVersion identifies the capabilities of the template
# https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/format-version-structure.html
AWSTemplateFormatVersion: 2010-09-09
Description: >-
  template07

# Transform section specifies one or more macros that AWS CloudFormation uses to process your template
# https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/transform-section-structure.html
Transform:
- AWS::Serverless-2016-10-31

# Resources declares the AWS resources that you want to include in the stack
# https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/resources-section-structure.html
Resources:
  # Each Lambda function is defined by properties:
  # https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#awsserverlessfunction

  # This is a Lambda function config associated with the source code: get-all-items.js
  getAllItemsFunction:
    Type: AWS::Serverless::Function
    Properties:
      Handler: src/handlers/get-all-items.getAllItemsHandler
      Runtime: nodejs22.x
      Architectures:
        - x86_64
      MemorySize: 128
      Timeout: 100
      Description: A simple example includes a HTTP get method to get all items from a DynamoDB table.
      Policies:
        # Give Create/Read/Update/Delete Permissions to the SampleTable
        - DynamoDBCrudPolicy:
            TableName: !Ref SampleTable
      Environment:
        Variables:
          # Make table name accessible as environment variable from function code during execution
          SAMPLE_TABLE: !Ref SampleTable
      Events:
        Api:
          Type: Api
          Properties:
            Path: /
            Method: GET
  # Each Lambda function is defined by properties:
  # https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#awsserverlessfunction

  # This is a Lambda function config associated with the source code: get-by-id.js
  getByIdFunction:
    Type: AWS::Serverless::Function
    Properties:
      Handler: src/handlers/get-by-id.getByIdHandler
      Runtime: nodejs22.x
      Architectures:
        - x86_64
      MemorySize: 128
      Timeout: 100
      Description: A simple example includes a HTTP get method to get one item by id from a DynamoDB table.
      Policies:
        # Give Create/Read/Update/Delete Permissions to the SampleTable
        - DynamoDBCrudPolicy:
            TableName: !Ref SampleTable
      Environment:
        Variables:
          # Make table name accessible as environment variable from function code during execution
          SAMPLE_TABLE: !Ref SampleTable
      Events:
        Api:
          Type: Api
          Properties:
            Path: /{id}
            Method: GET
  # Each Lambda function is defined by properties:
  # https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#awsserverlessfunction

  # This is a Lambda function config associated with the source code: put-item.js
  putItemFunction:
    Type: AWS::Serverless::Function
    Properties:
      Handler: src/handlers/put-item.putItemHandler
      Runtime: nodejs22.x
      Architectures:
        - x86_64
      MemorySize: 128
      Timeout: 100
      Description: A simple example includes a HTTP post method to add one item to a DynamoDB table.
      Policies:
        # Give Create/Read/Update/Delete Permissions to the SampleTable
        - DynamoDBCrudPolicy:
            TableName: !Ref SampleTable
      Environment:
        Variables:
          # Make table name accessible as environment variable from function code during execution
          SAMPLE_TABLE: !Ref SampleTable
      Events:
        Api:
          Type: Api
          Properties:
            Path: /
            Method: POST
  # Simple syntax to create a DynamoDB table with a single attribute primary key, more in
  # https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#awsserverlesssimpletable

  # DynamoDB table to store item: {id: <ID>, name: <NAME>}
  SampleTable:
    Type: AWS::Serverless::SimpleTable
    Properties:
      PrimaryKey:
        Name: id
        Type: String
      ProvisionedThroughput:
        ReadCapacityUnits: 2
        WriteCapacityUnits: 2

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

$ cat template08/template.yaml 
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Description: >
  template08

  Sample SAM Template for template08

# More info about Globals: https://github.com/awslabs/serverless-application-model/blob/master/docs/globals.rst
Globals:
  Function:
    Timeout: 3

Resources:
  HelloWorldFunction:
    Type: AWS::Serverless::Function # More info about Function Resource: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#awsserverlessfunction
    Properties:
      CodeUri: hello_world_function
      Handler: hello_world/app.lambda_handler
      Runtime: python3.12
      Architectures:
        - x86_64
      Events:
        HelloWorld:
          Type: CloudWatchEvent # More info about CloudWatchEvent Event Source: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#cloudwatchevent
          Properties:
            Pattern:
              source:
                - aws.ec2
              detail-type:
                - EC2 Instance State-change Notification

Outputs:
  # ServerlessRestApi is an implicit API created out of Events key under Serverless::Function
  # Find out more about other implicit resources you can reference within SAM
  # https://github.com/awslabs/serverless-application-model/blob/master/docs/internals/generated_resources.rst#api
  HelloWorldFunction:
    Description: "Hello World Lambda Function ARN"
    Value: !GetAtt HelloWorldFunction.Arn
  HelloWorldFunctionIamRole:
    Description: "Implicit IAM Role created for Hello World function"
    Value: !GetAtt HelloWorldFunctionRole.Arn
$ 

$ cat template09/template.yaml 
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31

Description: >
  Sample SAM Template for template09
  
Resources:
  StreamingFunction:
    Type: AWS::Serverless::Function
    Properties:
      CodeUri: src/
      Handler: index.handler
      Runtime: nodejs22.x
      Architectures:
        - x86_64
      Timeout: 10
      FunctionUrlConfig:
        AuthType: AWS_IAM
        InvokeMode: RESPONSE_STREAM

Outputs:
  StreamingFunction:
    Description: "Streaming Lambda Function ARN"
    Value: !GetAtt StreamingFunction.Arn
  StreamingFunctionURL:
    Description: "Streaming Lambda Function URL"
    Value: !GetAtt StreamingFunctionUrl.FunctionUrl


$ 

$ cat template10/template.yaml 
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Description: >
  template10
  
  Sample SAM Template for template10


Resources:
  PostsTable:
    Type: AWS::Serverless::SimpleTable

  Greeter:
    Type: AWS::Serverless::Function # More info about Function Resource: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#awsserverlessfunction
    Properties:
      CodeUri: greeter/
      Handler: app.lambdaHandler
      Runtime: nodejs22.x
      Architectures:
        - x86_64

  HelloWorldGraphQLApi:
    Type: AWS::Serverless::GraphQLApi
    Properties:
      SchemaUri: ./gql/schema.graphql
      Auth:
        Type: API_KEY
      ApiKeys:
        MyApiKey:
          Description: my api key
      DataSources:
        DynamoDb:
          Posts:
            TableName: !Ref PostsTable
            TableArn: !GetAtt PostsTable.Arn
        Lambda:
          Greeter:
            FunctionArn: !GetAtt Greeter.Arn
      Functions:
        preprocessPostItem:
          Runtime:
            Name: APPSYNC_JS
            Version: 1.0.0
          DataSource: NONE
          CodeUri: ./gql/preprocessPostItem.js
        createPostItem:
          Runtime:
            Name: APPSYNC_JS
            Version: "1.0.0"
          DataSource: Posts
          CodeUri: ./gql/createPostItem.js
        getPostFromTable:
          Runtime:
            Name: APPSYNC_JS
            Version: "1.0.0"
          DataSource: Posts
          CodeUri: ./gql/getPostFromTable.js
        greet:
          Runtime:
            Name: APPSYNC_JS
            Version: "1.0.0"
          DataSource: Greeter
          CodeUri: ./gql/greet.js
      Resolvers:
        Mutation:
          addPost:
            Runtime:
              Name: APPSYNC_JS
              Version: "1.0.0"
            Pipeline:
            - preprocessPostItem
            - createPostItem
        Query:
          getPost:
            Runtime:
              Name: APPSYNC_JS
              Version: "1.0.0"
            Pipeline:
            - getPostFromTable
          sayHello:
            Runtime:
              Name: APPSYNC_JS
              Version: "1.0.0"
            Pipeline:
            - greet
          sayGoodbye:
            Runtime:
              Name: APPSYNC_JS
              Version: "1.0.0"
            Pipeline:
            - greet


Outputs:
  HelloWorldGraphQLApi:
    Description: HelloWorldGraphQLApi endpoint URL for Prod environment
    Value: !GetAtt HelloWorldGraphQLApi.GraphQLUrl
  HelloWorldGraphQLApiMyApiKey:
    Description: API Key for HelloWorldGraphQLApi
    Value: !GetAtt HelloWorldGraphQLApiMyApiKey.ApiKey

$ 

$ cat template11/template.yaml 
# This is the SAM template that represents the architecture of your serverless application
# https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-template-basics.html

# The AWSTemplateFormatVersion identifies the capabilities of the template
# https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/format-version-structure.html
AWSTemplateFormatVersion: 2010-09-09
Description: >-
  template11
# Transform section specifies one or more macros that AWS CloudFormation uses to process your template
# https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/transform-section-structure.html
Transform:
- AWS::Serverless-2016-10-31

# Resources declares the AWS resources that you want to include in the stack
# https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/resources-section-structure.html
Resources:
  # Each Lambda function is defined by properties:
  # https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#awsserverlessfunction

  # This is an API gateway associated with the getByIdFunction and putItemFunctions
  ApiGatewayApi:
    Type: AWS::Serverless::Api
    Properties:
      StageName: Prod
      Cors:
        AllowMethods: "'OPTIONS, POST, GET'"
        AllowHeaders: "'Content-Type'"
        AllowOrigin: "'*'" #DO NOT USE THIS VALUE IN PRODUCTION - https://docs.aws.amazon.com/apigateway/latest/developerguide/http-api-cors.html

  # This is a Lambda function config associated with the source code: get-by-id.js
  getAllItemsFunction:
    Type: AWS::Serverless::Function
    Properties:
      CodeUri: backend/
      Handler: src/handlers/get-all-items.getAllItemsHandler
      Runtime: nodejs22.x
      Architectures:
        - x86_64
      MemorySize: 128
      Timeout: 100
      Description: A simple example includes a HTTP get method to get all items by id from a DynamoDB table.
      Policies:
        # Give Create/Read/Update/Delete Permissions to the SampleTable
        - DynamoDBCrudPolicy:
            TableName: !Ref SampleTable
      Environment:
        Variables:
          # Make table name accessible as environment variable from function code during execution
          SAMPLE_TABLE: !Ref SampleTable
          # Make DynamoDB endpoint accessible as environment variable from function code during execution
          ENDPOINT_OVERRIDE: ""
      Events:
        Api:
          Type: Api
          Properties:
            Path: /
            Method: GET
            RestApiId:
              Ref: ApiGatewayApi
  # Each Lambda function is defined by properties:
  # https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#awsserverlessfunction

  # This is a Lambda function config associated with the source code: get-by-id.js
  getByIdFunction:
    Type: AWS::Serverless::Function
    Properties:
      CodeUri: backend/
      Handler: src/handlers/get-by-id.getByIdHandler
      Runtime: nodejs22.x
      Architectures:
        - x86_64
      MemorySize: 128
      Timeout: 100
      Description: A simple example includes a HTTP get method to get one item by id from a DynamoDB table.
      Policies:
        # Give Create/Read/Update/Delete Permissions to the SampleTable
        - DynamoDBCrudPolicy:
            TableName: !Ref SampleTable
      Environment:
        Variables:
          # Make table name accessible as environment variable from function code during execution
          SAMPLE_TABLE: !Ref SampleTable
          # Make DynamoDB endpoint accessible as environment variable from function code during execution
          ENDPOINT_OVERRIDE: ""
      Events:
        Api:
          Type: Api
          Properties:
            Path: /{id}
            Method: GET
            RestApiId:
              Ref: ApiGatewayApi
  # Each Lambda function is defined by properties:
  # https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#awsserverlessfunction

  # This is a Lambda function config associated with the source code: put-item.js
  putItemFunction:
    Type: AWS::Serverless::Function
    Properties:
      CodeUri: backend/
      Handler: src/handlers/put-item.putItemHandler
      Runtime: nodejs22.x
      Architectures:
        - x86_64
      MemorySize: 128
      Timeout: 100
      Description: A simple example includes a HTTP post method to add one item to a DynamoDB table.
      Policies:
        # Give Create/Read/Update/Delete Permissions to the SampleTable
        - DynamoDBCrudPolicy:
            TableName: !Ref SampleTable
      Environment:
        Variables:
          SAMPLE_TABLE: !Ref SampleTable
          # Make DynamoDB endpoint accessible as environment variable from function code during execution
          ENDPOINT_OVERRIDE: ""
      Events:
        Api:
          Type: Api
          Properties:
            Path: /
            Method: POST
            RestApiId:
              Ref: ApiGatewayApi
  # Simple syntax to create a DynamoDB table with a single attribute primary key, more in
  # https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#awsserverlesssimpletable

  # DynamoDB table to store item: {id: <ID>, name: <NAME>}
  SampleTable:
    Type: AWS::Serverless::SimpleTable
    Properties:
      PrimaryKey:
        Name: id
        Type: String
      ProvisionedThroughput:
        ReadCapacityUnits: 2
        WriteCapacityUnits: 2

  # S3 Bucket to host single page app website
  WebSiteBucket:
    Type: "AWS::S3::Bucket"
    Properties:
      BucketEncryption:
        ServerSideEncryptionConfiguration:
          - BucketKeyEnabled: true
      VersioningConfiguration:
        Status: Enabled
  WebSiteBucketPolicy:
    Type: "AWS::S3::BucketPolicy"
    Properties:
      Bucket: !Ref WebSiteBucket
      PolicyDocument:
        Version: "2012-10-17"
        Id: "PolicyForCloudFrontPrivateContent"
        Statement:
        - Sid: "AllowCloudFrontServicePrincipal"
          Effect: "Allow"
          Principal:
            Service: "cloudfront.amazonaws.com"
          Action: "s3:GetObject"
          Resource: !Join [ "", [ "arn:aws:s3:::", !Ref WebSiteBucket, "/*" ] ]
          Condition:
            StringEquals:
              "AWS:SourceArn": !Join [ "", [ "arn:aws:cloudfront::", !Ref "AWS::AccountId", ":distribution/", !Ref CloudFrontDistribution ] ]
  
  # CloudFront Distribution for hosting the single page app website
  CloudFrontDistribution:
    Type: "AWS::CloudFront::Distribution"
    Properties:
      DistributionConfig:
        Origins:
        - DomainName: !GetAtt WebSiteBucket.RegionalDomainName
          Id: "myS3Origin"
          OriginAccessControlId: !GetAtt CloudFrontOriginAccessControl.Id
          S3OriginConfig: 
            OriginAccessIdentity: ""
        Enabled: true
        DefaultRootObject: "index.html"
        HttpVersion: "http2"
        DefaultCacheBehavior:
          AllowedMethods:
          - "DELETE"
          - "GET"
          - "HEAD"
          - "OPTIONS"
          - "PATCH"
          - "POST"
          - "PUT"
          CachedMethods:
          - "GET"
          - "HEAD"
          TargetOriginId: "myS3Origin"
          ForwardedValues:
            QueryString: false
            Cookies:
              Forward: "none"
          ViewerProtocolPolicy: "allow-all"
          MinTTL: 0
          DefaultTTL: 3600
          MaxTTL: 86400
        PriceClass: "PriceClass_200"
        Restrictions:
          GeoRestriction:
            RestrictionType: "whitelist"
            Locations:
            - "US"
            - "CA"
            - "GB"
            - "DE"
        ViewerCertificate:
          CloudFrontDefaultCertificate: true
  CloudFrontOriginAccessControl:
    Type: "AWS::CloudFront::OriginAccessControl"
    Properties:
      OriginAccessControlConfig:
        Name: !Sub "${WebSiteBucket} OAC"
        OriginAccessControlOriginType: "s3"
        SigningBehavior: "always"
        SigningProtocol: "sigv4"
Outputs:
  APIGatewayEndpoint:
    Description: "API Gateway endpoint URL for Prod stage"
    Value: !Sub "https://${ApiGatewayApi}.execute-api.${AWS::Region}.amazonaws.com/Prod/"
  CloudFrontDistributionId:
    Description: "CloudFront Distribution ID for hosting web front end"
    Value: !Ref CloudFrontDistribution
  CloudFrontDistributionDomainName:
    Description: "CloudFront Distribution Domain Name for accessing web front end"
    Value: !GetAtt CloudFrontDistribution.DomainName
  WebS3BucketName:
    Description: "S3 Bucket for hosting web frontend"
    Value: !Ref WebSiteBucket
$