Skip to content

Instantly share code, notes, and snippets.

@mvanholsteijn
Last active October 22, 2022 11:09
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mvanholsteijn/d671ad7dd387d3d721d9475156167eaf to your computer and use it in GitHub Desktop.
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
#!/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