Created
September 30, 2020 15:25
-
-
Save mrtj/8c28f82dcbccf8b6ae6066e849ec0131 to your computer and use it in GitHub Desktop.
Call any AWS service directly using the credentials of AWS IoT device certificate
This file contains hidden or 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
''' | |
A snippet demonstrating how an AWS IoT device can make direct calls to every AWS | |
service using only the device certificate and private key. | |
For more info see the docs at https://docs.aws.amazon.com/iot/latest/developerguide/authorizing-direct-aws.html | |
to create the role and the role alias. To get the AWS IoT credential provider endpoint of your account you can use | |
$ aws iot describe-endpoint --endpoint-type iot:CredentialProvider | |
Dependencies: requests and boto3 | |
$ pip install requests boto3 | |
''' | |
import requests | |
import boto3 | |
def get_session(endpoint, role_alias, cert, key, root_ca): | |
''' Get a boto3 session using the credentials of AWS IoT device certificate. | |
Params: | |
- endpoint: The AWS IoT credential provider endpoint of your account | |
- role_alias: The name of the AWS IoT role alias | |
- cert: The filename of your device certificate | |
- key: The filename of your private key | |
- root_ca: The filename of the root CA certificate | |
Returns: | |
- A configured boto3 session object that can be used to make direct calls | |
to AWS services enabled by the assumed role. | |
''' | |
url = f'https://{endpoint}/role-aliases/{role_alias}/credentials' | |
resp = requests.get(url, cert=(cert, key), verify=root_ca) | |
credentials = resp.json()['credentials'] | |
session = boto3.session.Session( | |
aws_access_key_id=credentials['accessKeyId'], | |
aws_secret_access_key=credentials['secretAccessKey'], | |
aws_session_token=credentials['sessionToken'] | |
) | |
return session |
Thank you for this!
For anyone else that comes across this- if you want to use ${credentials-iot:ThingName} in your iam role, you must add the "x-amzn-iot-thingname" header to the request
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Test the session: