LoginSignup
9
10

More than 1 year has passed since last update.

AWS S3 の使い方 (aws-cli, boto3)

Last updated at Posted at 2019-01-07

AWS S3 を aws-cli と boto3 で使ってみます。
bucket01 というバケットにアクセスできるとします。

A) aws-cli

A-0) バケットの一覧

aws s3 ls

A-1) ファイルの一覧

aws s3 ls s3://bucket01

A-2) ファイルのアップロード

sample01.txt をアップロードします。

aws s3 cp sample01.txt s3://bucket01

A-3) ファイルの削除

sample01.txt を削除します。

aws s3 rm s3://bucket01/sample01.txt

A-4) ファイルのダウンロード

sample02.txt をダウンロード

aws s3 cp s3://bucket01/sample02.txt .

A-5) フォルダーのりネーム

aws s3 --recursive mv s3://bucket01/folder_a \
        s3://bucket01/folder_b

A-6) バケットの作成

BUCKET="bucket01"
#
aws s3 mb s3://$BUCKET

A-7) バケットの削除

BUCKET="bucket01"
aws s3 rb s3://$BUCKET --force

B) boto3

B-0) バケットの一覧

list_buckets.py
#! /usr/bin/python

import boto3

s3 = boto3.resource('s3')

for bucket in s3.buckets.all():
    print(bucket.name)

B-1) ファイルの一覧

s3_list.py
#! /usr/bin/python
#
import boto3

bucket_name = "bucket01"
s3 = boto3.resource('s3')

my_bucket = s3.Bucket(bucket_name)
for object in my_bucket.objects.all():
    print(object)
    print(object.key)
#

B-2) ファイルのアップロード

sample01.txt をアップロードします。

s3_upload.py
#! /usr/bin/python
#
import boto3

bucket_name = "bucket01"
s3 = boto3.resource('s3')

s3.Bucket(bucket_name).upload_file('sample01.txt', 'sample01.txt')

B-3) ファイルの削除

sample01.txt を削除します。

s3_rm.py
#! /usr/bin/python
#
import boto3

bucket_name = "bucket01"
s3 = boto3.resource('s3')

my_bucket = s3.Bucket(bucket_name)
s3_client = boto3.client('s3')
s3_client.delete_object(Bucket=bucket_name, Key='sample01.txt')

B-4) ファイルのダウンロード

sample02.txt をダウンロード

s3_download.py
#! /usr/bin/python
#
import boto3

bucket_name = "bucket01"
s3 = boto3.resource('s3')

s3.Bucket(bucket_name).download_file('sample02.txt', 'sample02.txt')

B-5) データの書き込み

sample.json を作成

s3_put.py
#! /usr/bin/python
#
import boto3
import json

s3 = boto3.resource('s3')

bucket_name = "bucket01"

json_key = "sample.json"
obj = s3.Object(bucket_name,json_key)

test_json = {'key': 'valueaaa',
        'key2': 'Hello'}
data = json.dumps(test_json).encode('utf-8')
r = obj.put(Body = data)

# get json data
print(obj.get()['Body'].read())

C) wget

バケットにバケットポリシー s3:GetObject をつければ、次のようにして、ファイルのダウンロードが出来ます。

wget https://bucket01.s3.amazonaws.com/sample02.txt

ポリシーは次のようになります。

{
  "Id": "Policy1546858622092",
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "Stmt1546858528773",
      "Action": [
        "s3:GetObject"
      ],
      "Effect": "Allow",
      "Resource": "arn:aws:s3:::bucket01/*",
      "Principal": "*"
    }
  ]
}

参考ページ
AWS S3 でページを公開する

9
10
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
9
10