Get app-engine's current instance id in node.js

1.6k Views Asked by At

Is there any way to get the current instance id from app-engine in node.js?

I found solutions only for java and python but nothing for node.

2

There are 2 best solutions below

0
On

You can use the Node.js AWS SDK to do it as well, version 3 has async version built in but we use version 2 so I rolled my own promise version to call it from our app which is using koa but would work equally well in express etc.

const getInstanceId = () => {
  return new Promise((resolve, reject) => {
    const meta = new AWS.MetadataService();
    meta.request('/latest/meta-data/instance-id', (err, data) => {
      if (err) {
        reject(err);
      } else {
        resolve(data);
      }
    });
  });
};

Then you can call it in async code:

try {
  const results = await getInstanceId();
  logger.info('Instance details: ', results);
} catch (e) {
  logger.error('Error occurred', e);
}
0
On

As there's no traditional App Engine runtime for nodejs, I'm assuming you're using Flexible Environment (AKA "Custom Runtimes"). In such a case, you can read in the docs that using the Compute Engine Metadata Server can provide the information you're looking for. Custom Runtime / Flex apps are actually running in a Docker container on a Compute Engine VM. The docs say:

Each instance of your application can use the Compute Engine metadata server to query information about the instance, including its host name, external IP address, instance ID, custom metadata, and service account information. App Engine does not allow you to set custom metadata for each instance, but you can set project-wide custom metadata and read it from your App Engine and Compute Engine instances.

Cheers!