The boto3
documentation lists the order in which credentials are searched and the credentials are fetched from the EC2 instance metadata service only at the very last.
How do I force boto3
to fetch the credentials only from the EC2 instance profile or the instance metadata service?
I came across this which lets me get the temporary credentials from the metadata service and then I could pass this on to create a boto3
session.
However my question is whether there is a better way to do this? Is it possible to create a boto3
session by specifying the provider
to use ie InstanceMetadataProvider
- link ? I tried searching the docs a lot, but couldn't figure it out.
The reason - the context under which this script runs also has environment variables with AWS keys set which would obviously take precedence, however I need the script to run only with the IAM role assigned to the EC2 instance.
So I ended up doing this, works as expected. Always uses the temp creds from the instance role. The script is short-lived so the validity of the creds is not an issue.
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)
If there is a better way to do, please feel free to post.
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(...)
You could also use 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
It's a similar idea, but I find it returns much faster
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.