How to specify credentials when connecting to boto3 S3?

In boto, I specified my credentials when connecting to S3 this way:

import boto
from boto.s3.connection import Key, S3Connection
S3 = S3Connection( settings.AWS_SERVER_PUBLIC_KEY, settings.AWS_SERVER_SECRET_KEY )

Then I could use S3 to perform my operations (in my case, removing an object from the recycle bin).

With boto3, all the examples I found are as follows:

import boto3
S3 = boto3.resource( 's3' )
S3.Object( bucket_name, key_name ).delete()

I cannot provide my credentials, so all attempts fail InvalidAccessKeyId.

How can I specify credentials with boto3?

+60
source share
4 answers

You can create session :

import boto3
session = boto3.Session(
    aws_access_key_id=settings.AWS_SERVER_PUBLIC_KEY,
    aws_secret_access_key=settings.AWS_SERVER_SECRET_KEY,
)

Then use this session to get the S3 resource:

s3 = session.resource('s3')
+86
source

client , .

 s3_client = boto3.client('s3', 
                      aws_access_key_id=settings.AWS_SERVER_PUBLIC_KEY, 
                      aws_secret_access_key=settings.AWS_SERVER_SECRET_KEY, 
                      region_name=REGION_NAME
                      )
+43

@JustAGuy . , , AWS CLI . , CLI SDK ~/.aws. , AWS CLI python.

Cli Pypi, . , Cli

$> pip install awscli  #can add user flag 
$> aws configure
AWS Access Key ID [****************ABCD]:[enter your key here]
AWS Secret Access Key [****************xyz]:[enter your secret key here]
Default region name [us-west-2]:[enter your region here]
Default output format [None]:

After that, you can access botoany API without specifying keys (if you do not want to use other credentials).

0
source

Source: https://habr.com/ru/post/1684822/


All Articles