我觉得这个问题已经被问了很多,但从目前的答案来看,没有什么对我有用。
我正在尝试使用无服务器部署应用程序。我serverless.yml
是:
app: product-events-api
service: product-events
custom:
secrets: ${ssm:/aws/reference/secretsmanager/serverless-product-events-${self:provider.stage}~true, ''}
provider:
name: aws
runtime: nodejs10.x
region: eu-west-1
stage: ${opt:stage, 'preview'}
timeout: 30
# Role ARN must adhere to the RegEx: arn:(aws[a-zA-Z-]*)?:iam::d{12}:role/?[a-zA-Z_0-9+=,.@-_/]+
role: arn:aws:iam::${self:custom.secrets.AWS_ACCOUNT_ID}:role/${self:custom.secrets.IAM_ROLE_NAME}
vpc: ${self:custom.secrets.vpc}
environment:
STAGE: ${self:provider.stage}
NODE_ENV: production
DB_NAME: ${self:custom.secrets.DB_NAME}
DB_URL: ${self:custom.secrets.DB_URL}
functions:
getProductEvents:
handler: src/routes/api/handler.events
memorySize: 1024
description: Get product event
events:
- http:
path: /events
method: get
role
评估为绝对 ARNarn:aws:iam::<Account ID>:role/lambda_basic_execution
。
运行sls deploy --stage production
给了我错误:
发生错误:GetProductEventsLambdaFunction - Lambda 无法代入为函数定义的角色。(服务:AWSLambdaInternal;状态代码:400;错误代码:无效参数值异常;请求 ID:4750b33e-329c-4383-abd4-a61ec4d326b2(。
我们拥有的几乎所有 lambda 都使用此 IAM 角色。我转向这个答案试图在函数级别仅通过名称来定义role
,但得到:
CloudFormation 模板无效:模板错误:Fn::GetAtt 的实例引用未定义的资源lamba_basic_execution
如果我跑;aws iam get-role --role-name lambda_basic_execution
,我返回:
{
"Role": {
"AssumeRolePolicyDocument": {
"Version": "2012-10-17",
"Statement": [
{
"Action": "sts:AssumeRole",
"Principal": {
"Service": "lambda.amazonaws.com"
},
"Effect": "Allow",
"Sid": ""
}
]
},
"MaxSessionDuration": 3600,
"RoleId": "<Role ID>",
"CreateDate": "2015-10-13T15:06:34Z",
"RoleName": "lambda_basic_execution",
"Path": "/",
"Arn": "arn:aws:iam::<Account ID>:role/lambda_basic_execution"
}
}
如果我从模板中删除声明role
,部署将有效,然后我可以通过控制台手动添加角色。我想这是一个无服务器问题。
正如您提到的,您很少有使用相同的 IAM 角色的 lambda,我建议您创建一个 IAM 角色作为 serverless.yml 脚本的一部分。此方法的好处是,您可以根据将来的需求轻松添加或删除任何权限。你可以做类似的事情
YourIAMRole:
Type: AWS::IAM::Role
Properties:
AssumeRolePolicyDocument:
Statement:
- Effect: Allow
Principal:
Service: lambda.amazonaws.com
Action: sts:AssumeRole
Path: /
ManagedPolicyArns:
- arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole
Policies:
- # Any permission you want to add, For an example I am adding S3
PolicyName: "resources_access"
PolicyDocument:
Version: "2012-10-17"
Statement:
-
Effect: "Allow"
Action: "s3:Get*"
Resource: !Join
- ''
- - "arn:aws:s3:::"
- !Ref YourParameteredBucketName
完成此操作后,可以按如下方式将此角色分配给函数:
Role: !GetAtt YourIAMRole.Arn