Scan AWS Account for IAM Role
If you are like me you happen to work with ALZs with LOTS of accounts. Jumping into each one to verify a role exists, or doesn’t it quite tedious. So here I have a simple “one-liner” that loops through your accounts and looks for the existence of a role (by partial lookup).
One-liner
for role in $(cat ~/.aws/credentials | grep devopsadmin | cut -d '[' -f2 | cut -d ']' -f1 | grep -v ^role_arn); do echo $role; aws --profile $role iam list-roles | jq -r ".Roles[].RoleName" | grep CMK; done
Breakdown
First we tell bash to list grab our AWS Credentials file, which is an INI that we store the profile names in as
[ProfileName]
, in my case I only care for the names containing devopsadmin
. The cut is to trim the [
& ]
off
the line, and finally the grep -v
skips any lines that start with role_arn
as these aren’t needed (this time).
for role in $(cat ~/.aws/credentials | grep devopsadmin | cut -d '[' -f2 | cut -d ']' -f1 | grep -v ^role_arn); do
Next, I echo out the role being used, because it makes it easy to know if an account matches:
echo $role;
Now we call the AWS IAM service asking to list-roles
aws --profile $role iam list-roles
This returns some JSON in the format:
{
"Roles": [
{
"Path": "/",
"RoleName": "fake-role-name-CMK",
"RoleId": "AROAYNOUTAHCON",
"Arn": "arn:aws:iam::123456789012:role/fake-role-name-CMK",
"CreateDate": "2019-12-20T01:09:38Z",
"AssumeRolePolicyDocument": {
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": {
"Federated": "arn:aws:iam::123456789012:saml-provider/utahcon-idp"
},
"Action": "sts:AssumeRoleWithSAML",
"Condition": {
"StringEquals": {
"SAML:aud": "https://signin.aws.amazon.com/saml"
}
}
}
]
},
"Description": "",
"MaxSessionDuration": 3600
}
...
]
}
Now sure I could simply grep this return JSON for the answer, but that isn’t really clean or fun, so instead we will
employ the use of jq
to make sure we are only evaluating the RoleName
of each role:
jq -r ".Roles[].RoleName"
Finally I grep
for the search term (CMK
in my case) in the role name:
grep CMK
Happy Hunting!
I hope this helps someone, maybe even myself again one day.