LambdaからS3のオブジェクトをCopyObjectCommandで移動する(node.js v18) – AWS SDK for JavaScript v3
CopyObjectCommand
aws cliだとaws s3 mvコマンドがありますが、AWS SDK for JavaScript v3だとオブジェクトを移動する操作がありません。
ですので一旦コピーしてから、コピー元を削除する必要があります。
$ aws s3 cp s3://bucket-a/tmp/hoge.json s3://bucket-a/tmp/gomi/hoge.json
まず上記のコピーコマンドをLambdaで実装します。
import { S3Client, CopyObjectCommand } from '@aws-sdk/client-s3'
export const handler = async(event) => {
const client = new S3Client({
region: 'ap-northeast-1'
})
const input = {
Bucket: 'bucket-a',
Key: 'tmp/gomi/hoge.json',
CopySource: 'bucket-a/tmp/hoge.json'
}
const command = new CopyObjectCommand(input)
await client.send(command)
const response = {
statusCode: 200,
body: JSON.stringify('Hello from Lambda'),
};
return response;
}
CopyObjectCommandに指定するパラメータは以下の通りです。
| キー | 値 |
|---|---|
| Bucket | コピー先バケット名 |
| Key | コピー先バケット名以降のオブジェクトキー |
| CopySource | コピー元バケット名/オブジェクトキー |
DeleteObjectCommand
コピーができたら、今度はコピー元のオブジェクトを削除します。削除するにはDeleteObjectCommandを使用します。
s3://bucket-a/tmp/hoge.jsonを削除します。
import { S3Client, DeleteObjectCommand } from '@aws-sdk/client-s3'
export const handler = async(event) => {
const client = new S3Client({
region: 'ap-northeast-1'
})
const input = {
Bucket: 'bucket-a',
Key: 'tmp/hoge.json'
}
const command = new DeleteObjectCommand(input)
await client.send(command)
const response = {
statusCode: 200,
body: JSON.stringify('Hello from Lambda'),
};
return response
}
これでaws s3 mvコマンドと同じ事が実装できます。
move
コピーした後にコピー元を削除します。
index.mjs
import { S3Client, CopyObjectCommand, DeleteObjectCommand } from '@aws-sdk/client-s3'
export const handler = async(event) => {
const client = new S3Client({
region: 'ap-northeast-1'
})
let input, command
// コピー
input = {
Bucket: 'bucket-a',
Key: 'tmp/gomi/hoge.json',
CopySource: 'bucket-a/tmp/hoge.json'
}
command = new CopyObjectCommand(input)
await client.send(command)
// 削除
input = {
Bucket: 'bucket-a',
Key: 'tmp/hoge.json'
}
command = new DeleteObjectCommand(input)
await client.send(command)
const response = {
statusCode: 200,
body: JSON.stringify('Hello from Lambda'),
}
return response
参考サイト
ERROR: The request could not be satisfied
ERROR: The request could not be satisfied
Amazon S3 オブジェクトに対する操作の実行 - AWS SDK for Java 1.x
AWS SDK for Java を使用して Amazon S3 バケットのオブジェクトをリスト表示、アップロード、ダウンロード、コピー、名前変更、移動または削除する方法。
Attention Required! | Cloudflare

KHI入社して退社。今はCONFRAGEで正社員です。関西で140-170/80~120万から受け付けております^^
得意技はJS(ES20xx),Java,AWSの大体のリソースです
コメントはやさしくお願いいたします^^
座右の銘は、「狭き門より入れ」「願わくは、我に七難八苦を与えたまえ」です^^

コメント