AWS SDKを触ったことがなかったので、Python向けのSDKであるbotoをAWSのサイトにあるtutorialを参考に試してみます。botoはバージョンアップされており、現行の最新バージョンはboto3となっているので、その点を考慮しつつ勉強。
tutorialのページはこちら。
こっちはboto3のreferenceね。
Boto 3 Documentation — Boto 3 Docs 1.6.19 documentation
とりあえず、awscliとbotoをインストール。
$ pip install awscli $ pip install boto3 $ pip freeze | grep -e aws -e boto awscli==1.14.16 boto3==1.5.6 botocore==1.8.20
awsのクレデンシャル情報を登録。今回は何も考えずにAdmin権限を与えたIAMユーザを設定しています。
$ aws configure AWS Access Key ID [None]: XXXXXXXXXXXXXXXXX AWS Secret Access Key [None]: XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX Default region name [None]: ap-northeast-1 Default output format [None]: $ aws configure list Name Value Type Location ---- ----- ---- -------- profile <not set> None None access_key ****************QU7A shared-credentials-file secret_key ****************oOmg shared-credentials-file region ap-northeast-1 config-file ~/.aws/config
尚、boto3には以下5つの主要機能があるとのこと。高レベルAPIでオブジェクト指向のResourcesと、昔から低レベルAPIのClientsがあります。今回は、高レベルAPIであるResourcesにて処理を書いてみます。
- Resources
- an object-oriented interface to Amazon Web Services (AWS). They provide a higher-level abstraction than the raw, low-level calls made by service clients.
- Collections
- Clients
- Paginators
- Some AWS operations return results that are incomplete and require subsequent requests in order to attain the entire result set. The process of sending subsequent requests to continue where a previous request left off is called pagination.
- Waiters
- a way to block until a certain state has been reached.
S3をいじってみるぞ。bucketをつくろう。
> import boto3 > s3 = boto3.resource('s3') > s3.create_bucket(Bucket='mybucket-kiritanperopero', CreateBucketConfiguration={'LocationConstraint': 'ap-northeast-1'}) s3.Bucket(name='mybucket-kiritanperopero')
つづいて、objectをつくるぞ。
> object = s3.Object('mybucket-kiritanperopero', 'tmp/zunda.txt') > body = u'ずんねえさま' > object.put(Body=body)
つくったobjectの中身を見るぞ。
> object.get()['Body'].read().decode('utf-8') 'ずんねえさま'