如何在无服务器框架中分配功能级别IamRoleStatements?

时间:2017-01-04 22:33:30

标签: aws-lambda amazon-iam serverless-framework

我想为serverless.yml

中列出的不同功能分配不同的权限
 functions:
  hello:
    handler: handler.hello
  crawl-distributor:
    handler: CrawlDistributor.handler
  product-scanner:
    handler: ProductScanner.handler
    iamRoleStatements:
      - Effect: Allow
        Action:
          - dynamodb:*
          - lambda:*
        Resource: "*"

这似乎不起作用。当我在提供者级别添加iamRoleStatements时,它可以工作,但最终会将权限应用于所有函数。

 provider:
  name: aws
  runtime: nodejs4.3
  stage: api
  region: us-east-1
  profile: dev
  iamRoleStatements:
    - Effect: Allow
      Action:
        - dynamodb:*
        - lambda:*
      Resource: "*"

1 个答案:

答案 0 :(得分:12)

docs开始,您需要在resources下创建函数角色,并在函数中引用此新角色。

示例:

service: my-test

provider:
  name: aws
  runtime: nodejs4.3
  stage: api
  region: us-east-1
  profile: dev

functions:
  hello:
    handler: handler.hello
  crawl-distributor:
    handler: CrawlDistributor.handler
  product-scanner:
    role: myDynamoRole
    handler: ProductScanner.handler

resources:
  Resources:
    myDynamoRole:
      Type: AWS::IAM::Role
      Properties:
        RoleName: myDynamoRole
        AssumeRolePolicyDocument:
          Version: '2012-10-17'
          Statement:
            - Effect: Allow
              Principal:
                Service:
                  - lambda.amazonaws.com
              Action: sts:AssumeRole
        Policies:
          - PolicyName: myPolicyName
            PolicyDocument:
              Version: '2012-10-17'
              Statement:
                - Effect: Allow
                  Action:
                    - dynamodb:*
                    - lambda:*
                  Resource: "*"