Tom Bradshaw
Tom Bradshaw

Reputation: 25

Finding IAM SA Keys Older than 89 Days in Google Cloud

I'm trying to write a script that will hunt out all IAM service keys that have existed longer than 89 days to meet our security requirements, but I'm typing myself into knots.

My best attempt so far:

gcloud iam service-accounts keys list --quiet --managed-by=user --iam-account $SERVICE_ACCOUNT_EMAIL --filter='createTime<=P89D' --format='csv[no-heading](KEY_ID)'

But this appears to catch all of the keys. I'm struggling to get my head around Google's filter configurations. Any pointers gladly accepted.

Upvotes: 0

Views: 665

Answers (2)

Tom Bradshaw
Tom Bradshaw

Reputation: 25

I've ended up using the above method with ISO dates generated in a script and it seems to be working now. It feels like the kind of thing that should be nicely handled with the filters, but getting it working is taking more time than a bash date

Upvotes: 0

DazWilkin
DazWilkin

Reputation: 40416

The underlying REST method is projects.serviceAccounts.keys.list and the result is a ServiceAccountKey which contains valid[Before|After]Time which are strings in the protobuf Timestamp.

So, I think this needs to either be a string comparison of dates (!) or comparing durations (but I'm unfamiliar with the duration format and how to compare).

You can convert the validAfterTime to a duration, i.e. --filter=validAfterTime.duration() (see duration) and then compare (!) but as Durations

Or construct a date that's within your scope and compare as-is. The following is hacky, please proceed with caution:

PROJECT=...
ACCOUNT=...

PAST=$(date -d "-90 days" +%Y-%m-%dT%H:%M:%SZ)

EMAIL="${ACCOUNT}@${PROJECT}.iam.gserviceaccount.com"

gcloud iam service-accounts keys list \
--iam-account=${EMAIL} \
--project=${PROJECT} \
--filter="validAfterTime<${PAST}"

I think there's a better way to do this!

Upvotes: 3

Related Questions