GetCurrentAWSUserIAMPolicies

nicolaw 7th June 2019 at 11:57am
AWS awscli CodeSnippets
#!/usr/bin/env bash

set -Eeuo pipefail

trap 'declare rc=$?; >&2 echo "Unexpected error executing $BASH_COMMAND at ${BASH_SOURCE[0]} line $LINENO"; exit $rc' ERR

# TODO: If we're using a role, discover the role and find out those policies too.
#       - list-attached-role-policies
#       - list-role-policies

# TODO: How can we get the policy details that include what actions can be
#       performed on what resources?

# FIXME: Is there a better way to get all this information? This is pedestrian.

main () {
  declare user_name="${1:-}" group_name="" policy_name="" policy_arn=""
  if [[ -z "$user_name" ]] ; then
    user_name="$(aws sts get-caller-identity | jq -r .Arn | cut -d/ -f2)"
  fi

  # Groups the user is a member of
  while read -r group_name
  do
    # Policies attached to the group
    while read -r policy_arn
    do
      aws iam get-policy --policy-arn "$policy_arn"
    done < <(aws iam list-attached-group-policies --group-name "$group_name" | jq -r '.AttachedPolicies[]|.PolicyArn')

    # Inline policies directly on the group
    while read -r policy_name
    do
      aws iam get-group-policy --group-name "$group_name" --policy-name "$policy_name"
    done < <(aws iam list-group-policies --group-name "$group_name" | jq -r '.PolicyNames[]|.')
  done < <(aws iam list-groups-for-user --user-name "$user_name" | jq -r '.Groups[]|.GroupName')

  # Policies attached to the user
  while read -r policy_arn
  do
    aws iam get-policy --policy-arn "$policy_arn"
  done < <(aws iam list-attached-user-policies --user-name "$user_name" | jq -r '.AttachedPolicies[]|.PolicyArn')

  # Inline policies directly on the user
  while read -r policy_name
  do
    aws iam get-user-policy --user-name "$user_name" --policy-name "$policy_name"
  done < <(aws iam list-user-policies --user-name "$user_name"  | jq -r '.PolicyNames[]|.')
}

main "$@"