Help us understand the problem. What is going on with this article?

[AWS] boto3のSessionでアクセス権を切り替える

More than 3 years have passed since last update.

事前準備

IAMで、default, dev, prodユーザーを作成します。
devには、AmazonS3FullAccessのポリシーをアタッチし、S3へのアクセスを許可します。
S3に、bucket1, bucket2, bucket3を用意します。

credentialsファイルを利用

  • credentialsファイル

    ~/.aws/credentials or C:\Users\USER_NAME\.aws\credentials

    [default]
    aws_access_key_id = DEFAULT_ID
    aws_secret_access_key = SECRET_KEY1
    
    [dev]
    aws_access_key_id = DEV_ID
    aws_secret_access_key = SECRET_KEY2
    
    [prod]
    aws_access_key_id = PROD_ID
    aws_secret_access_key = SECRET_KEY3
    
  • Pythonプログラム

    import boto3.session
    
    dev_sess = boto3.session.Session(profile_name='dev')
    s3 = dev_sess.resource('s3')
    for bucket in s3.buckets.all():
        print(bucket.name)
    

    ※ profile_nameのデフォルトは、profile_name='default'です。

アクセスID、シークレットキーを直接指定

  • Pythonプログラム

    import boto3.session
    
    dev_sess = boto3.session.Session(
                                aws_access_key_id='DEV_ID',
                                aws_secret_access_key='SECRET_KEY2')
    s3 = dev_sess.resource('s3')
    for bucket in s3.buckets.all():
        print(bucket.name)
    

    ※ ID/パスワードがプログラムに埋め込まれています。実運用では避けましょう。

実行結果

  • 'dev'を指定
bucket1
bucket2
bucket3
  • 'prod'を指定
ClientError: An error occurred (AccessDenied) when calling the ListBuckets operation: Access Denied
  • 'foo'を指定
ProfileNotFound: The config profile (foo) could not be found
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away