0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

S3 コマンドの基本的な使い方

Last updated at Posted at 2025-01-15

はじめに

S3の基本的なデータ取得や作成、アップロードなどのコマンドをまとめてみました。
S3 APIではなく、CLI

Profile作成

awsコマンドを叩く際にprofileを指定しますが、そのprofileを事前にconfigureで作ります。

# aws configureコマンド実行
aws configure --profile s3_user

# 以下の4項目を聞かれるので、設定
AWS Access Key ID [None]: アクセスキー
AWS Secret Access Key [None]: アクセスシークレット
Default region name [None]: リージョン
Default output format [None]: json(だいたいDefaultjson

S3のリスト取得

単純な参照 末尾にスラッシュを付けるか付けないかで動作が変わります

・そのファイルorDIRの存在を確認する場合は、スラッシュ無し
aws --profile s3_user s3 ls s3://{bucket_name}/{path}
・DIRの配下のファイル一覧を見たい場合、スラッシュを付ける
aws --profile s3_user s3 ls s3://{bucket_name}/{path}/

再帰的に確認する場合 --recursiveオプションをつけると、DIR配下の全てのファイルリストが返却されます。
aws --profile s3_user s3 ls s3://{bucket_name}/{path} --recursive

S3の単体ファイル取得

aws --profile s3_user s3 cp s3://{bucket_name}/{path} {copy_path}

まとめて取得する場合、syncコマンドを利用

S3に単体ファイル移動・コピー

■移動
aws --profile s3_user s3 mv {local_file_path} s3://{bucket_name}/{target_path}

■コピー
aws --profile s3_user s3 mv {local_file_path} s3://{bucket_name}/{target_path}

まとめてアップする場合は、syncコマンドを利用

S3のファイルsync

syncはパスを指定してファイルを転送します。

■コマンドの基本形
aws --profile s3_user s3 sync {sync元のpath} {sync先のpath}

■aws s3へファイルをアップロードする場合(パスの末尾にスラッシュはつけない)
aws --profile s3_user s3 sync /home/www/target_dir s3://{buckect}/{sync_target_path}

■aws s3からファイルをダウンロードする場合(パスの末尾にスラッシュはつけない)
aws --profile s3_user s3 sync s3://{buckect}/{sync_target_path} /home/www/target_dir

syncするファイルの選別を行う場合、syncするファイルのパスに含まれる文字列で指定が可能です。
--exclude="*" 全てのファイルを除外する
--include="{target_dir_name}" syncするターゲットのDIRを含むファイルだけを指定する

ドライランのオプション指定で、syncのリハーサルが可能です。極力一発でのsyncはやめて、dryrunでファイルやターゲットが正しいかチェックしましょう。
--dryrun

■オプションの付け方
aws s3 sync hogehoge s3://hoge_buckect/hogehoge --exclude="*" --include="202407"
※一度全てのファイルを除外し、includeで202407がパスに含まれるものだけsyncする
※オプションの前後を入れ替えると動作が変わる為、注意

syncはdefaultではタイムスタンプやバイナリサイズなどを見るような動作をします。
syncオプションを付け替えると、sync対象の取り方が変わります。

S3のファイル削除

■単体ファイル削除のケース
aws --profile s3_user s3 rm s3://{buckect}/{sync_target_path}

DIR単位での削除のケース
aws --profile s3_user s3 rm s3://{buckect}/{sync_target_path} --recursive
recursiveオプションを忘れないように
※末尾のスラッシュは不要

おわりに

AWS EC2環境下であれば、気軽にS3へのファイルのアップロード・ダウンロードができてうれしい。
PHPのLaravelなどAWSサービスへの対応を行っているフレームワークを使っていれば、S3を介したファイルやり取りも楽になってきているので、気軽に使っていければと思います。

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?