Skip to content

Instantly share code, notes, and snippets.

@nmagee
Created March 1, 2019 14:44
Show Gist options
  • Select an option

  • Save nmagee/42a448f8b84223ee6d7c233ca5c70f9a to your computer and use it in GitHub Desktop.

Select an option

Save nmagee/42a448f8b84223ee6d7c233ca5c70f9a to your computer and use it in GitHub Desktop.
Get temporary AWS Credentials for external users by assuming a defined IAM Role
#!/usr/local/bin/python
import boto3
import json
# The calls to AWS STS AssumeRole must be signed with the access key ID
# and secret access key of an existing IAM user or by using existing temporary
# credentials such as those from antoher role.
# Python SDK documentation:
# http://boto3.readthedocs.io/en/latest/reference/services/sts.html#client
sts_client = boto3.client('sts')
# Call the assume_role method of the STSConnection object and pass the role
# ARN and a role session name. Keys/token expire in 900 seconds.
assumed_role_object=sts_client.assume_role(
RoleArn="arn:aws:iam::123456789012:role/my-role",
RoleSessionName="AssumeRoleSession1",
DurationSeconds=900
)
# From the response that contains the assumed role, get the temporary
# credentials that can be used to make subsequent API calls
credentials=assumed_role_object['Credentials']
print(credentials)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment