I am using the Boto 3 python library, and want to connect to AWS CloudFront.
I need to specify the correct AWS Profile (AWS Credentials), but looking at the official documentation, I see no way to specify it.
I am initializing the client using the code:
client = boto3.client('cloudfront')
However, this results in it using the default profile to connect.
I couldn’t find a method where I can specify which profile to use.
Here is Solutions:
We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.
I think the docs aren’t wonderful at exposing how to do this. It has been a supported feature for some time, however, and there are some details in this pull request.
So there are three different ways to do this:
Option A) Create a new session with the profile
dev = boto3.session.Session(profile_name='dev')
Option B) Change the profile of the default session in code
Option C) Change the profile of the default session with an environment variable
$ AWS_PROFILE=dev ipython >>> import boto3 >>> s3dev = boto3.resource('s3')
This section of the boto3 documentation is helpful.
Here’s what worked for me:
session = boto3.Session(profile_name='dev') client = session.client('cloudfront')
Do this to use a profile with name ‘dev’:
session = boto3.session.Session(profile_name='dev') s3 = session.resource('s3') for bucket in s3.buckets.all(): print(bucket.name)
Just add profile to session configuration before client call.
1- To use Session
import boto3 aws_session = boto3.session.Session(profile_name='dev') s3 = aws_session.resource('s3')
2- To use resource
import boto3 boto3.setup_default_session(profile_name='dev') s3 = boto3.resource('s3')
3- OR, Pass environment variables
AWS_SECRET_ACCESS_KEY to boto3.
import boto3 aws_session = boto3.Session( aws_access_key_id=settings.AWS_SERVER_PUBLIC_KEY, aws_secret_access_key=settings.AWS_SERVER_SECRET_KEY, ) s3 = aws_session.resource('s3')
Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂