目的
AWS CLIで指定ユーザーにアタッチされているポリシーの一覧を取得する。
※AWS CLIではaws iam get-user --user-name xxxxx
やaws iam list-attached-group-policies --group-name yyyyy
でユーザー名やグループ名を指定して、許可ポリシーを確認することはできる。
しかし、一発でそのユーザーに許可されている全ポリシーを取得することはできない。(たぶん)
スクリプト
1.ヒアドキュメントでスクリプトを作成
get_user_policies.sh
cat << 'EOT' > get_user_policies.sh
#!/bin/bash
# 使用方法
# ./get_user_policies.sh ユーザー名
# ユーザー名を取得
user_name=$(aws iam get-user --user-name $1 --query 'User.UserName' --output text)
if [ $? -ne 0 ]; then
echo "ユーザー $1 は存在しません"
exit 1
fi
# ユーザーに直接アタッチされているポリシーを取得
user_policies=$(aws iam list-attached-user-policies --user-name ${user_name} --query 'AttachedPolicies[].PolicyArn' --output text)
# ユーザーに直接アタッチされているインラインポリシーを取得
user_inline_policies=$(aws iam list-user-policies --user-name ${user_name} --query 'PolicyNames' --output text)
# 結果を出力
echo "## ユーザー ${user_name} に直接アタッチされているポリシー"
if [ -z "${user_policies}" ]; then
echo "なし"
else
for policy in ${user_policies}; do
echo ${policy}
done
fi
echo ""
echo "## ユーザー ${user_name} に直接アタッチされているインラインポリシー"
if [ -z "${user_inline_policies}" ]; then
echo "なし"
else
for policy in ${user_inline_policies}; do
echo ${policy}
done
fi
# ユーザーが所属しているグループを取得
groups=$(aws iam list-groups-for-user --user-name ${user_name} --query 'Groups[].GroupName' --output text)
echo ""
echo "## ユーザー ${user_name} が所属しているグループにアタッチされているポリシー"
# グループにアタッチされているポリシーを取得
for group in ${groups}; do
group_policies=$(aws iam list-attached-group-policies --group-name ${group} --query 'AttachedPolicies[].PolicyArn' --output text)
echo "### グループ ${group}"
if [ -z "${group_policies}" ]; then
echo "なし"
else
for policy in ${group_policies}; do
echo ${policy}
done
fi
done
echo ""
echo "## ユーザー ${user_name} が所属しているグループにアタッチされているインラインポリシー"
# グループにアタッチされているポリシーを取得
for group in ${groups}; do
group_policies=$(aws iam list-group-policies --group-name ${group} --query 'PolicyNames' --output text)
echo "### グループ ${group}"
if [ -z "${group_policies}" ]; then
echo "なし"
else
for policy in ${group_policies}; do
echo ${policy}
done
fi
done
EOT
2. 実行権限付与
chmod +x get_user_policies.sh
使用方法
get_user_policies.sh <ユーザー名>
実行例
[cloudshell-user@ip-10-134-8-207 ~]$ ./get_user_policies.sh user20240406
## ユーザー user20240406 に直接アタッチされているポリシー
arn:aws:iam::aws:policy/AmazonEC2ReadOnlyAccess
arn:aws:iam::aws:policy/IAMUserChangePassword
## ユーザー user20240406 に直接アタッチされているインラインポリシー
なし
## ユーザー user20240406 が所属しているグループにアタッチされているポリシー
### グループ greup-test02
arn:aws:iam::aws:policy/IAMReadOnlyAccess
### グループ group-test01
arn:aws:iam::aws:policy/AWSCloudFormationReadOnlyAccess
arn:aws:iam::aws:policy/AWSCloudShellFullAccess
## ユーザー user20240406 が所属しているグループにアタッチされているインラインポリシー
### グループ greup-test02
なし
### グループ group-test01
S3_ListAllMyBuckets
S3_ListBucket
※ポリシーは検証のために適当にアタッチしてある