Search code examples
amazon-web-servicesaws-lambdaaws-cloudformationserverless

Lambda not inheriting permissions while deploying CloudFormation from Serverless


I have the following serverless.yml, file which deploys an application into AWS by creating a S3 bucket and a lambda function. Yet, the IAM role created for the lambda function is the standard one that allows to log into CloudFront (see below), not access the S3. The authorizations defined in the IAM role are not granted to the lambda. Am i missing anything? Do I have to reference the IAM role in the lambda function definition in serverless.yml?

service: webanalysistool

custom:
  stage: ${opt:stage, 'dev'}

# plugins:
#   - serverless-offline

provider:
  name: aws
  runtime: nodejs14.x
  memorySize: 1024
  stage: ${self:custom.stage}
  # todo change it to your aws config
  profile: cl_dev
  versionFunctions: false
  environment:
    bucketName: "webanalysistool-${self:custom.stage}"

  architecture: arm64
  iam:
    role:
      statements:
        # Allow functions to list all buckets
        - Effect: Allow
          Action: "s3:ListBucket"
          Resource: "*"
        # Allow functions to read/write objects in a bucket
        - Effect: Allow
          Action:
            - "s3:GetObject"
            - "s3:PutObject"
          Resource:
            - "arn:aws:s3:::${self:provider.environment.bucketName}/*"

package:
  exclude:
    - "node_modules/aws-sdk/**"

functions:
  analyse:
    handler: src/handler.start
    timeout: 150
    events:
      - s3:
          bucket: ${self:provider.environment.bucketName}
          event: s3:ObjectCreated:*
          rules:
            - prefix: input/

IAM role created for the lambda function during deployment (I masked the AWS ID):

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Action": [
                "logs:CreateLogStream",
                "logs:CreateLogGroup"
            ],
            "Resource": [
                "arn:aws:logs:us-east-1:999999999999:log-group:/aws/lambda/webanalysistool-dev*:*"
            ],
            "Effect": "Allow"
        },
        {
            "Action": [
                "logs:PutLogEvents"
            ],
            "Resource": [
                "arn:aws:logs:us-east-1:999999999999:log-group:/aws/lambda/webanalysistool-dev*:*:*"
            ],
            "Effect": "Allow"
        }
    ]
}

Solution

  • Working for me

      iamRoleStatements:
          - Effect: "Allow"
            Action:
              - "s3:PutObject"
              - "s3:GetObject"
              - "s3:PutBucketAcl"
              - "s3:PutObjectAcl"
              - "s3:DeleteObject"
            Resource:
              - "arn:aws:s3:::${YOU_BUCKET}/*"
    
       events:
          - s3:
              existing: true
              bucket:
                !Ref YOU_BUCKET
              event: s3:ObjectCreated:*
              rules:
                - prefix: input/