Last active
December 29, 2019 03:11
-
-
Save FanchenBao/fbe896a90ff59d737df48e4f87c6d9d2 to your computer and use it in GitHub Desktop.
Combine both obtaining credentials and downloading a file from S3, using AWS IoT Thing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import boto3 | |
import requests | |
def obtain_temporary_credentials() -> Tuple[str, str, str]: | |
"""Obtain temporary credentials from AWS IoT device certificate and private key.""" | |
credential_provider_endpoint = 'https://<your_credentials_provider_endpoint>/role-aliases/iot-s3-access-role-alias/credentials' | |
device_cert_path = '<path_to_device_cert>' | |
device_private_key_path = '<path_to_device_private_key>' | |
resp = requests.get( | |
credential_provider_endpoint, | |
headers={'x-amzn-iot-thingname': 'TestThing'}, | |
cert=(device_cert_path, device_private_key_path), | |
) | |
if resp: # check whether https request succeeds | |
credentials = resp.json() | |
access_key_id = credentials['credentials']['accessKeyId'] | |
secrete_access_key = credentials['credentials']['secretAccessKey'] | |
session_token = credentials['credentials']['sessionToken'] | |
return access_key_id, secrete_access_key, session_token | |
else: | |
print('error requesting temporary access to AWS S3') | |
return '', '', '' | |
def download_file_from_s3() -> None: | |
"""Using the credentials obtained to access S3 via boto3 and download a file.""" | |
access_key_id, secrete_access_key, session_token = obtain_temporary_credentials() | |
if access_key_id: | |
s3_cli = boto3.client( # access S3 with obtained credentials | |
's3', | |
aws_access_key_id=access_key_id, | |
aws_secret_access_key=secrete_access_key, | |
aws_session_token=session_token, | |
) | |
# download a file (path to file must match the permission granted to s3-access-role) | |
s3_cli.download_file('<bucket_name>', '<path_to_file>', '<path_for_download>') | |
else: | |
print('No credentials available for accessing AWS S3') | |
# driver | |
download_file_from_s3() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment