JMESPath with the AWS CLI - IAM example
Intro
I needed a way to list all IAM roles in an account that have a trust relationship with other AWS accounts - that is, any role that could be assumed by someone from another account.
One way is to just use list-roles
and do a search to see if certain AWS accounts were allowed or check for the "AWS"
key.
This way is similar, but it queries the response before printing it out so it sort of filters it and might make it a little easier to track which roles can or can’t be assumed from another account.
Either way is fine, but I find myself always looking for working jmespath examples, so here’s one.
Command
aws iam list-roles --query "Roles[].[RoleName, AssumeRolePolicyDocument.Statement[].Principal.AWS]"
Note that you might need to specify --profile PROFILE_NAME_HERE
.
Output
Example output if there are 2 roles total. In this example, rds-monitoring-role
doesn’t allow any AWS accounts/users/roles to assume it, but TestAssumeRole
does.
[
[
"rds-monitoring-role",
[]
],
[
"TestAssumeRole",
[
"arn:aws:iam::123456000000:user/tyler-example-assumer"
]
]
]
Fix it in post
Extra tip: The following regex will match empty blocks such as the rds-monitoring-role
in the example output above so you can remove them afterwards (for example, with a find and replace in VSCode):
^\s+\[\n^\s+".*",\n^\s+\[\]\n^\s+\],\n
# Matches
# [
# "rds-monitoring-role",
# []
# ],