Skip to content

Instantly share code, notes, and snippets.

@atheiman
Last active August 5, 2024 17:41
Show Gist options
  • Save atheiman/5ed559dbaacfd6199b3cb546fa218855 to your computer and use it in GitHub Desktop.
Save atheiman/5ed559dbaacfd6199b3cb546fa218855 to your computer and use it in GitHub Desktop.
AWS organization switch role (assume role) bookmark generator - outputs html to stdout that can be saved to a .html file and imported into browser bookmarks.
import boto3
import os
# Example usage from a bash shell:
# PREFIX='AWS COMM' AWS_PROFILE=comm-mgmt ROLE_NAME=AWSControlTowerExecution python ./aws_switch_role_bookmark_generator.py > ./aws-switch-role-bookmarks.html
# Environment variables for configuration
role_name = os.environ.get("ROLE_NAME", "OrganizationAccountAccessRole")
include_mgmt = os.environ.get("INCLUDE_MGMT", "true").lower() == "true"
prefix = os.environ.get("PREFIX", "AWS")
sts = boto3.client("sts")
caller_arn = sts.get_caller_identity()["Arn"]
partition = caller_arn.split(":")[1]
if partition == "aws-us-gov":
domain = "signin.amazonaws-us-gov.com"
else:
domain = "signin.aws.amazon.com"
url_template = "https://" + domain + "/switchrole?roleName={role_name}&account={acct_id}&displayName={display_name}"
orgs = boto3.client("organizations")
mgmt_acct_id = orgs.describe_organization()["Organization"]["MasterAccountId"]
print(
"""<!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>"""
)
for pg in orgs.get_paginator("list_accounts").paginate():
for a in pg["Accounts"]:
if not include_mgmt and a["Id"] == mgmt_acct_id:
continue
url = url_template.format(role_name=role_name, acct_id=a["Id"], display_name=a["Name"])
print(f"<DT><A HREF=\"{url}\">{prefix} - {a['Name']} - {role_name}</A>")
print("</DL><p>")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment