Skip to content

Instantly share code, notes, and snippets.

@amatthies
Last active September 25, 2018 02:26
Show Gist options
  • Save amatthies/7e78dbb89a49169e3e6f3350e541d1e3 to your computer and use it in GitHub Desktop.
Save amatthies/7e78dbb89a49169e3e6f3350e541d1e3 to your computer and use it in GitHub Desktop.
Handling multiple aws profiles and roles on my local machine

Handling multiple aws profiles and roles on my local machine

I have pretty some aws profiles. And each of those profiles can assume pretty some IAM roles. I write code for instance roles: I trip, when I see aws_access_key_id = in code. ("No! No! No!")

When I started writing aws stuff, I added profile= arguments to all my boto3 constructors... until the roles started to be crucial. In fact, on several AWS accounts I can be several users, who can assume several roles.

Long story short: meanwhile, I handle all profile and (most of the) region stuff locally before coding, not in the code. For an EC2 instance, the needed credentials are "just there" – I want the same on my local machine.

My ~/.aws folder contains two files, credentials and config:

(floto-dev)anne@Annes-MacBook-Pro:~/.aws $ ls -a
.           ..          config      credentials

In credentials, I have defined several profiles:

[default]
aws_access_key_id = AKIAJAJAJAJAJAJAJAJA
aws_secret_access_key = secretSECRETsecretsupersecret/secretKEY!

[blueprint]
aws_access_key_id = AKIAJOJOJOJOJOJOJAJA
aws_secret_access_key = SECRETsecretsecretsupersecret/secretKEY.

[realwork]
aws_access_key_id = AKIAJUHUJUHUJOJOJAJA
aws_secret_access_key = Pfffffff+mmmmmh/alsoverrrrrrrrrrysecret.

In config, I have defined several roles.

[profile super-admin]
role_arn=arn:aws:iam::123456789012:role/super-admin
source_profile=realwork

[profile blueprint-admin]
role_arn=arn:aws:iam::987654321098:role/super-admin
source_profile=blueprint

[profile realwork-readonly]
role_arn=arn:aws:iam::123456789012:role/data-fisher
source_profile=realwork

(Note: if you don't need roles, you don't need config for the profile stuff, credentials is enough.)

Before I start working on something, I just set two environment variables:

export AWS_DEFAULT_REGION="eu-west-1"
export AWS_PROFILE="super-admin"

resp. (in my python startup scripts, e.g. ~/.ipython/profile_floto/startup/00-logging.py)

import os
os.environ['AWS_PROFILE'] = 'super-admin'
os.environ['AWS_DEFAULT_REGION'] = 'eu-west-1'

And then things just work. boto3 just assumes the role, even cross-account, very cool.

I admit that I'm overusing the super-admin role for all my profiles, but that's another topic...

http://boto3.readthedocs.org/en/latest/guide/configuration.html#assume-role-provider

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