簡體   English   中英

使用Boto3從無服務器Lambda函數調用AWS S3存儲桶時出現AccessDenied錯誤消息

[英]AccessDenied error message when calling aws s3 buckets from serverless lambda function with boto3

我正在使用amazon aws構建無服務器應用程序。我現在正在測試boto3以從aws s3服務中獲取存儲桶列表。盡管我的IAM用戶具有AdministratorAccess訪問權限,但每次嘗試調用lambda函數時,它都會顯示錯誤消息。有人可以幫我嗎?謝謝您的關注。這是我的錯誤信息

{
    "stackTrace": [
        [
            "/var/task/handler.py",
            9,
            "hello",
            "for bucket in s3.buckets.all():"
        ],
        [
            "/var/runtime/boto3/resources/collection.py",
            83,
            "__iter__",
            "for page in self.pages():"
        ],
        [
            "/var/runtime/boto3/resources/collection.py",
            161,
            "pages",
            "pages = [getattr(client, self._py_operation_name)(**params)]"
        ],
        [
            "/var/runtime/botocore/client.py",
            312,
            "_api_call",
            "return self._make_api_call(operation_name, kwargs)"
        ],
        [
            "/var/runtime/botocore/client.py",
            605,
            "_make_api_call",
            "raise error_class(parsed_response, operation_name)"
        ]
    ],
    "errorType": "ClientError",
    "errorMessage": "An error occurred (AccessDenied) when calling the ListBuckets operation: Access Denied"
}

這是我的lambda函數handler.py

import json
import boto3


def hello(event, context):

    s3 = boto3.resource('s3')

    for bucket in s3.buckets.all():
        print(bucket.name)



    body = {
        "message": "gg"
    }


    response = {
        "statusCode": 200,
        "body": json.dumps(body)
    }

    return response

這是我的serverless.yml文件

# Welcome to Serverless!
#
# This file is the main config file for your service.
# It's very minimal at this point and uses default values.
# You can always add more config options for more control.
# We've included some commented out config examples here.
# Just uncomment any of them to get that config option.
#
# For full config options, check the docs:
#    docs.serverless.com
#
# Happy Coding!

service: serverless-boto3

# You can pin your service to only deploy with a specific Serverless version
# Check out our docs for more details
# frameworkVersion: "=X.X.X"

provider:
  name: aws
  runtime: python2.7

# you can overwrite defaults here
#  stage: dev
#  region: us-east-1

# you can add statements to the Lambda function's IAM Role here
#  iamRoleStatements:
#    - Effect: "Allow"
#      Action:
#        - "s3:ListBucket"
#      Resource: { "Fn::Join" : ["", ["arn:aws:s3:::", { "Ref" : "ServerlessDeploymentBucket" } ] ]  }
#    - Effect: "Allow"
#      Action:
#        - "s3:PutObject"
#      Resource:
#        Fn::Join:
#          - ""
#          - - "arn:aws:s3:::"
#            - "Ref" : "ServerlessDeploymentBucket"
#            - "/*"

# you can define service wide environment variables here
#  environment:
#    variable1: value1

# you can add packaging information here
#package:
#  include:
#    - include-me.py
#    - include-me-dir/**
#  exclude:
#    - exclude-me.py
#    - exclude-me-dir/**

functions:
  hello:
    handler: handler.hello

#    The following are a few example events you can configure
#    NOTE: Please make sure to change your handler code to work with those events
#    Check the event documentation for details
    events:
      - http:
          path: users/create
          method: get
#      - s3: ${env:BUCKET}
#      - schedule: rate(10 minutes)
#      - sns: greeter-topic
#      - stream: arn:aws:dynamodb:region:XXXXXX:table/foo/stream/1970-01-01T00:00:00.000
#      - alexaSkill
#      - alexaSmartHome: amzn1.ask.skill.xx-xx-xx-xx
#      - iot:
#          sql: "SELECT * FROM 'some_topic'"
#      - cloudwatchEvent:
#          event:
#            source:
#              - "aws.ec2"
#            detail-type:
#              - "EC2 Instance State-change Notification"
#            detail:
#              state:
#                - pending
#      - cloudwatchLog: '/aws/lambda/hello'
#      - cognitoUserPool:
#          pool: MyUserPool
#          trigger: PreSignUp

#    Define function environment variables here
#    environment:
#      variable2: value2

# you can add CloudFormation resource templates here
#resources:
#  Resources:
#    NewResource:
#      Type: AWS::S3::Bucket
#      Properties:
#        BucketName: my-new-bucket
#  Outputs:
#     NewOutput:
#       Description: "Description for the output"
#       Value: "Some output value"

在您的serverless.yml您沒有授予Lambda函數任何訪問S3的權限。 模板中的示例已被注釋掉。

Lambda函數使用IAM角色獲得訪問AWS資源的權限。 在Amazon管理控制台中,選擇您的Lambda函數。 向下滾動並查找執行角色 這將向您顯示為函數創建的模板。

管理權限:使用IAM角色(執行角色)

每個Lambda函數都有一個與之關聯的IAM角色(執行角色)。 創建Lambda函數時,可以指定IAM角色。 您授予此角色的權限確定了AWS Lambda在擔任該角色時可以做什么。 您授予IAM角色兩種類型的權限:

  • 如果您的Lambda函數代碼訪問其他AWS資源,例如從S3存儲桶讀取對象或將日志寫入CloudWatch Logs,則需要向該角色授予對相關Amazon S3和CloudWatch操作的權限。

  • 如果事件源基於流(Amazon Kinesis流和DynamoDB流),則AWS Lambda會代您輪詢這些流。 AWS Lambda需要權限來輪詢流並讀取流上的新記錄,因此您需要向此角色授予相關權限。

適用於AWS Lambda的IAM策略

我已經具有權限,但是添加以下資源為我解決了該問題:

 Resources:
     S3Bucket:
       Type: AWS::S3::Bucket
       Properties:
         BucketName: ${self:custom.bucketName}
     S3BucketPermissions:
       Type: AWS::S3::BucketPolicy
       DependsOn: S3Bucket
       Properties:
         Bucket: ${self:custom.bucketName}
         PolicyDocument:
           Statement:
             - Principal: "*"
               Action:
                 - s3:PutObject
                 - s3:PutObjectAcl
               Effect: Allow
               Sid: "AddPerm"
               Resource: arn:aws:s3:::${self:custom.bucketName}/*

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM