我有一个AWS SAM模板,该模板可创建显式lambda和隐式API网关(通过Events
属性)。我需要为Lambda和API网关分配特定和不同的IAM角色。而lambda角色在SAM模板语法中是不言而喻的,但我不知道如何将角色分配给API网关。
,例如
# template.yaml
...
Resources:
MyLambda:
Type: AWS::Serverless::Function
Properties:
FunctionName: very-important-lambda
Handler: src/index.handler
Runtime: nodejs8.10
Role: !Sub "arn:aws:iam::${AWS::AccountId}:role/lambda-role-name
CodeUri: ./build
# Below event creates an AWS::ApiGateway::RestApi resource, but how do I give that resource an IAM Role?
Events:
PostDomainEvent:
Type: Api
Properties:
Method: POST
Path: "/path/resource/v1"
为什么要在API网关中添加角色?Sam Wil自动(隐式)安排了API网关具有使用Lambda资源策略(有关API Gateway的文档)
中的lambda函数的权限如果要设置API网关的资源策略或设置其他设置,则可以明确定义Lambda-Event使用的API。
例如。设置资源策略:
RestApi:
Type: AWS::Serverless::Api
Properties:
Policy: >
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": {
"AWS": "arn:aws:iam::123456789012:root"
},
"Action": "execute-api:Invoke",
"Resource": "arn:aws:execute-api:eu-central-1: 123456789012:7mancjlc5z/*"
}
]
}
Function:
Type: AWS::Serverless::Function
Properties:
Events:
ApiRequest:
Type: Api
Properties:
Path: /v1/comments
Method: post
RestApiId: !Ref RestApi
SAM文档对此并不完全清楚,而是在编写上述设置的那一刻。