繁体   English   中英

仅从 EC2 实例配置文件中获取 boto3 凭据

[英]Fetch boto3 credentials only from EC2 instance profile

boto3 文档列出了搜索凭据的顺序,并且仅在最后才从 EC2 实例元数据服务中获取凭据。

如何强制boto3仅从 EC2 实例配置文件或实例元数据服务中获取凭据?

我遇到了这个,它让我从元数据服务中获取临时凭证,然后我可以传递它来创建一个boto3 session。

但是我的问题是是否有更好的方法来做到这一点? 是否可以通过指定要使用的provider (即InstanceMetadataProvider - link )来创建boto3 session? 我尝试了很多文档搜索,但无法弄清楚。

原因 - 此脚本运行的上下文也有带有 AWS 密钥集的环境变量,这显然优先,但是我需要脚本仅在分配给 EC2 实例的 IAM 角色下运行。

所以我最终这样做了,按预期工作。 始终使用来自实例角色的临时凭证。 该脚本是短暂的,因此信用证的有效性不是问题。

from botocore.credentials import InstanceMetadataProvider, InstanceMetadataFetcher

provider = InstanceMetadataProvider(iam_role_fetcher=InstanceMetadataFetcher(timeout=1000, num_attempts=2))
creds = provider.load().get_frozen_credentials()
client = boto3.client('ssm', region_name='us-east-1', aws_access_key_id=creds.access_key, aws_secret_access_key=creds.secret_key, aws_session_token=creds.token)

如果有更好的方法,请随时发布。

import boto3 import botocore botocore_session = botocore.session.get_session() credential_provider = botocore_session.get_component('credential_provider') instance_metadata_provider = credential_provider.get_provider('iam-role') credential_provider.insert_before('env', instance_metadata_provider) boto3_session = boto3.Session(botocore_session=botocore_session) client = boto3_session.client(...) resource = boto3_session.resource(...)

您也可以使用 boto3。

>>> session = boto3.Session(region_name='foo_region')
>>> credentials = session.get_credentials()
>>> credentials = credentials.get_frozen_credentials()
>>> credentials.access_key
u'ABC...'
>>> credentials.secret_key
u'DEF...'
>>> credentials.token
u'ZXC...'
>>> access_key = credentials.access_key
>>> secret_key = credentials.secret_key

这是一个类似的想法,但我发现它返回得更快

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM