问题:使用boto3连接到CloudFront时如何选择AWS配置文件

我正在使用Boto 3 python库,并想连接到AWS CloudFront。我需要指定正确的AWS Profile(AWS凭证),但是在查看官方文档时,我看不到指定它的方法。

我正在使用代码初始化客户端: client = boto3.client('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.


回答 0

我认为文档在展示如何执行此操作方面并不出色。一段时间以来,它一直是受支持的功能,并且此pull request中有一些细节。

因此,有三种不同的方法可以做到这一点:

选项A)使用配置文件创建新会话

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

选项B)在代码中更改默认会话的配置文件

    boto3.setup_default_session(profile_name='dev')

选项C)使用环境变量更改默认会话的配置文件

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

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')

回答 1

这样做以使用名称为’dev’的配置文件:

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

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)

回答 2

boto3文档的本部分非常有用。

这对我有用:

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

This section of the boto3 documentation is helpful.

Here’s what worked for me:

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

回答 3

只需在客户端调用之前将配置文件添加到会话配置即可。 boto3.session.Session(profile_name='YOUR_PROFILE_NAME').client('cloudwatch')

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


声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。