google-compute-engine - 如何使用 GCE Node.js 客户端从实例模板创建新的 GCE VM 实例?
问题描述
在Google 计算引擎中,我可以使用实例模板从模板创建新的 VM。这使用 GCE 控制台可以正常工作,并且使用API也可以正常工作(URL 参数“sourceInstanceTemplate”)。
如何使用googleapis/nodejs-compute(Node.js GCE SDK)从实例模板创建新的 GCE-VM?
解决方案
google-auth-library-nodejs可用于直接访问GCE instances.insert API。
以下示例改编自https://github.com/google/google-auth-library-nodejs,如果在 GCE 中执行(特别是在Google Cloud Function中),则可以正常工作。
const zone = 'some-zone';
const name = 'a-name';
const sourceInstanceTemplate = `some-template-name`;
createVM(zone, name, sourceInstanceTemplate)
.then(console.log)
.catch(console.error);
async function createVM(zone, vmName, templateName) {
const {auth} = require('google-auth-library');
const client = await auth.getClient({
scopes: 'https://www.googleapis.com/auth/cloud-platform'
});
const projectId = await auth.getDefaultProjectId();
const sourceInstanceTemplate = `projects/${projectId}/global/instanceTemplates/${templateName}`;
const url = `https://www.googleapis.com/compute/v1/projects/${projectId}/zones/${zone}/instances?sourceInstanceTemplate=${sourceInstanceTemplate}`;
return await client.request({
url: url,
method: 'post',
data: {name: vmName}
});
}
推荐阅读
- postgresql - Postgresql:搜索具有相似字符的字符串
- reactjs - 如何在反应原生中使用Formik在另一个屏幕中发送带有路由参数的值?
- django - Django ORM - 根据字符串获取不同的对象
- ios - 如何在 swiftUI 中创建自定义滑块视图?
- django - 如何在 DjangoRestFramework 中实现按图像搜索功能?
- javascript - HTMLElement.querySelector() 使用cheerio
- sql - 未定义行数的计算
- nativescript - 可滚动标签 nativescript
- python - 如何加入熊猫列表?
- google-analytics - 我们如何检查是否正在为谷歌分析跟踪配置文件生成数据?