Home > Back-end >  gcloud filter result based on time
gcloud filter result based on time

Time:12-27

I am trying to list machine Images on GCP and filter out results based on CreatimeTimestamp - a few hours/days. I'm trying to do something like this :

gcloud beta compute machine-images list --sort-by "creationTimestamp" --project=XXXXX --format="table(name,creationTimestamp.date('%Y-%m-%d-%T'))" --filter="CREATION_TIMESTAMP.date('%Y-%m-$d-%H:%M:%S')<'$(date -d '3 hours ago' " %Y-%m-%d-%H:%M:%S")'"

To list 3 hours old machine-images

CodePudding user response:

Update

Thinking more about your question, I think there's probably an easier way than my answer (below). The documentation suggests that you can do a date compare directly. So, perhaps:

WHEN=$(date  %s --date='3 hours ago')
gcloud beta compute machine-images list \
--project=${PROJECT} \
--format="table(name,creationTimestamp)") \
--filter="creationTimestamp.date(\" %s\")>${WHEN}"

gcloud filter doesn't include a shell and so you can't include e.g. bash's date command in the filter.

I think (!) the way to do this is to format output the results you want and then filter.

IMAGES=$(gcloud beta compute machine-images list \
--project=${PROJECT} \
--format="csv[no-heading](name,creationTimestamp.date())")

for IMAGE in ${IMAGES}
do
  IFS=, read NAME TIMESTAMP <<< ${IMAGE}
  CREATED=$(date  %s --date=${TIMESTAMP}
  WHEN=$(date  %s --date='3 hours ago')
  if [ ${CREATED} -gt ${WHEN} ]
  then
    printf "Image: %s (Creation: %s)\n" NAME TIMESTAMP
  fi
done
  • Related