Azure Web Apps

Azure Web Apps

Determine the slot in which we're running

Via incoming HTTP header

If your code in an Azure Web App for Linux needs to determine in which deployment slot it's running, then the incoming WAS-DEFAULT-HOSTNAME HTTP header seems to be the only reliable way. Also confirmed here.

When you're in the production slot, then the value looks like this: someappname.azurewebsites.net. When you created a slot called stage1, then this header is someappname-stage1.azurewebsites.net. The absence of the suffix points to the production slot, otherwise the suffix gives the user-chosen name.

There's a second header called X_SITE_DEPLOYMENT_ID, but this one contains an identifier like someappname__f375, which isn't too helpful.

<h1>Server <?php echo $_SERVER['HTTP_WAS_DEFAULT_HOSTNAME']; ?></h1>

Via system-assigned managed identity

Another, certainly much more clear way, could be using a system-assigned managed identity, assuming you assigned one to all deployment slots. If you fetch an access_token, then the xms_mirid claim in the JWT contains the real instance ID, such as

  • "/subscriptions/.../resourcegroups/.../providers/Microsoft.Web/sites/someappname" for the production slot, or

  • "/subscriptions/.../resourcegroups/.../providers/Microsoft.Web/sites/someappname/slots/stage1" for the stage1 slot.

Fetching a managed-identity access_token from PHP in an Azure Web App for Linux

  • Inside Azure Web Apps for Linux, you can't simply query the instance metadata endpoint, you need a special endpoint from an environment variable https://docs.microsoft.com/en-us/azure/app-service/overview-managed-identity?tabs=dotnet#using-the-rest-protocol

  • Also api-version must be a special one

<?php
  $resource = 'https://storage.azure.com/';
  $endpoint = $_ENV["IDENTITY_ENDPOINT"];
  $params = array('api-version' => '2019-08-01', 'resource' => $resource);
  $url = $endpoint . '?' . http_build_query($params);
  $headers = array(
      'Metadata: true',
      'X-IDENTITY-HEADER: ' . $_ENV['IDENTITY_HEADER']
  );
  
  $ch = curl_init();
  curl_setopt($ch, CURLOPT_URL, $url);
  curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  $response = curl_exec($ch);
  curl_close ($ch);
  
  $response_json = json_decode($response);
  $access_token = $response_json->{'access_token'};
?>

<a href="https://jwt.ms/#access_token=<?php echo $access_token; ?>" target="_blank">
   See the JWT in https://jwt.ms
</a>

Last updated