[英]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.我正在使用 Boto 3 python 库,并希望连接到 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.我需要指定正确的 AWS 配置文件(AWS 凭证),但是查看官方文档,我看不出有什么方法可以指定它。
I am initializing the client using the code: client = boto3.client('cloudfront')
我正在使用代码初始化客户端: 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.我找不到可以指定使用哪个配置文件的方法。
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 .然而,它已经成为受支持的功能有一段时间了,并且在这个pull request 中有一些细节。
So there are three different ways to do this:因此,有三种不同的方法可以做到这一点:
Option A) Create a new session with the profile选项 A) 使用配置文件创建新会话
dev = boto3.session.Session(profile_name='dev')
Option B) Change the profile of the default session in code选项 B) 在代码中更改默认会话的配置文件
boto3.setup_default_session(profile_name='dev')
Option C) Change the profile of the default session with an environment variable选项 C) 使用环境变量更改默认会话的配置文件
$ AWS_PROFILE=dev ipython
>>> import boto3
>>> s3dev = boto3.resource('s3')
Do this to use a profile with name 'dev':这样做以使用名为“dev”的配置文件:
session = boto3.session.Session(profile_name='dev')
s3 = session.resource('s3')
for bucket in s3.buckets.all():
print(bucket.name)
This section of the boto3 documentation is helpful. boto3 文档的这一部分很有帮助。
Here's what worked for me:以下是对我有用的内容:
session = boto3.Session(profile_name='dev')
client = session.client('cloudfront')
Just add profile to session configuration before client call.只需在客户端调用之前将配置文件添加到会话配置中。 boto3.session.Session(profile_name='YOUR_PROFILE_NAME').client('cloudwatch')
1- To use Session boto3.session.Session
: 1- 使用 Session boto3.session.Session
:
import boto3
aws_session = boto3.session.Session(profile_name='dev')
s3 = aws_session.resource('s3')
2- To use resource boto3.resource
: 2-使用资源boto3.resource
:
import boto3
boto3.setup_default_session(profile_name='dev')
s3 = boto3.resource('s3')
3- OR, Pass environment variables AWS_ACCESS_KEY_ID
and AWS_SECRET_ACCESS_KEY
to boto3. 3- 或者,将环境变量AWS_ACCESS_KEY_ID
和AWS_SECRET_ACCESS_KEY
给 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')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.