Skip to content

Instantly share code, notes, and snippets.

@limed
Last active June 4, 2022 22:31
Show Gist options
  • Save limed/00c299a751c203ba5197051c24297564 to your computer and use it in GitHub Desktop.
Save limed/00c299a751c203ba5197051c24297564 to your computer and use it in GitHub Desktop.
Federate into aws console when you have aws keys exported
#!/usr/bin/env python3
import json
import sys
import requests
import click
from webbrowser import open_new_tab
from urllib.parse import quote_plus
from os import getenv, environ
# session timeout in seconds: 43200 == 12 hours
session_timeout = 43200
def is_china():
if 'AWS_ROLE_ARN' not in environ:
raise Exception(f"AWS_ROLE_ARN environment variable is not set")
aws_role = getenv('AWS_ROLE_ARN')
split_arn = aws_role.split(':', 5)[1:][0]
if split_arn == 'aws-cn':
return True
else:
return False
@click.command()
@click.option(
"-d",
"--debug",
is_flag=True,
default=False,
help="Print more debug info"
)
@click.option(
"-o",
"--output",
default=True,
help="Print federate URL"
)
@click.option(
"-b",
"--browser",
is_flag=True,
default=False,
help="Open browser window")
def federate(debug, output, browser):
url_credentials = {
'sessionId': getenv('AWS_ACCESS_KEY_ID'),
'sessionKey': getenv('AWS_SECRET_ACCESS_KEY'),
'sessionToken': getenv('AWS_SESSION_TOKEN'),
}
if None in url_credentials.values():
raise Exception(f"No valid credentials: {url_credentials}")
if is_china():
endpoint = {
'console': "https://console.amazonaws.cn",
'federation': "https://signin.amazonaws.cn/federation"
}
else:
endpoint = {
'console': "https://console.aws.amazon.com/",
'federation': "https://signin.aws.amazon.com/federation"
}
json_string_with_temp_credentials = json.dumps(url_credentials)
request_parameters = "?Action=getSigninToken"
request_parameters += f"&SessionDuration={session_timeout}"
request_parameters += f"&Session={quote_plus(json_string_with_temp_credentials)}"
request_url = f"{endpoint['federation']}{request_parameters}"
if debug:
print(f"[DEBUG] Endpoints: {endpoint}")
print(f"[DEBUG] Request URL: {request_url}")
print(f"[DEBUG] Requesting STS Token")
r = requests.get(request_url)
if debug:
print(f"[DEBUG]: Federation response {r.text}")
# Returns a JSON document with a single element named SigninToken.
signin_token = json.loads(r.text)
# Step 5: Create URL where users can use the sign-in token to sign in to
# the console. This URL must be used within 15 minutes after the
# sign-in token was issued.
request_parameters = "?Action=login"
request_parameters += "&Issuer=maws-federate"
request_parameters += f"&Destination={quote_plus(endpoint['console'])}"
request_parameters += f"&SigninToken={signin_token['SigninToken']}"
request_url = f"{endpoint['federation']}{request_parameters}"
if browser:
# Open browser tab
print("Opening new tab")
open_new_tab(request_url)
output = False
if output:
# Send final URL to stdout
print(request_url)
if __name__ == "__main__":
federate()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment