最終版本
#!/bin/bash
date=$(date +"%Y_%m_%d_%H_%M")
api_key=$YOUR_API_KEY
label=$YOUR_VPS_LABEL
description=$label"_"$date
max_snapshots=3
sub_id=$(curl -H "API-Key: $api_key" https://api.vultr.com/v1/server/list | jq '.[] | select(.label=="'$label'") | .SUBID' -r)
snapshots=`curl -H "API-Key: $api_key" https://api.vultr.com/v1/snapshot/list | jq '[.[] | select(.description | contains("'$label'")) | .SNAPSHOTID ]'`
if ((`echo $snapshots | jq length` > 2)); then
snapshot_id=`echo $snapshots | jq '.[2]' -r`
curl -H "API-Key: $api_key" https://api.vultr.com/v1/snapshot/destroy --data "SNAPSHOTID=$snapshot_id"
fi
curl -H "API-Key: $api_key" https://api.vultr.com/v1/snapshot/create --data "SUBID=$sub_id&description=$description"
分段解析
date=$(date +"%Y_%m_%d_%H_%M")
api_key=$YOUR_API_KEY
label=$YOUR_VPS_LABEL
description=$label"_"$date
max_snapshots=3
- description 改成 label + 時間戳
- max_snapshots: 最多只保留三個備份
sub_id=$(curl -H "API-Key: $api_key" https://api.vultr.com/v1/server/list | jq '.[] | select(.label=="'$label'") | .SUBID' -r)
透過 label 取回要備份的 VPS ID。
snapshots=`curl -H "API-Key: $api_key" https://api.vultr.com/v1/snapshot/list | jq '[.[] | select(.description | contains("'$label'")) | .SNAPSHOTID ]'`
- | select(.description | contains("'$label'"))
從清單中篩選出 description 包含有 $label 的 snapshot。
- | .SNAPSHOTID
只留下 SNAPSHOTID 欄位。
- '[ ..... ]'
最外層的 [] 是用來產生新陣列(e.g. [ "1715d7a02f2a6", "e865d793622dc", "aae5d788d62a1" ]),方便後續處理。