3
0

More than 1 year has passed since last update.

Colaboratory と AWSの連携

Last updated at Posted at 2022-06-26

この記事の目的

Colaboratoryでboto3を経由してAWSのAPIを実行する環境を作成します。

👇これより先は下記記事の内容を前提とします

AWS設定ファイルをGoogle Drive へ保存する

ColaboratoryからAWS認証情報を読み込むため、aws configureの実行により生成された設定ファイルconfigおよびcredentialsをGoogle Driveへ保存します。

  • AWS設定ファイルconfigおよびcredentialsの場所
    Linux または macOS では「~/.aws/」、Windows では「C:/Users/USERNAME/.aws/」にあります。
  • AWS設定ファイルのGoogle Drive保存先
    Google Drive保存先は任意の場所ですが、以下の説明では[Google Drive]/.aws/を利用します。
    👇
    [Google Drive]/.aws/config
    [Google Drive]/.aws/credentials

Google Drive のマウント

Colaboratoryから下記コードを実行しGoogle Driveをマウントします。

from google.colab import drive
drive.mount('/content/drive')

image

Google Driveへのアクセス許可を確認するダイアログが表示されます。
image

image

AWS認証設定

Colaboratoryから下記コードを実行しAWSの認証ファイルを設定します。

import os

path1 = "/content/drive/MyDrive/.aws/config"
os.environ['AWS_CONFIG_FILE'] = path1

path2 = "/content/drive/MyDrive/.aws/credentials"
os.environ['AWS_SHARED_CREDENTIALS_FILE'] = path2

image

boto3のインストール

Colaboratoryから下記コードを実行しboto3をインストールします。

ps
!pip install boto3

image

boto3実行サンプル

Colaboratoryからboto3のAPIを利用できます。

import boto3

bucket_name = 'your.bucket.name.xxxxx'
key_prefix = ''

s3 = boto3.resource('s3')
bucket = s3.Bucket(bucket_name)
list = bucket.meta.client.list_objects_v2(Bucket=bucket.name, Prefix=key_prefix)

for obj in list.get("Contents"):
  print("file:",obj.get("Key"),obj.get("Size"), obj.get("LastModified"))

image

👇前提記事

👇参考URL

3
0
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
3
0