Skip to content

Instantly share code, notes, and snippets.

@gecko655
Last active October 30, 2025 11:52
Show Gist options
  • Save gecko655/fc54aabc0a17fedcf21021d12a39d18f to your computer and use it in GitHub Desktop.
Save gecko655/fc54aabc0a17fedcf21021d12a39d18f to your computer and use it in GitHub Desktop.
aws sso 用 ~/.aws/config を作るやつ
#!/usr/bin/env bash
set -euo pipefail
### Usage:
### aws sso login
### SSO_SESSION=[session_name] REGION=[region] ./generate_aws_sso_config.bash
SSO_SESSION="${SSO_SESSION:-my-sso-session}"
REGION="${REGION:-ap-northeast-1}"
TOKEN="${TOKEN:-$(jq -r '.accessToken//empty' ~/.aws/sso/cache/*.json 2>/dev/null | head -1)}"
[ -z "${TOKEN:-}" ] && { echo "ERROR: TOKEN が取得できません。先に aws sso login を実行してください。" >&2; exit 1; }
# () を削除して小文字化
sanitize_name() {
echo "$1" | tr '[:upper:]' '[:lower:]' | sed -E 's/[^a-z0-9_-]+/_/g'
}
N=
while :; do
R="$(aws sso list-accounts --access-token "$TOKEN" ${N:+--next-token "$N"})"
printf '%s' "$R" | jq -r '.accountList[] | [.accountId, .accountName] | @tsv' | while IFS=$'\t' read -r ACC_ID ACC_NAME; do
BASE="$(sanitize_name "$ACC_NAME")"
n=
while :; do
resp="$(aws sso list-account-roles --account-id "$ACC_ID" --access-token "$TOKEN" ${n:+--next-token "$n"})"
printf '%s' "$resp" | jq -r --arg base "$BASE" --arg id "$ACC_ID" --arg s "$SSO_SESSION" --arg r "$REGION" '
.roleList[].roleName as $role
| ($role | ascii_downcase) as $rl
| "[profile \($base)-\($rl)]\nsso_session = \($s)\nsso_account_id = \($id)\nsso_role_name = \($role)\noutput = json\nregion = \($r)\n"'
n="$(printf '%s' "$resp" | jq -r '.nextToken // empty')"
[ -z "$n" ] && break
done
done
N="$(printf '%s' "$R" | jq -r '.nextToken // empty')"
[ -z "$N" ] && break
done
@gecko655
Copy link
Author

gecko655 commented Oct 30, 2025

[profile {account_name}-{role_name}]
sso_session = {SSO_SESSION}
sso_account_id = {account_id}
sso_role_name = {role_name}
output = json
region = {REGION}

みたいなのを吐いてくれる。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment