Subscribed unsubscribe Subscribe Subscribe

Lambda×NodeJS×S3でファイルをアップロードしてみる

http://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/S3.html

Role

  • Permissions
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Action": [
        "logs:CreateLogGroup",
        "logs:CreateLogStream",
        "logs:PutLogEvents"
      ],
      "Resource": "arn:aws:logs:*:*:*"
    },
    {
      "Effect": "Allow",
      "Action": [
        "s3:GetObject",
        "s3:PutObject"
      ],
      "Resource": [
        "arn:aws:s3:::*"
      ]
    }
  ]
}
  • Trust Relationships
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "",
      "Effect": "Allow",
      "Principal": {
        "Service": "lambda.amazonaws.com"
      },
      "Action": "sts:AssumeRole"
    }
  ]
}

ソース

  • 初期化
console.log('Started UploadObjectOnS3');

var AWS = require('aws-sdk');
AWS.config.region = 'ap-northeast-1';
var bucketName = '{{バケット名}}';

var options = {
  params: {
    Bucket: bucketName
  }
};
  • イベント実行時
exports.handler = function(event, context) {
  var fileName = '{{ファイル名}}';
  var body = '{{json等}}';
  var params = {
    Key: fileName,
    Body: body
  };
  s3bucket.upload(params, function(err, data) {
    if (err) {
      console.log("Error uploading data: ", err);
    } else {
      console.log("Successfully uploaded data to " + bucketName + "/" + fileName);
    }
    context.done(null, 'Finished UploadObjectOnS3');
  });
};