Skip to content

Instantly share code, notes, and snippets.

@htnosm
Last active May 1, 2021
Embed
What would you like to do?
Generate bookmarks HTML based on ~/.aws/config

generate-aws-switch-role-bookmark

Overview

Requirements

  • Python 3.6+

~/.aws/config sample

# color = {red(default), orange, yellow, green, blue}
[profile A]
role_arn = arn:aws:iam::123456789012:role/switch-to-assume-role
source_profile = bastion
color = red

[profile B]
role_arn = arn:aws:iam::987654321098:role/switch-to-assume-role
source_profile = bastion
color = blue

Usage

  • (1) Output HTML
python generate-aws-switch-role-bookmark.py > bookmark.html
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import configparser
from operator import itemgetter
HOME = os.environ['HOME']
bin_dir = os.path.dirname(os.path.abspath(__file__))
header = '''
<!DOCTYPE NETSCAPE-Bookmark-file-1>
<!-- This is an automatically generated file.
It will be read and overwritten.
DO NOT EDIT! -->
<META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=UTF-8">
<TITLE>Bookmarks</TITLE>
<H1>Bookmarks</H1>
<DL><p>
'''
footer = '''
</DL><p>
'''
colors = {
'red': 'F2B0A9',
'orange': 'FBBF93',
'yellow': 'FAD791',
'green': 'B7CA9D',
'blue': '99BCE3',
}
def main():
ini = configparser.ConfigParser()
ini.read(f'{HOME}/.aws/config', 'UTF-8')
links = []
for section in ini.sections():
if section.startswith('profile '):
profile = section.split(' ')[1]
if 'source_profile' in ini.options(section):
role_arn = ini[section]['role_arn']
role_arn_parts = role_arn.split(':')
account_id = role_arn_parts[4]
role_name = role_arn_parts[5].replace('role/', '')
color = colors['red']
if 'color' in ini.options(section):
color = colors[ini[section]['color']]
link = f'{" " * 12}<DT><A HREF=\"https://signin.aws.amazon.com/switchrole?account={account_id}&roleName={role_name}&displayName={profile}_{role_name}&color={color}\">{profile}</A>'
link_dict = {
'role': role_name,
'link': link,
}
links.append(link_dict)
links.sort(key=itemgetter('role'))
prev = ""
htmls = [header]
for item in links:
if prev != item['role']:
if len(prev) > 0:
htmls.append(f'{" " * 4}</DL><p>')
htmls.append(f'''
<DT><H3>{item["role"]}</H3>
<DL><p>
''')
prev = item['role']
htmls.append(item['link'])
htmls.append(f'{" " * 4}</DL><p>')
htmls.append(footer)
print('\n'.join(htmls))
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment