-
-
Save rrichards/0fb711e8cd5a2674cb1ab9c5fb8a6233 to your computer and use it in GitHub Desktop.
Google Compute Engine Snapshot Create and Rotate in Ruby
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/ruby | |
require 'json' | |
require 'time' | |
class Snapshot | |
def initialize() | |
@format = 'json' | |
@zone = get_zone | |
@hostname = hostname | |
@time = Time.now.to_i | |
@regex = ".*#{@hostname}.*" | |
@snapshot_name = "#{@hostname}-#{@time}" | |
@rotate_days = 3 | |
@rotate_period = @rotate_days * 60 * 60 *24 | |
@disk_name = get_primary_disk | |
end | |
def get_zone | |
output = `curl --silent "http://metadata.google.internal/computeMetadata/v1/instance/zone" -H "Metadata-Flavor: Google"` | |
output.split("/").last | |
end | |
def hostname | |
hostname = `curl "http://metadata.google.internal/computeMetadata/v1/instance/hostname" -H "Metadata-Flavor: Google"` | |
hostname.split(".").first | |
end | |
def get_primary_disk | |
instance = `gcloud compute instances describe #{@hostname} --format json --zone #{@zone}` | |
instance = JSON.parse instance | |
instance["disks"][0]["deviceName"] | |
end | |
def run_backup | |
create_snapshot | |
delete_old_snapshots | |
end | |
def create_snapshot | |
puts "Creating snapshot #{@snapshot_name}" | |
`gcloud compute disks snapshot #{@disk_name} --snapshot-name #{@snapshot_name} --zone #{@zone}` | |
end | |
def delete_old_snapshots | |
snapshots = get_snapshots | |
if snapshots.length > 0 | |
snapshots.each do |name| | |
puts "Deleting snapshot #{name}" | |
`gcloud compute snapshots delete #{name} --quiet` | |
end | |
else | |
puts "No snapshots to delete" | |
end | |
end | |
def get_snapshots | |
puts "Finding snapshots older than #{Time.now - @rotate_period}" | |
instances = `gcloud compute snapshots list --format #{@format} --regex #{@regex}` | |
instances = JSON.parse instances | |
instances.select { |instance| Time.parse(instance["creationTimestamp"]) <= Time.now - (@rotate_period) }.map { |instance| instance["name"] } | |
end | |
end | |
snapshot = Snapshot.new | |
snapshot.run_backup |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment