Finding deployment ID or commit hash with Azure Web Apps Node.JS

in Cloud & Serverless


You deploy your Node.js code to Azure Web Apps. In your code, you want a way to know the commit ID/hash of the latest deployment.

Unfortunately, Azure does not keep the information on the latest commit it deployed in environment variables. And git is not available either for us to look it up with git rev-parse.

Set up build.js

This script saves build information to build.json which we can later access at any time after deployment. The script can have any name, not necessarily build.js, just make sure it matches what you put into your package.json in the next step.

const fs = require('fs');
const path = require('path');

// Debug info, see Azure Deployment Center logs
console.log("process.env\n", process.env);

// Define path to build.json where build information will be stored
const filePath = path.join(__dirname, 'build.json');

try {
    // Create object with build data
    const buildData = {commitHash: process.env.SCM_COMMIT_ID};
    // Write build data to build.json
    fs.writeFileSync(filePath, JSON.stringify(buildData), 'utf-8');
} catch (error) {
    console.error('Failed to generate '+filePath, error);
}

SCM_COMMIT_ID comes from projectkudu/kudu where it was introduced in 2013. Kudu is the engine behind git deployments in Azure App Service. The repository was set to be a read-only public archive in late September 2024, but the tool is said to continue on Azure. There are other environment variables available during deployment, see https://github.com/projectkudu/kudu/wiki/Deployment-Environment.

Add your build.js to package.json

Use the scriptsbuild directive in package.json to schedule our script to be executed on each build.

{
  "name": "example application",
  "version": "1.0.0",
  // ...
  "scripts": {
    "build": "node build.js",
  },
  // ...
}

Read the build information when you need it

Here's how you can get that information anywhere inside your Node.js application.

const fs = require('fs');
const path = require('path');

// Read the build information
const filePath = path.join(process.cwd(), 'build.json');
const buildData = JSON.parse(fs.readFileSync(filePath, 'utf-8'));
// Here's the commit hash
console.log(buildData.commitHash);

Bonus points

If you do have access to git during build, then simply do this in your build.js:

const { execSync } = require('child_process');

const commitHash = execSync('git rev-parse --short HEAD').toString().trim();

This way you can get the latest commit hash without relying on Azure/Kudu-specific environment variables.

#node-js #microsoft-azure