Search code examples
google-cloud-platformgcloudgoogle-iam

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.


Solution

  • 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!