Table of Contents
AWS cpとsyncコマンド
Def: aws cp and sync
aws cpコマンドはcp — AWS CLI Latest Command Referenceによると
- Copies a local file or S3 object to another location locally or in S3.
一方, aws syncコマンドはsync - AWS CLI Latest Command Referenceによると
- Syncs directories and S3 prefixes. Recursively copies new and updated files from the source directory to the destination.
aws cpはオブジェクトをコピーするコマンドであるのに対し, aws syncは対象ディレクトリ内部の新規作成または更新されたファイルについて同期するコマンドです. 実際に使うにあたって意識すべき挙動の差は以下です
aws cp: destination areaにファイルがすでにあろうがなかろうがコピーするaws sync: 同期の前にdestination areaを一度見て, 新規作成 or 更新があったものについてのみ同期する
aws syncはコピーの前にファイルのメタデータを参照するので, updateなどの場合はaws cpよりもパフォーマンスが良いですが, 新規にすべてのファイルをコピーする場合はaws cpの方がパフォーマンスが良くなります.
How to Use aws cp and aws sync
S3バケットの特定のディレクトリをローカルへコピーする場合,
aws sync:sourceとdestinationのPATHを指定aws cp:sourceとdestinationのPATHを指定 +--recursiveoptionの追加
という差異があります. 基本構文は以下です:
1
2
3
4
5
## aws sync
% aws s3 sync "s3://source-path" <destination-path>
## aws cp
% aws s3 cp --recursive "s3://source-path" <destination-path>
--dryrun optionのススメ
いきなり思いついたスクリプトを実行すると誤ってファイルを消してしまったり, 想定外のバケットに対して処理を始めてしまうリスクがあります. そのため, スクリプトを実行する前に --dryrun optionを用いて, どのような挙動になるかテストすることが推奨されます.
Option: –dryrun
--dryrun : (boolean) Displays the operations that would be performed using the specified command without actually running them.
利用例:
1
% aws s3 sync --dryrun "s3://source-path" <destination-path>
特定のディレクトリやファイルのみをコピーしたい場合
コピーや同期の対象オブジェクトを指定した条件でfilterしたい場合, --excludeと--includeを組み合わせて用います.
条件指定に方法と--excludeと--include組み合わせルールについてまず確認します.
Rule 1: Filter Valueのパターン
除外や含むパターンを指定する場合--exclude "<value>", --include "<value>"という形で指定しますが,
"<value>"で指定できるパターンの書き方は以下となります
*: Matches everything?: Matches any single character[sequence]: Matches any character in sequence[!sequence]: Matches any character not in sequence
Rule2: 指定の順番と効力
Filter条件が複数指定された場合, 後者の方の効力が優先する. つまり,
1
--exclude "*" --include "*.txt"
と指定すると, 一旦すべてのファイルを除外してから, .txt拡張子のファイルを連携する(=.txt拡張子のみ連携する)挙動になります. 一方,
1
--include "*.txt" --exclude "*"
の順番で指定すると, *に該当するオブジェクト(=すべてのオブジェクト)が除外されます.
Filterコマンドの例
1
2
3
4
5
6
7
8
9
s3://hogehoge
├── diary
│ ├── 2022-01-01.csv
│ ├── 2022-02-01.csv
│ ├── 2023-01-01.csv
│ └── 2023-02-01.csv
├── foo.txt
├── bar.txt
└── baz.jpg
という構成のS3バケットhogehogeが与えられたとします. これをローカルのカレントディレクト以下にある空のsandboxディレクトリにコピーする場合
1
% aws s3 cp --recursive "s3://hogehoge" ./sandbox --exclude "*" --include "*.csv"
とすると, ローカル側では
1
2
3
4
5
6
./sandbox
└── diary
├── 2022-01-01.csv
├── 2022-02-01.csv
├── 2023-01-01.csv
└── 2023-02-01.csv
となります.
1
% aws s3 cp --recursive "s3://hogehoge" ./sandbox --exclude "*.csv"
と実行すると
1
2
3
4
s3://hogehoge
├── foo.txt
├── bar.txt
└── baz.jpg
さらに, 2023年のcsvファイルのみ連携させたい場合は
1
% aws s3 cp --recursive "s3://hogehoge" ./sandbox --exclude "*" --include "*2023-0[12]-01.csv"
と実行すると
1
2
3
4
./sandbox
└── diary
├── 2023-01-01.csv
└── 2023-02-01.csv
References
- cp — AWS CLI Latest Command Reference
- sync — AWS CLI Latest Command Reference
- AWS CLI Command Reference
(注意:GitHub Accountが必要となります)