[英]“Truncating” a DynamoDB Table Created via CloudFormation (SAM)
[英]How to get access to the bucket created via cloudformation in my lambda?
我正在通過 cloudformation 模板創建 lambda 和 S3。 對於存儲桶,我傳入了存儲桶名稱的參數。 我想在 lambda function 的 python 代碼中訪問此存儲桶。 我怎樣才能做到這一點?
雲形成模板
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Description: Sample SAM Template
Globals:
Function:
Timeout: 3
Parameters:
bucketName:
Default: somename
Resources:
S3Bucket:
Type: AWS::S3::Bucket
Properties:
AccessControl: PublicRead
BucketName: !Sub '${bucketName}-${AWS::AccountID}'
HelloWorldFunction:
Type: AWS::Serverless::Function
Properties:
CodeUri: hello_world/
Handler: app.lambda_handler
Runtime: python3.8
Environment:
Variables:
s3bucketName: !GetAtt S3Bucket
lambda_handler function
import boto3
import os
from requests_aws4auth import AWS4Auth
session = boto3.Session()
credentials = session.get_credentials()
aws4auth = AWS4Auth(credentials.access_key,credentials.secret_key,region, service, session_token=credentials.token)
s3 = boto3.resource('s3')
//get access to the S3 bucket created??
s3 = boto3.resource('s3')
obj = s3.Object(bucket, key)
objAsString = obj.get()['Body'].read().decode('utf-8')
您還缺少從 lambda 訪問 s3 存儲桶的策略。
HelloWorldFunction:
Type: AWS::Serverless::Function
Properties:
CodeUri: hello_world/
Handler: app.lambda_handler
Runtime: python3.8
Environment:
Variables:
S3_BUCKET_NAME: !Ref S3Bucket
Policies:
- Statement:
- Effect:
Action:
- 's3:GetObject'
- 's3:ListBucket'
- 's3:ListBucketMultipartUploads'
- 's3:PutObject'
Resource:
- !Sub 'arn:aws:s3:::${S3Bucket}'
我將在單獨的 cloudformation s3.yaml
中創建存儲桶並執行一次。
....
Resources:
S3Bucket:
Type: AWS::S3::Bucket
Properties:
AccessControl: PublicRead
BucketName: !Sub '${bucketName}-${AWS::AccountID}'
Outputs:
BucketName:
Value: !Ref S3Bucket
Description: 'Bucket name'
Export:
Name: s3-bucket-name
之后,我可以使用 lambda 在其他 cloudformation 中導入這個s3-bucket-name
。
Variables:
S3_BUCKET_NAME: !ImportValue s3-bucket-name
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.