5

I need to fire off an alert to the security team if a users AWS access keys exceed 90 days old. I am doing this in bash.

So far my script is outputting the keys and the dates like this:

AKIAJS7KPHZCQRQ5FJWA : 2016-08-31T15:38:18Z
AKIAICDOHVTMEAB6RM5Q : 2018-02-08T03:55:51Z

How do I handle determining if the date is past 90 days old using that date format in bash?

I am using Ubuntu 18.04. I believe that the date format is ISO 8601. Please confirm/correct if that is wrong as well.

0

2 Answers 2

14

You can use GNU date to convert a date-time string into a number of seconds (since "the epoch", 1st January 1970). From there it's a simple arithmetic comparison

datetime='2016-08-31T15:38:18Z'
timeago='90 days ago'

dtSec=$(date --date "$datetime" +'%s')    # For "now", use $(date +'%s')
taSec=$(date --date "$timeago" +'%s')

echo "INFO: dtSec=$dtSec, taSec=$taSec" >&2

[ $dtSec -lt $taSec ] && echo too old
0
2

The below script will read the format you presented above, but if you already have the values in existing variables, you could consolidate the code:

#!/bin/bash
cutoff=$(date -d '90 days ago' +%s)
while read -r key colon date
do
  age=$(date -d "$date" +%s)
  if (($age < $cutoff))
  then
    printf "Warning! key %s is older than 90 days\n" "$key" >&2
  fi
done < input

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.