ChatGPT解决这个技术问题 Extra ChatGPT

How to choose an AWS profile when using boto3 to connect to CloudFront

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.

See also: read and download a file from AWS S3 with profiles
have you tried using the keys into the code? (also you can use env var to hide it from the code) client = boto3.client('s3', aws_access_key_id = '<access-key>', aws_secret_access_key = '<secret-key>')

A
Alex Ramos

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

    boto3.setup_default_session(profile_name='dev')

Option C) Change the profile of the default session with an environment variable

    $ AWS_PROFILE=dev ipython
    >>> import boto3
    >>> s3dev = boto3.resource('s3')

Shouldn't the env variable be AWS_PROFILE?
Thanks for that! didn't seem to find that information anywhere so far. It seems I only needed step 2 to make this work though. What did step 1 do? (since the dev variable isn't used or passed into anything else?)
Those are options, not steps. In the first option you create a new session to use rather than the default session. So to create a client with that session you would do something like dev.client('s3') instead of boto3.client('s3')
off topic, ipython was also useful for me.
Get the profile list using boto3.session.Session().available_profiles - it is a list. Then use the one you want @jordan-phillips.
H
He3lixxx

This section of the boto3 documentation is helpful.

Here's what worked for me:

session = boto3.Session(profile_name='dev')
client = session.client('cloudfront')

I really thought this was going to work for me in my work with Secrets Manager. But Secrets Manager + KMS = nope.
a
asmaier

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)

M
MrKulli

Just add profile to session configuration before client call. boto3.session.Session(profile_name='YOUR_PROFILE_NAME').client('cloudwatch')


This worked (with decryption). Splitting this over two commands didn't.

关注公众号,不定期副业成功案例分享
Follow WeChat

Success story sharing

Want to stay one step ahead of the latest teleworks?

Subscribe Now