我创建了一个 Google Cloud Compute Engine,并每晚对其进行备份(快照)。我在同一个项目中有第二个 VM,它是第一个 VM 的克隆。每次都可以使用第一个 VM 的刚创建的新快照更新第二个 VM 实例吗?所以我有一个故障回复服务器,它最多有 24 小时的历史?
答案1
答案2
如果有人遇到同样的问题,我编写了一个云函数并每天安排它。步骤如下:
- 获取最新快照
- 删除旧虚拟机
- 创建新虚拟机
- 将新创建的 VM IP 放入 Cloudflare LoadBalancer
这是它的代码:
const Compute = require("@google-cloud/compute");
const axios = require("axios");
const compute = new Compute({
projectId: "myProjectID",
keyFilename: "./gcloud_key.json"
});
exports.updateFailOverVM = async (pubSubEvent, context) => {
try {
const snapshots = await compute.getSnapshots({
orderBy: "creationTimestamp desc"
});
const snapshot = snapshots[0][0];
console.log(`Going to use Snapshot: ${snapshot.name}`);
const sourceSnapshot = `https://www.googleapis.com/compute/v1/projects/myProjectID/global/snapshots/${snapshot.name}`;
const zone = compute.zone("MySelectedZone");
const vm = zone.vm("MyVMName");
// Delete old FailOver
console.log("start deleting old VM");
const [deleteOperation] = await vm.delete();
deleteOperation.on("complete", async function(metadata) {
console.log("finished deleting old VM");
// Create new VM
console.log("start creating new VM");
const [newVM, createOperation] = await vm.create({
http: false,
https: true,
machineType: "n1-standard-1",
disks: [
{
initializeParams: {
sourceSnapshot
},
sizeGb: 50,
type:
"projects/MyProjectID/zones/mySelectedZone/diskTypes/pd-standard",
boot: true
}
]
});
createOperation.on("complete", async function(metadata) {
const [newVMMeta] = await vm.getMetadata();
const newIP = newVMMeta.networkInterfaces[0].accessConfigs[0].natIP;
console.log("finished creating new VM");
// Route Cloudflare to new IP
console.log("Put new IP to Cloudflare");
await axios({
method: "patch",
url:
"https://api.cloudflare.com/client/v4/user/load_balancers/pools/MyPoolID",
data: {
origins: [
{
name: "MyPoolName",
address: newIP,
enabled: true,
weight: 1
}
]
},
headers: {
"X-Auth-Email": "MyCloudflareEmail",
"X-Auth-Key": "MyCloudflareAuthKey"
}
});
console.log("Finished putting IP to Cloudflare");
});
});
} catch (err) {
console.error(err);
}
};