API名称始终是SAM中的堆栈名称

时间:2019-03-07 19:58:47

标签: aws-lambda amazon-cloudformation aws-serverless aws-sam aws-sam-cli

我正在使用AWS CLI部署SAM模板。

AWS Api名称已设置为与CloudFormation堆栈名称相同。我期望基于以下模板内容将Api称为“用户”。

是否可以设置API名称?

SAM模板:

  MyApi:
    Type: AWS::Serverless::Api
    Properties:
      Name: Users
      StageName: default

使用其他信息进行更新(用于部署的完整模板和AWS CLI命令):

模板:

AWSTemplateFormatVersion: 2010-09-09
Transform: AWS::Serverless-2016-10-31

Resources:
  HelloFunction:
    Type: AWS::Serverless::Function
    Properties:
      Handler: main
      Runtime: go1.x
      Events:
        GetEvent:
          Type: Api
          Properties:
            Path: /
            Method: post
            #RestApiId: !Ref ApiGateway1

  LambdaInvokePermission:
    Type: AWS::Lambda::Permission
    Properties:
      FunctionName: !GetAtt
        - HelloFunction
        - Arn
      Action: 'lambda:InvokeFunction'
      Principal: apigateway.amazonaws.com
      SourceAccount: !Ref 'AWS::AccountId'

  MyApi:
    Type: AWS::Serverless::Api
    Properties:
      Name: Users
      StageName: default
      EndpointConfiguration: REGIONAL
      DefinitionBody:
        swagger: "2.0"
        info:
          title: "TestAPI"
        paths:
          /:
            post:
              x-amazon-apigateway-integration:
                uri:
                  Fn::Sub: arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${HelloFunction.Arn}/invocations
                responses: {}
                httpMethod: "POST"
                type: "aws_proxy"
Outputs:
  FunctioArn:
    Value: !GetAtt  HelloFunction.Arn
    Export:
      Name: HelloFunctionArn

CLI命令:

aws cloudformation package --template-file template.yml 
--output-template-file samtemplate.yaml --s3-bucket (bucketname) 

aws cloudformation deploy --template-file samtemplate.yaml 
--stack-name apisample-stack  --capabilities CAPABILITY_IAM

1 个答案:

答案 0 :(得分:1)

使用Name属性是设置API名称的正确方法。

但是,我认为您对该模板的功能感到困惑。如您所写,此模板将创建两个API-“隐式API”,然后创建您明确声明的名为“ Users”的API。

请注意:

  • 隐式API从堆栈名称中获取其名称。 (这似乎就是您正在观察的内容。)

  • 显式API从Name属性获取其名称。

如果您不想创建隐式API,而是自己明确定义它-似乎是这种情况-那么您只需要引用它即可:

  Events:
    GetEvent:
      Type: Api
      Properties:
        Path: /
        Method: post
        RestApiId: !Ref MyApi # Add this line

这将导致创建一个API,并将其命名为“用户”。