From 311567fa1a73c5066f69e703acfcf2585e980967 Mon Sep 17 00:00:00 2001
From: Adar Nimrod <nimrod@shore.co.il>
Date: Thu, 18 Nov 2021 12:15:08 +0200
Subject: [PATCH] AWS assume-role script.

To run commands with a different IAM user/ role. No other configuration
needed (unlike aws-vault, not to pick on them, it's actually quite
nice). Also, an AWS CLI alias.
---
 .aws/cli/alias            |  1 +
 Documents/bin/assume-role | 39 +++++++++++++++++++++++++++++++++++++++
 2 files changed, 40 insertions(+)
 create mode 100755 Documents/bin/assume-role

diff --git a/.aws/cli/alias b/.aws/cli/alias
index bd45f84..4c3ac58 100644
--- a/.aws/cli/alias
+++ b/.aws/cli/alias
@@ -11,3 +11,4 @@ metadata-region = !python3 << EOF
     EOF
 du = s3 ls --recursive --human-readable --summarize
 enable_ena = ec2 modify-instance-attribute --ena-support --instance-id
+assume-role = !assume-role
diff --git a/Documents/bin/assume-role b/Documents/bin/assume-role
new file mode 100755
index 0000000..a837719
--- /dev/null
+++ b/Documents/bin/assume-role
@@ -0,0 +1,39 @@
+#!/bin/sh
+set -eu
+
+# This script runs the AWS assume-role command, captures the output, sets the
+# environment variables (AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY and
+# AWS_SESSION_TOKEN) and executes the command given.
+
+usage() {
+    echo "$(basename "$0"): [-h|--help] ROLE_ARN COMMAND [PARAMETER [PARAMETER ...]]"
+}
+
+command -v aws > /dev/null || { echo 'Cannot find the AWS CLI, exiting.' >&2; exit 1; }
+
+if [ "$#" -lt 2 ]
+then
+    usage
+    exit 1
+fi
+
+role_arn="$1"
+shift
+
+credentials="$(aws sts assume-role \
+    --output text \
+    --duration-seconds 3600 \
+    --role-arn "$role_arn" \
+    --role-session-name 'CircleCI_executor')"
+
+AWS_ACCESS_KEY_ID="$(echo "$credentials" | awk 'NR == 2 {print $2}')"
+AWS_SECRET_ACCESS_KEY="$(echo "$credentials" | awk 'NR == 2 {print $4}')"
+AWS_SESSION_TOKEN="$(echo "$credentials" | awk 'NR == 2 {print $5}')"
+
+export AWS_ACCESS_KEY_ID
+export AWS_SECRET_ACCESS_KEY
+export AWS_SESSION_TOKEN
+
+unset AWS_SECURITY_TOKEN
+
+eval exec "$@"
-- 
GitLab