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.

Easy Python 3.9+ Aug 9, 2026 Cloud + Python 14 views 0 copies

Python code

28 lines
Python 3.9+
import 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

stdout
{
  "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

  1. Use `botocore.stub.Stubber` to stub a real `assume_role` response via boto3.
  2. 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

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Cloud + Python

Related tutorials and quizzes for this topic.