Last active
September 13, 2022 16:45
-
-
Save tayopal/414c326992e9335eaf3aeb236003728a to your computer and use it in GitHub Desktop.
Print "export" statements for AWS_PROFILE for profiles in ~/.aws/config
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
### Parse AWS config | |
# Cluster roles by environment and alphabetize | |
# Print easily copy/pasta export statements for env selection | |
# Allow selection of internal or customer environments | |
### Example AWS config that works with this: | |
# [profile sso] | |
# region = us-west-2 | |
# # etc... | |
# [profile data_ams_test_infra] | |
# role_arn = arn:aws:iam::337314033594:role/staff/InfrastructureEngineer | |
# source_profile = sso | |
# # etc... | |
import os | |
import argparse | |
import sys | |
MIN_PYTHON = (3, 9) | |
if sys.version_info < MIN_PYTHON: | |
sys.exit("Minimum Python version is %s.%s" % MIN_PYTHON) | |
internal_environments = ("core_", "app_", "security_", "data_ams_test_", "sso") | |
def main(args): | |
config = open(os.path.expanduser('~/.aws/config')).readlines() | |
profiles = [] | |
for line in config: | |
if '[profile' in line: | |
profile_name = line.strip('[]\n').split()[1] | |
if args.internal and profile_name.startswith(internal_environments): | |
profiles.append(profile_name) | |
elif args.customers and not profile_name.startswith(internal_environments): | |
profiles.append(profile_name) | |
sso = [p for p in profiles if "_no_sso" not in p] | |
envs = {} | |
for p in sso: | |
role = p.split('_')[-1] | |
env = p.replace(f"_{role}", "") | |
if env not in envs: | |
envs[env] = [] | |
envs[env].append(p) | |
for env, profiles in sorted(envs.items()): | |
print(env.upper()) | |
for p in profiles: | |
print(f"\texport AWS_PROFILE={p}") | |
def init_argparse(): | |
parser = argparse.ArgumentParser( | |
usage="%(prog)s [OPTION]", | |
description="Print out roles to assume with export statements") | |
parser.add_argument( | |
"-i", "--internal", action=argparse.BooleanOptionalAction, | |
help="Display internal roles", | |
) | |
parser.add_argument( | |
"-c", "--customers", action=argparse.BooleanOptionalAction, | |
help="Display customer roles", | |
) | |
parser.set_defaults(internal=False, customers=False) | |
return parser | |
if __name__ == "__main__": | |
main(init_argparse().parse_args()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment