Creating short-lived, temporary roles for experimenting with AWS IAM policy documents

As part of some recent work, I was experimenting with IAM roles in AWS, and I came up with a way to create short-lived, temporary IAM roles that use a particular IAM policy document.

It goes something like this:

with temporary_iam_credentials(admin_role_arn, policy_document) as credentials:
    # do stuff with your credentials, which are precisely scoped to
    # the provided IAM policy document.

The function temporary_iam_credentials() gives you a set of temporary AWS credentials, which have the permissions defined by the IAM policy document. You can make API calls using those credentials, and check they behave correctly – that API calls are allowed or denied as appropriate.

When you’re done, it cleans up after itself, so there are no temporary resources left hanging around in your account.

I use it in two ways:

It was a useful experience working with Python’s context managers, with using ExitStack to handle nested context managers, and seeing how quickly IAM can react to changes.

You can find the code on GitHub, and I’ve also written a “what I learnt” section in the README.

The “what I learnt” is a new thing I’m trying. The number of people who have the exact same problem as me – and will try to use my code to solve it – is pretty small. The number of people who have similar problems – and who might benefit from my ideas if not the actual code – is probably larger. I’m trying to make my repos more useful for the latter group.