LoginSignup
21
16

More than 3 years have passed since last update.

LambdaでS3からファイルを取得しようとしたらbotocore.exceptions.ClientError: An error occurred (AccessDenied) when calling the GetObject operation: Access Deniedとなった時の対応方法

Last updated at Posted at 2019-05-10

AWSもPythonもぜーーんぶ初心者でわけわからん。

  • 環境
    • OS : Ubuntu Server 18.04 LTS
    • Python 3.6

事象 : Lambda関数でBoto3を使ってS3にあるファイルを取得しようとしたら怒られた

lambda_function.py
def get_file_from_s3(file_name: str):
    """S3よりファイルを取得する."""
    s3 = boto3.client('s3')
    try:
        file = s3.get_object(Bucket = BUCKET_NAME, Key = 'irai.txt')
    except botocore.exceptions.ClientError as e:
        if e.response['Error']['Code'] == "404":
            logger.error("The object does not exist.")
        else:
            raise e
CloudWatchのログ
get_file_from_s3('irai.txt')
File "/var/task/lambda_function.py", line 91, in get_file_from_s3
file = s3.get_object(Bucket = BUCKET_NAME, Key = 'irai.txt')
File "/var/runtime/botocore/client.py", line 314, in _api_call
return self._make_api_call(operation_name, kwargs)
File "/var/runtime/botocore/client.py", line 612, in _make_api_call
raise error_class(parsed_response, operation_name)
botocore.exceptions.ClientError: An error occurred (AccessDenied) when calling the GetObject operation: Access Denied

原因 : Lambdaに設定されたIAMロールにS3へのアクセス権限がないから

Lambdaはファンクション登録時にそのファンクションで利用するIAMロールを選択できると思うので、そこでS3アクセス権限のあるロールを選択してください。 - スタック・オーバーフロー

対応 : IAMロールにS3へのアクセス権限を設定する

参考 : IAM RoleとBucket PolicyでAmazon S3へのアクセス制御を行う - yoshidashingo

  1. コンソールから[IAM]を選択する
    • image.png
  2. ロールの一覧からLambdaで使用しているIAMロールを選択する
    • image.png
  3. [Attach policies]ボタンを押下する。
  4. [AmazomS3FullAccess]を選択して[Attach policy]ボタンで追加する。
    • image.png
21
16
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
21
16