ruby Google Cloud Compute使用Rotate创建快照
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了ruby Google Cloud Compute使用Rotate创建快照相关的知识,希望对你有一定的参考价值。
#!/bin/ruby
require 'json'
require 'time'
require 'syslog'
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 --silent "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
msg = "Finished the snapshots"
Syslog.open($0, Syslog::LOG_PID | Syslog::LOG_CONS) { |s| s.info msg }
end
def create_snapshot
msg = "Creating snapshot #{@snapshot_name}"
Syslog.open($0, Syslog::LOG_PID | Syslog::LOG_CONS) { |s| s.info msg }
`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|
msg = "Deleting snapshot #{name}"
Syslog.open($0, Syslog::LOG_PID | Syslog::LOG_CONS) { |s| s.info msg }
`gcloud compute snapshots delete #{name} --quiet`
end
else
msg = "No snapshots to delete"
Syslog.open($0, Syslog::LOG_PID | Syslog::LOG_CONS) { |s| s.info msg }
end
end
def get_snapshots
msg = "Finding snapshots older than #{Time.now - @rotate_period}"
Syslog.open($0, Syslog::LOG_PID | Syslog::LOG_CONS) { |s| s.info msg }
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
以上是关于ruby Google Cloud Compute使用Rotate创建快照的主要内容,如果未能解决你的问题,请参考以下文章
cannot find package "cloud.google.com/go/compute/metadata"
Google Cloud Compute Engine 是不是与 Google Cloud SQL 分开
Google Cloud、Kubernetes 和 Cloud SQL 代理:默认 Compute Engine 服务帐户问题
使用 Go 在 Google Container/Compute Engine 中登录到 Google Cloud
Google Cloud 中的 Google Compute Engine、App Engine 和 Container Engine 有啥区别?
无法在 Google Cloud Compute Engine 上使用 GPU