Skip to content

Instantly share code, notes, and snippets.

@filipeandre
Last active August 7, 2025 08:35
Show Gist options
  • Save filipeandre/63cbda4788939c0ec9d345d12ba83abc to your computer and use it in GitHub Desktop.
Save filipeandre/63cbda4788939c0ec9d345d12ba83abc to your computer and use it in GitHub Desktop.
Temp AWS credentials
import boto3
import os
def export_temp_credentials():
session = boto3.Session()
credentials = session.get_credentials().get_frozen_credentials()
print(f'os.environ["AWS_ACCESS_KEY_ID"] = "{credentials.access_key}"')
print(f'os.environ["AWS_SECRET_ACCESS_KEY"] = "{credentials.secret_key}"')
# If using temporary credentials (like in CloudShell), session_token will be present
if credentials.token:
print(f'os.environ["AWS_SESSION_TOKEN"] = "{credentials.token}"')
if __name__ == "__main__":
export_temp_credentials()
import boto3
import json
from botocore.exceptions import ClientError
def export_temp_credentials_as_dict(region="us-east-1"):
session = boto3.Session(region_name=region)
credentials = session.get_credentials().get_frozen_credentials()
sts = session.client("sts")
try:
identity = sts.get_caller_identity()
account_id = identity["Account"]
except Exception as e:
print(f"❌ Error fetching account ID: {e}")
return
# Try to get account name from AWS Organizations
label = f"Account {account_id}" # fallback
try:
org = session.client("organizations")
response = org.describe_account(AccountId=account_id)
account_name = response["Account"]["Name"]
label = f"{account_name} ({account_id})"
except ClientError as e:
print(f"⚠️ Could not retrieve account name: {e.response['Error']['Message']}")
except Exception as e:
print(f"⚠️ Unexpected error getting account name: {e}")
output = {
"label": label,
"aws_access_key_id": credentials.access_key,
"aws_secret_access_key": credentials.secret_key,
"aws_session_token": credentials.token,
"region": region
}
print(json.dumps(output, indent=4))
if __name__ == "__main__":
export_temp_credentials_as_dict("us-east-1")
@filipeandre
Copy link
Author

filipeandre commented Jul 10, 2025

python3 <(curl -s https://gist.githubusercontent.com/filipeandre/63cbda4788939c0ec9d345d12ba83abc/raw/0b6f570b74e3be5bb30bdb09636407b05e59199d/create_temp_aws_credentials.py)

@filipeandre
Copy link
Author

filipeandre commented Aug 7, 2025

python3 <(curl -s https://gist.githubusercontent.com/filipeandre/63cbda4788939c0ec9d345d12ba83abc/raw/5f073229a64b404dafa7832108d74b5fef37c00a/create_temp_aws_credentials2.py)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment