Boto3のインストール方法と初期設定をご紹介します。
なお、以下公式サイトを参考としています。
Installation
事前にpipをインストールしておいてください。
Botoのインストールは以下のコマンドで完了です。
pip install boto3
Using Boto 3
Botoを使用するには、まずBotoをimportし、AWSのどのサービスに対して使用するのかを明示的にしてください。
ここでは、AWS S3のサービスを使用します。
To use Boto 3, you must first import it and tell it what service you are going to use:
import boto3 # Let's use Amazon S3 s3 = boto3.resource('s3')
加えて以下の文を追記します。
先ほどの例で、既にS3のリソースを取得しているので、様々なリクエストを作成したり、リスポンスを処理できます。
この例では、全てのバケット名を表示します。
Now that you have an s3 resource, you can make requests and process responses from the service. The following uses the buckets collection to print out all bucket names:
# Print out bucket names for bucket in s3.buckets.all(): print(bucket.name)
上記の物を合わせた物がこちらです。
以下のコードを実行すると、全てのバケット名を表示します。
なお、「aws configure」で設定されたデフォルトの設定(アクセスキーやシークレットキー)が使用されますので、事前に設定しておきましょう。
import boto3 # Let's use Amazon S3 s3 = boto3.resource('s3') # Print out bucket names for bucket in s3.buckets.all(): print(bucket.name)
profileを指定して使用する場合は以下のコードを使用してください。
「profile = ‘sample-profile’」の部分を使用するプロファイルに変更してください。
プロファイルの設定についてはawscli 複数アカウント profileを参照してください。
import boto3 from boto3.session import Session profile = 'sample-profile' session = Session(profile_name=profile) s3 = session.resource('s3') for bucket in s3.buckets.all(): print(bucket.name)
ちなみに、以下のコードを実行すると、バケットの情報をPythonの辞書で取得できるので何かと便利です。
※プロファイルを指定しなかった場合はデフォルトプロファイルが自動的に使用されますのでご注意ください。
- https://boto3.readthedocs.io/en/latest/reference/services/s3.html#S3.Client.list_buckets
import boto3 # Create an S3 client s3 = boto3.client('s3') # Call S3 to list current buckets response = s3.list_buckets() print(response)
コメント