我想使用 Node 动态获取我的 Google VM 实例的 IP 地址。是否有任何 NPM 软件包或 Google Cloud 是否提供任何 API?我不想手动复制粘贴它。
最佳答案
您可以使用Node.js Client library for Google Compute Engine 。
有多种方法可以检索计算实例的外部 IP 地址,例如您可以运行以下代码:
const Compute = require('@google-cloud/compute');
const compute = new Compute({
projectId: 'your-project-id',
keyFilename: '/your/path/to/file'
});
const zone = compute.zone('instanceZone');
const vm = zone.vm('instanceName');
vm.getMetadata(function(err, metadata, apiResponse) {});
//-
// If the callback is omitted, we'll return a Promise.
//-
vm.getMetadata().then(function(data) {
// Representation of this VM as the API sees it.
const metadata = data[0];
console.log(metadata.networkInterfaces[0].accessConfigs[0].natIP)
});
此外,您还可以使用Google Cloud Platform command-line interface .
gcloud 计算实例描述实例名称 --zone=instanceZone | grep natIP
关于node.js - 有没有办法使用任何 npm 或 Google 云 API 从 Node 获取虚拟机的外部 IP 地址?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54977689/