Help us understand the problem. What is going on with this article?

VPC Lambdaからs3へアクセスする

More than 3 years have passed since last update.

問題

AWS LambdaがVPC対応したので試したところ、そのままではs3へのアクセスが出来なかった。

例えば、こんな感じにタイムアウトする。

{
  "errorMessage": "2016-02-12T17:15:10.898Z 12c18327-ddbc-1e15-ad30-da8934f8a9c3 Task timed out after 30.00 seconds"
}

原因

ドキュメントに書いてあった。

When you add VPC configuration to a Lambda function, it can only access resources in that VPC. If a Lambda function needs to access both VPC resources and the public Internet, the VPC needs to have a Network Address Translation (NAT) instance inside the VPC.

AWS Lambda uses the VPC information you provide to set up ENIs that allow your Lambda function to access VPC resources. The ENIs that AWS Lambda creates do not have public Internet access. Therefore, even if you have an Internet gateway attached to your VPC, your Lambda function will not be able to access the Internet. If your Lambda function requires Internet access (for example, to access AWS services that don't have VPC endpoints, such as Amazon Kinesis), you can configure a NAT instance inside your VPC or you can use the Amazon VPC NAT gateway. For more information, see NAT Gateways in the Amazon VPC User Guide.

解決策

NATを使う方法

private subnetにLambdaを設置し、そのrouting tableでインターネット向けの通信(0.0.0.0/0)の経路情報ををNAT gateway又はNAT instanceに割り当てる。

Lambda on VPCを使うと、Internet gatewayが割り当てられているpublic subnetを設定しても外部への通信ができないので、Default VPCだろうが敢えてprivate subnetを作成する必要がある。

VPC Endpointを使う方法

VPC Endpoint for S3を設定する事によって、private network経由の通信が可能になる。但し、Lambdaと同一リージョンのs3 bucketに限定される。

s3以外のインターネット越しの外部リソースにはアクセスできないが、こちらの方が設定がより簡単。

serverless-operations
AWSクラウド技術の豊富な知見を活かし、サーバーレスによる開発や運用の支援、コンサルティングまで行う会社です
https://serverless.co.jp/
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした