Pages - Menu

2022年8月17日 星期三

[GCP] shellScript取得GCE機器列表內的CPU個數

前言

要算一下各服務所佔的比例,
大方向用VM的機器 cpu來算

一個一個點進去VM機器裡面算CPU的數量是可行,

但我好懶!!!太沒效率了,寫指令撈吧,然後把資料丟去excel做加總。


正文

如果用gcloud compute list 能夠列出機器的類型,但裡面的cpu數量還是不知道。

找了一下發現有人寫好一個shell script,拿來改一下能夠直接列出cpu數量
跟連結的內容相比,我這邊多加了一個狀態。
因為有些機器是不開機的,當有任務時,才會開機,故大部分時間都是關機狀態。

# Get instance name,zone for `${PROJECT}
for PAIR in $(\
  gcloud compute instances list \
  --project=${PROJECT} \
  --format="csv[no-heading](name,zone.scope(zones),status)")
do
  # Parse result from above into instance and zone vars
  IFS=, read INSTANCE ZONE STATUS <<< ${PAIR}
  # Get the machine type value only
  MACHINE_TYPE=$(\
    gcloud compute instances describe ${INSTANCE} \
    --project=${PROJECT} \
    --zone=${ZONE} \
    --format="value(machineType.scope(machineTypes))")
  # If it's custom-${vCPUs}-${RAM} we've sufficient info
  if [[ ${MACHINE_TYPE} == custom* ]]
  then
    IFS=- read CUSTOM CPU MEM <<< ${MACHINE_TYPE}
    printf "%s: vCPUs: %s; Mem: %s; Status: %s\n" ${INSTANCE} ${CPU} ${MEM} ${STATUS}
  else
    # Otherwise, we need to call `machine-types describe`
    CPU_MEMORY=$(\
      gcloud compute machine-types describe ${MACHINE_TYPE} \
      --project=${PROJECT} \
      --zone=${ZONE} \
      --format="csv[no-heading](guestCpus,memoryMb)")
    IFS=, read CPU MEM <<< ${CPU_MEMORY}
    printf "%s: vCPUs: %s; Mem: %s; Status: %s\n" ${INSTANCE} ${CPU} ${MEM} ${STATUS}
  fi
done


ref. gcloud command to display vCPU’s and Memory assigned to Instances

沒有留言:

張貼留言