Skip to content

Instantly share code, notes, and snippets.

@ronan-cunningham
Last active September 25, 2024 08:21
Show Gist options
  • Save ronan-cunningham/2ae8f2248d05120333dbca5b1194a5d1 to your computer and use it in GitHub Desktop.
Save ronan-cunningham/2ae8f2248d05120333dbca5b1194a5d1 to your computer and use it in GitHub Desktop.
Assume role and check credentials with boto
import boto3
from botocore.exceptions import NoCredentialsError, PartialCredentialsError
from botocore.config import Config
import pprint
config = Config(
region_name = region,
retries = {
'max_attempts': 10,
'mode': 'standard'
}
)
role_arn='arn:aws:iam::111111:role/path/SomeRole'
session_name='whatever'
default_region='eu-west-1'
external_id='whatever'
region = None
def who_ami(session :object)-> None:
pp = pprint.PrettyPrinter(indent=4)
client = session.client("sts", region_name=region,config=config)
response = client.get_caller_identity()
pp.pprint(response)
def assume_role(role_arn:str, session_name:str)->object:
try:
sts_client = boto3.client('sts')
# Assume the specified role
response = sts_client.assume_role(
RoleArn=role_arn,
RoleSessionName=session_name,
ExternalId=external_id
)
# Extract the assumed role credentials
credentials = response['Credentials']
return credentials
except (NoCredentialsError, PartialCredentialsError) as e:
print(f"Error in assuming role: {e}")
raise
def get_boto_session(credentials:object)->object:
return boto3.Session(
aws_access_key_id=credentials["AccessKeyId"],
aws_secret_access_key=credentials["SecretAccessKey"],
aws_session_token=credentials["SessionToken"],
)
credentials = assume_role(role_arn, session_name)
if credentials:
session = get_boto_session(credentials)
who_ami(session)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment