How to Create a Mock STS AssumeRole Credentials Dict in Python
Build a realistic AWS STS AssumeRole response dict with temporary credentials, expiry time, and assumed role ARN for local testing.
Python code
28 linesimport json
from datetime import datetime, timedelta, timezone
def mock_sts_credentials(role_arn, session_name, duration=3600):
now = datetime.now(timezone.utc)
expiration = now + timedelta(seconds=duration)
credentials = {
"Credentials": {
"AccessKeyId": "ASIAEXAMPLEACCESSKEY",
"SecretAccessKey": "EXAMPLEseCretAccessKey1234567890abcdef",
"SessionToken": "FwoGZXIvYXdzEBEaDCEXAMPLEtokenvalue1234567890==",
"Expiration": expiration.strftime("%Y-%m-%dT%H:%M:%SZ"),
},
"AssumedRoleUser": {
"AssumedRoleId": "AROEXAMPLE:" + session_name,
"Arn": role_arn.replace(":role/", ":assumed-role/") + "/" + session_name,
},
}
return credentials
if __name__ == "__main__":
creds = mock_sts_credentials(
"arn:aws:iam::123456789012:role/MyRole",
"my-session",
)
print(json.dumps(creds, indent=2))
Output
{
"Credentials": {
"AccessKeyId": "ASIAEXAMPLEACCESSKEY",
"SecretAccessKey": "EXAMPLEseCretAccessKey1234567890abcdef",
"SessionToken": "FwoGZXIvYXdzEBEaDCEXAMPLEtokenvalue1234567890==",
"Expiration": "2025-03-15T10:30:00Z"
},
"AssumedRoleUser": {
"AssumedRoleId": "AROEXAMPLE:my-session",
"Arn": "arn:aws:iam::123456789012:assumed-role/MyRole/my-session"
}
}
How it works
This function mimics the exact structure of sts.assume_role's returned credentials so your code can be tested offline. It uses datetime.now(timezone.utc) to generate a UTC timestamp and adds the requested duration to set the expiration. The assumed-role ARN is built by replacing :role/ with :assumed-role/ and appending the session name, matching AWS's format. Static placeholder values keep the output deterministic for snapshots, while the role ARN and session name remain configurable.
Common mistakes
- Using naive datetime without timezone, causing local timezone drift in `Expiration`.
- Forgetting to replace `:role/` with `:assumed-role/` when constructing the assumed-role ARN.
- Hardcoding a fixed expiration instead of computing it from the current time plus duration.
- Not including `SessionToken`, which many downstream AWS SDK calls require.
Variations
- Use `botocore.stub.Stubber` to stub a real `assume_role` response via boto3.
- Move credentials into a `typing.TypedDict` for static type checking.
Real-world use cases
- Unit-testing code that calls AWS services by injecting mocked credentials without hitting the STS API.
- Golden-file testing of outputs that serialize credential dicts, ensuring consistent expiry strings.
- Local development scripts that bootstrap credentials before running cloud SDK callbacks.
Sponsored
More from Cloud + Python
- Build a URL Shortener Client with Python medium
- Create a Cloud Storage Helper Class in Python easy
- Create a Data Helper Class for Beginners in Python easy
- Cross Account Role Chaining Mock Credentials in Python medium
- Exponential Backoff with Jitter for Cloud API Calls in Python medium
- Generate Mock CloudFormation Stack Events in Python easy
Keep learning
Related tutorials and quizzes for this topic.