LoginSignup
50
44

More than 5 years have passed since last update.

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

Posted at

問題

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

50
44
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
50
44