自动删除 GCP Cloud SQL 按需备份

问题描述 投票:0回答:3

我正在寻找可以在 x 天后自动删除 Cloud SQL 数据库备份的方法。我找到了使用 gcloud 命令创建按需备份的方法。但有人知道有没有一种方法可以自动删除 GCP CloudSQL 中的按需备份?

我已使用以下命令创建按需备份,是否有一个标志可以设置保留此备份的天数?

gcloud sql backups create \ --async \ --instance=my-instance

google-cloud-platform gcloud google-cloud-sql
3个回答
2
投票

这是删除特定日期的备份的代码片段。可以修改为每天运行并删除落后X天。

gcloud sql backups list --instance myinstance --sort-by WINDOW_START_TIME --filter 2023-06-06 --format="value(id)" | while read id; do gcloud sql backups delete --instance myinstance $id; done

输出:

The backup will be deleted. You cannot undo this action.

Do you want to continue (Y/n)?
Deleting backup run...
....done.
Deleted backup run [1186013200000].

1
投票

正如已接受的答案所提到的,我对脚本进行了一些修改,并且能够删除 x 天前创建的按需/自动备份。

使用下面的 shell 脚本删除 7 天前创建的任何备份

#!/bin/bash
current_date=$(date +%Y-%m-%d)
new_date=$(date -d "$current_date - 7 days" +%Y-%m-%d)

gcloud sql backups list --instance=my-instance --sort-by WINDOW_START_TIME --filter $new_date | awk 'NR>1{print $1}' | while read id; do gcloud sql backups delete --instance=my-instance $id; done

在此脚本中,数据库实例名称是 my-instance。


0
投票

基于以上答案。我继续修改脚本以处理两个给定日期之间的删除。

这适用于 macOS。您需要重新调整其他系统。

#!/bin/bash
instance_id=YOUR_INSTANCE_ID
start_date=2021-01-01
end_date=2021-12-31

start_date=$(date -j -f %Y-%m-%d $start_date +%Y-%m-%d)
end_date=$(date -j -f %Y-%m-%d $end_date +%Y-%m-%d)

while [ $start_date != $end_date ]
do
   printf "\033[1;31m-----------------------------------\033[0m\n"
   printf "\033[1;31mDELETING backups from: $start_date!\033[0m\n"

   gcloud sql backups list --instance=$instance_id --sort-by WINDOW_START_TIME --filter $start_date | awk 'NR>1{print $1}' | while read id; do gcloud sql backups delete --quiet --instance=$instance_id $id; done

   printf "\033[1;32mDONE $start_date\033[0m!\n"

   start_date=$(date -j -f %Y-%m-%d -v+1d $start_date +%Y-%m-%d)
done
© www.soinside.com 2019 - 2024. All rights reserved.