Engineer83
Engineer83

Reputation: 129

Trying to run a gcloud command that would list VM instances and show how many days old they are since their creation date

I'm trying to run a gcloud command that would list VM instances and show how many days old they are since creation date.

So far I only have the below command but I don't know if there is a way to put them in some order of how many days old they are from creation date. I've been trying to add some sort of filter but haven't managed to work it out.

If there is any advice it would be much appreciated.

gcloud projects list --format="table[box,title='My Project List'(createTime:sort=1,name,projectNumber,projectId:label=ProjectID,parent.id:label=Parent)"

Upvotes: 0

Views: 1157

Answers (1)

DazWilkin
DazWilkin

Reputation: 40416

Cloud SDK (gcloud) includes projections for date() and duration() but these would benefit from clearer documentation. I want, for example, to think that unit=1 returns the result as seconds (which would be easier) for what follows, but it does not (and I can't work out what it actually does, anyone?)

unit=1 -- I wonder whether this just unifies Timestamps to second precision? Since a Timestamp could have nanosecond precision, perhaps `date(.. unit=1, ...) just always rounds to seconds?

Even though gcloud (and many other CLIs) attempt to provide this smorgasbord of functionality, it's often better to follow the UNIX crede and assemble a solution from parts.

createTime are Timestamps; one of Google's Well-Known Protobuf Types

Purely bash:

# createtime Timestamps for all my projects
TIMESTAMPS=$(\
  gcloud projects list \
  --format="value(createTime.date())")

# In seconds
NOW=$(date +%s)

for TIMESTAMP in ${TIMESTAMPS}
do
  # Parse the Google Timestamp and return seconds
  CREATED=$(date +%s --date=${TIMESTAMP})
  # Difference in seconds since ${NOW}
  DIFF=$((${NOW}-${CREATED}))
  # Seconds-->Days
  DAYS=$((${DIFF}/3600/24))
  echo ${DAYS}
done

duration() may be useful but I'm unfamiliar with these ISO 8601 Durations

gcloud projects list \
--format="value(createTime.duration())"

A more complete example:

# Multiple values are easier to parse as CSV
VALUES=$(\
  gcloud projects list \
  --format="csv[no-heading](projectId,createTime.date())")

# In seconds
NOW=$(date +%s)

for VALUE in ${VALUES}
do
  # Extract PROJECT_ID and TIMESTAMP from VALUE
  IFS=, read PROJECT_ID TIMESTAMP <<< ${VALUE}
  # Parse the Google Timestamp and return seconds
  CREATED=$(date +%s --date=${TIMESTAMP})
  # Difference in seconds since ${NOW}
  DIFF=$((${NOW}-${CREATED}))
  # Seconds-->Days
  DAYS=$((${DIFF}/3600/24))
  printf "%s\t%s\n" "${DAYS}" "${PROJECT_ID}"
done

Upvotes: 2

Related Questions