Skip to content

Instantly share code, notes, and snippets.

@nightspotlight
Created October 31, 2025 18:35
Show Gist options
  • Select an option

  • Save nightspotlight/20326ee13f73ecd8814c2f9ad291f33d to your computer and use it in GitHub Desktop.

Select an option

Save nightspotlight/20326ee13f73ecd8814c2f9ad291f33d to your computer and use it in GitHub Desktop.
A shell function to use `aws ssm start-session` with temporary static IAM user credentials
#!/usr/bin/env bash
function ssm-start-session() (
local target="${1?Usage: ssm-start-session <instance-id>}"
local timestamp username policy_arn access_key_json
timestamp=$(date +%s)
username="ssm-session-temp-$timestamp"
policy_arn='arn:aws:iam::aws:policy/AdministratorAccess'
declare -x \
AWS_PAGER="" \
AWS_DEFAULT_OUTPUT="text" \
AWS_REGION="${AWS_REGION:-us-east-2}" \
AWS_ACCESS_KEY_ID \
AWS_SECRET_ACCESS_KEY
# shellcheck disable=SC2329
function cleanup() {
# Delete the temporary user and access key
aws iam delete-access-key \
--user-name "${username}" \
--access-key-id "${AWS_ACCESS_KEY_ID}"
aws iam detach-user-policy \
--user-name "${username}" \
--policy-arn "${policy_arn}"
aws iam delete-user \
--user-name "${username}" && \
echo "Deleted user ${username}"
}
trap cleanup EXIT
# Create a temporary user and an access key
user_arn="$(aws iam create-user \
--user-name "${username}" \
--tags 'Key=SSMSessionRunAs,Value=centos' \
'Key=terraform,Value=false' \
--query 'User.Arn')"
echo "Created user ${user_arn}"
aws iam attach-user-policy \
--user-name "${username}" \
--policy-arn "${policy_arn}"
access_key_json="$(aws iam create-access-key --user-name "${username}" --output json)"
AWS_ACCESS_KEY_ID="$(jq -erc '.AccessKey.AccessKeyId' <<< "${access_key_json}")"
AWS_SECRET_ACCESS_KEY="$(jq -erc '.AccessKey.SecretAccessKey' <<< "${access_key_json}")"
# Eventual consistency wait
until aws sts get-caller-identity >/dev/null 2>&1; do
echo "Waiting for IAM user propagation…"
sleep 2
done
# Start SSM session
aws ssm start-session --target "${target}"
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment