LoginSignup
5

More than 1 year has passed since last update.

S3のファイルをCLIで一括ダウンロード ( + IAM最小権限の設定)

Last updated at Posted at 2022-05-12

はじめに

S3ファイルを複数ダウンロード一括でダウンロードするには、コンソールでは対応できず、CLIでできるようなので、IAMユーザーを最小権限で実行する方法をまとめます。

ついでにアップロードもできるようにします。

事前設定

S3バケット名bucket-nameを作成し、バケット内に/json/test.jsonを作成

CLIのセットアップ設定

下記の記事通りに設定します。

上記記事の内、一部設定を変えます。

  • profile名は、s3-download
  • IAMユーザー名をs3-download
  • IAMユーザーの権限は、次項に記載しています。

IAMユーザー権限

Action権限最小 + バケットを制限 + IP制限

S3のバケットの内bucket-nameというバケット内のファイルのみを許可

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "VisualEditor0",
      "Effect": "Allow",
      "Action": "s3:ListAllMyBuckets",
      "Resource": "*",
      "Condition": {
        "ForAnyValue:IpAddress": {
          "aws:SourceIp": ["xxx.xx.xx.xx/32", "xxx.xx.xx.xx/32"]
        }
      }
    },
    {
      "Sid": "VisualEditor1",
      "Effect": "Allow",
      "Action": ["s3:PutObject", "s3:GetObject"],
      "Resource": "arn:aws:s3:::bucket-name/*"
    },
    {
      "Sid": "VisualEditor2",
      "Effect": "Allow",
      "Action": "s3:ListBucket",
      "Resource": "arn:aws:s3:::*"
    }
  ]
}

Action権限最小 + バケットを制限

S3のバケットの内bucket-nameというバケット内のファイルのみを許可

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "VisualEditor0",
      "Effect": "Allow",
      "Action": "s3:ListAllMyBuckets",
      "Resource": "*"
    },
    {
      "Sid": "VisualEditor1",
      "Effect": "Allow",
      "Action": ["s3:PutObject", "s3:GetObject"],
      "Resource": "arn:aws:s3:::bucket-name/*"
    },
    {
      "Sid": "VisualEditor2",
      "Effect": "Allow",
      "Action": "s3:ListBucket",
      "Resource": "arn:aws:s3:::*"
    }
  ]
}

Action一覧

Action 内容 Resource Condition
ListAllMyBuckets 権限のあるバケットのリスト表示 * IP制限
PutObject ファイルを書込(アップロード) arn:aws:s3:::bucket-name/* -
GetObject ファイルを取得(ダウンロード) arn:aws:s3:::bucket-name/* -
ListBucket バケット内のオブジェクトリストを表示 arn:aws:s3::: -

ダウンロード

bucket-nameバケットのjsonディレクトリ配下のファイルをローカルの./test配下にコピーする

ローカル
// バケット確認
$ aws s3 ls  --profile s3-download
2022-01-10 13:55:47 bucket-name

// ダウンロード
$ aws s3 cp s3://バケット名/ディレクトリパス  ローカルPCのパス  --recursive --profile プロフィール名

$ aws s3 cp s3://bucket-name/json/ ./test --recursive --profile s3-download

download: s3://bucket-name/json/test.json to ./bucket-name

*.jsonのみをダウンロードする場合

ローカル
$ aws s3 cp s3://test_bucket/json/ ./folder --exclude "*" --include "*.json" --recursive --profile s3-download

アップロード

$ aws s3 cp ローカルPCのパス s3://バケット名/ディレクトリパス --recursive --profile

$ aws s3 cp . s3://bucket-name/json/ --recursive --profile s3-download

S3に関する権限設定例

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
5