Skip to content

Instantly share code, notes, and snippets.

@toshke
Created December 24, 2021 08:22
Show Gist options
  • Select an option

  • Save toshke/f8a316928def93327a3e77d97320f1ed to your computer and use it in GitHub Desktop.

Select an option

Save toshke/f8a316928def93327a3e77d97320f1ed to your computer and use it in GitHub Desktop.

Revisions

  1. toshke created this gist Dec 24, 2021.
    49 changes: 49 additions & 0 deletions list_active_aws.py
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,49 @@
    #!/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()