Last active
October 22, 2022 11:09
-
-
Save mvanholsteijn/d671ad7dd387d3d721d9475156167eaf to your computer and use it in GitHub Desktop.
lists all Google IAM roles which contain the specified permission sorted by the number of permissions
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
# | |
# NAME | |
# gcp-least-privileged - lists all Google IAM roles which contain the specified permission | |
# | |
# EXAMPLE | |
# gcp-least-privileged compute.disks.delete | |
# | |
main() { | |
local permission | |
[[ $# -ne 1 ]] && usage | |
permission=($(sed -e 's/\./ /g' <<< $1)) | |
[[ ${#permission[@]} -ne 3 ]] && usage "invalid permission" | |
list_roles_with_permission $1 | |
} | |
list_roles_with_permission() { | |
local service permission | |
permission=$1 | |
service=$(cut -d . -f 1 <<< $permission) | |
for role in $(list_all_roles $service); do | |
gcloud iam roles describe $role --format json | \ | |
jq --arg permission $permission \ | |
'select(.includedPermissions[] | . == $permission) | | |
{ | |
name: .name, | |
title: .title, | |
description: .description, | |
number_of_permissions : (.includedPermissions|length) | |
}' | |
done | \ | |
jq --slurp 'sort_by(.number_of_permissions)' | |
} | |
list_all_roles() { | |
gcloud iam roles list --filter "name ~ ^roles/$1.*" --format 'value(name)' | |
cat <<! | |
roles/viewer | |
roles/editor | |
roles/owner | |
! | |
} | |
usage() { | |
echo "Usage: gcp-least-privileged <service>.<resource>.<operation>" >&2 | |
[[ $# -gt 0 ]] && echo "$@" >&2 | |
exit 1 | |
} | |
main $@ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment