らんだむな記憶

blogというものを体験してみようか!的なー

nodeでCompute Engine APIを使って外部IPを取得したい

ら辺を参考にする。

$ npm install --save googleapis

して、「IAM と管理」の「サービス アカウント」から取得した credentials の json を適当な場所に置いて

export GOOGLE_APPLICATION_CREDENTIALS="[PATH]" >> ~/.bashrc

で参照させる。で、Method: instances.get  |  Compute Engine ドキュメント  |  Google Cloudを見つつ、以下のようなスクリプトnode で実行すれば良いはず。(npm install時に「--save」オプションはいらない - Qiitaによると --save はもう不要らしい)
[gce-ip.js]

const {google} = require('googleapis');
const compute = google.compute('v1');

async function getVMsExternalIP() {
  const authClient = await google.auth.getClient({
    scopes: [
      'https://www.googleapis.com/auth/cloud-platform',
      'https://www.googleapis.com/auth/compute',
      'https://www.googleapis.com/auth/compute.readonly',
    ],
  });

  const projectId = await google.auth.getProjectId();
  const result = await compute.instances.get({
    auth: authClient,
    project: projectId,
    zone: "us-west1-b",
    instance: "ml-dev"
  });
  console.log(result.data.networkInterfaces[0].accessConfigs[0].natIP);
}

getVMsExternalIP()

う〜ん。curl だけでいけないのかな?

で、~/.bashrc に以下のような記述を追加すれば捗る。

function gce-ip()
{
    node ~/gce-ip.js
}