Skip to content

Commit a9f76fd

Browse files
committed
Include account id in output
1 parent 7dcfc9c commit a9f76fd

File tree

1 file changed

+20
-3
lines changed

1 file changed

+20
-3
lines changed

bin/aws-profiles

Lines changed: 20 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,8 @@ import configparser
33
import os
44
import sys
55

6+
# script.py - List AWS profile names with account IDs extracted from role_arn in credentials file
7+
68
# Get patterns from command-line arguments
79
patterns = sys.argv[1:]
810

@@ -18,8 +20,23 @@ credentials_file = os.environ.get('AWS_SHARED_CREDENTIALS_FILE', os.path.expandu
1820
config = configparser.ConfigParser(interpolation=None)
1921
config.read(credentials_file)
2022

21-
# Iterate through the sections and print those that match the patterns
23+
# Helper function to extract account ID from role_arn
24+
def get_account_id_from_arn(arn):
25+
# Split the ARN and extract the account ID
26+
parts = arn.split(':')
27+
if len(parts) > 4 and parts[0].startswith('arn') and parts[2] == 'iam':
28+
return parts[4] # The account ID is the 5th element in the ARN
29+
return 'Unknown'
30+
31+
# Iterate through the sections and print those that match the patterns along with the account ID
2232
for section in config.sections():
2333
if not patterns or any(pattern in section for pattern in patterns):
24-
print(section)
25-
34+
try:
35+
# Attempt to fetch the role_arn from the credentials file
36+
role_arn = config.get(section, 'role_arn')
37+
account_id = get_account_id_from_arn(role_arn)
38+
except (configparser.NoSectionError, configparser.NoOptionError):
39+
# If the role_arn is not found, set account_id to 'Unknown'
40+
account_id = 'Unknown'
41+
42+
print(f"{section}\t{account_id}")

0 commit comments

Comments
 (0)