Created
December 24, 2021 08:22
-
-
Save toshke/f8a316928def93327a3e77d97320f1ed to your computer and use it in GitHub Desktop.
list active aws profiles
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 | |
import boto3 | |
import os | |
from botocore.exceptions import ClientError | |
KEY_ID = 'aws_access_key_id' | |
SECRET_KEY = 'aws_secret_access_key' | |
SESSION_TOKEN = 'aws_session_token' | |
def main(): | |
fname = os.environ['HOME'] + '/.aws/credentials' | |
with open(fname, 'r') as f: | |
content = f.read() | |
profile = None | |
data = {} | |
for line in content.split(): | |
if line.strip().startswith('['): | |
profile = line.strip().replace('[','').replace(']','') | |
print(f'Reading profile: {profile}') | |
data[profile] = {} | |
elif '=' in line: | |
parts = line.split('=') | |
key = parts[0] | |
value = parts[1] | |
data[profile][key] = value | |
for profile in data: | |
print(f'Checking profile {profile}.... ') | |
if KEY_ID in data[profile] and SECRET_KEY in data[profile]: | |
kwargs = { KEY_ID: data[profile][KEY_ID], SECRET_KEY: data[profile][SECRET_KEY] } | |
if SESSION_TOKEN in data[profile]: | |
kwargs[SESSION_TOKEN] = data[profile][SESSION_TOKEN] | |
client = boto3.client('sts', **kwargs) | |
try: | |
arn = client.get_caller_identity()['Arn'] | |
print(f'.. accessible: {arn}') | |
data[profile]['accessible'] = True | |
except ClientError as e: | |
data[profile]['accessible'] = False | |
print('.. failed ') | |
accessible_profiles = [profile for profile in data if data[profile]['accessible']] | |
print(f'Accessible profiles:') | |
print('\n'.join(accessible_profiles)) | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment