Skip to content

Instantly share code, notes, and snippets.

@gffhcks
Last active April 18, 2019 16:23
Show Gist options
  • Save gffhcks/44f575b5de3662ae316d7d8ea58c3f3e to your computer and use it in GitHub Desktop.
Save gffhcks/44f575b5de3662ae316d7d8ea58c3f3e to your computer and use it in GitHub Desktop.
Get account ID from AWS profile (via role or MFA serial ARN)
#!/usr/bin/env python3
import argparse
import configparser
import os
import sys
CONFIG_PATH = os.path.expanduser("~/.aws/config")
CREDENTIALS_PATH = os.path.expanduser("~/.aws/credentials")
# Parse profile_name argument
parser = argparse.ArgumentParser(description="Open an AssumeRole page.")
parser.add_argument("profile_name", type=str, help="AWS profile name (in ~/.aws)")
args = parser.parse_args()
full_config = configparser.ConfigParser()
# Read and normalize config
config = configparser.ConfigParser()
config.read(CONFIG_PATH)
for profile in config:
# '.aws/config' has 'profile ' in front of each profile name
full_config[profile.replace("profile ", "")] = config[profile]
# Read credentials
full_config.read(CREDENTIALS_PATH)
# Determine account ID by role_arn or mfa_serial config option
# You can also use "account_id" to set the value explicitly
account_id = full_config.get(args.profile_name, "account_id", fallback="")
arn = full_config.get(args.profile_name, "role_arn", fallback="")
if full_config.get(args.profile_name, "aws_access_key_id", fallback=None):
arn = full_config.get(args.profile_name, "mfa_serial", fallback="")
try:
account_id = account_id or arn.split(":")[4]
print(account_id)
except IndexError:
print(f"ERR: Could not determine account ID from ~/.aws", file=sys.stderr)
sys.exit(1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment