How to create and rotate Automatic Snapshot?

前端 未结 10 2066
梦如初夏
梦如初夏 2020-12-14 08:33

On Compute Engine we can do Snapshots, which are basically backups. Could you try to figure out how we could create a script to do automated snapshots every day and keep lik

10条回答
  •  心在旅途
    2020-12-14 09:07

    The following is a very rude ruby script to accomplish this task. Please, consider it just as an example from which to take inspiration.

    Any feedback to improve it is welcome ;-)

    require 'date'
    
    ARCHIVE = 30 # Days
    DISKS   = [] # The names of the disks to snapshot
    FORMAT  = '%y%m%d'
    
    today = Date.today
    date = today.strftime(FORMAT).to_i
    limit = (today - ARCHIVE).strftime(FORMAT).to_i
    
    # Backup
    `gcloud compute disks snapshot #{DISKS.join(' ')} --snapshot-names #{DISKS.join("-#{date},")}-#{date}`
    
    # Rotate
    snapshots = []
    `gcloud compute snapshots list`.split("\n").each do |row|
      name = date
      row.split("\s").each do |cell|
        name = cell
        break
      end
      next if name == 'NAME'
      snapshots << name if name[-6, 6].to_i < limit
    end
    `yes | gcloud compute snapshots delete #{snapshots.join(' ')}` if snapshots.length > 0
    

提交回复
热议问题