Skip to content

Instantly share code, notes, and snippets.

@imranity
Last active November 21, 2023 07:36
Show Gist options
  • Save imranity/432af3b560605f5446a8ae24dfa66ece to your computer and use it in GitHub Desktop.
Save imranity/432af3b560605f5446a8ae24dfa66ece to your computer and use it in GitHub Desktop.
get IAM Role matching a name using jq and aws cli

Intro

To use aws cli, its common to invoke built-in features like --filters and --query however they aren't avaiable for all the commands.

for my use case i wanted to get a role matching a name, i.e. regex pattern . that was very easy using jq

one-liner to get Role ARN of a role macthing name

if i want to get a role matching name eksctl-dev-cluster-addon-iamserviceaccount then to get ARN of that role is simply doing

aws iam list-roles | jq -r '.Roles[] | select(.RoleName|match("eksctl-dev-cluster-addon-iamserviceaccount.")) | .Arn'

one-liner to get policy ARN of matching policy name

 aws iam list-policies | jq -r '.Policies[] | select(.PolicyName|match("kube-external-secrets")) | .Arn'
arn:aws:iam::<ID>:policy/kube-external-secrets

one-liner without jq(using built-in JMESPath https://jmespath.org/tutorial.html )

aws iam list-policies --query 'Policies[?PolicyName!=`null`]|[?starts_with(PolicyName,`kube-external-secrets`)==`true`][].[Arn]' --output text
arn:aws:iam::<ID>:policy/kube-external-secrets
@thiagokiyota
Copy link

Hi,
Now, as of aws provider version 3.55.0, we have a data source to get the functions.
"Use this data source to get the ARNs and names of IAM functions."
https://registry.terraform.io/providers/hashicorp/aws/3.55.0/docs/data-sources/iam_roles

@imlazy-xyz
Copy link

Thanks for the list-policies one liner.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment