Set or change a block blob's access tier with TypeScript

This article shows how to set or change a blob's access tier with the Azure Storage client library for JavaScript.

Prerequisites

  • The examples in this article assume you already have a project set up to work with the Azure Blob Storage client library for JavaScript. To learn about setting up your project, including package installation, importing modules, and creating an authorized client object to work with data resources, see Get started with Azure Blob Storage and TypeScript.
  • The authorization mechanism must have permissions to set the blob's access tier. To learn more, see the authorization guidance for the following REST API operation:

About block blob access tiers

To manage costs for storage needs, it can be helpful to organize your data based on how frequently it's accessed and how long it needs to be retained. Azure storage offers different access tiers so that you can store your blob data in the most cost-effective manner based on how it's being used.

Access tiers for blob data

Azure Storage access tiers include:

  • Hot tier - An online tier optimized for storing data that is accessed or modified frequently. The hot tier has the highest storage costs, but the lowest access costs.
  • Cool tier - An online tier optimized for storing data that is infrequently accessed or modified. Data in the cool tier should be stored for a minimum of 30 days. The cool tier has lower storage costs and higher access costs compared to the hot tier.
  • Cold tier - An online tier optimized for storing data that is infrequently accessed or modified. Data in the cold tier should be stored for a minimum of 90 days. The cold tier has lower storage costs and higher access costs compared to the cool tier.
  • Archive tier - An offline tier optimized for storing data that is rarely accessed, and that has flexible latency requirements, on the order of hours. Data in the archive tier should be stored for a minimum of 180 days.

To learn more about access tiers, see Access tiers for blob data.

While a blob is in the Archive access tier, it's considered to be offline, and can't be read or modified. In order to read or modify data in an archived blob, you must first rehydrate the blob to an online tier. To learn more about rehydrating a blob from the Archive tier to an online tier, see Blob rehydration from the Archive tier.

Restrictions

Setting the access tier is only allowed on block blobs. To learn more about restrictions on setting a block blob's access tier, see Set Blob Tier (REST API).

Note

To set the access tier to Cold using TypeScript, you must use a minimum client library version of 12.13.0.

Set a blob's access tier during upload

To upload a blob into a specific access tier, use the BlockBlobUploadOptions. The tier property choices are: Hot, Cool, Cold, or Archive.

async function uploadWithAccessTier(
  containerClient: ContainerClient
): Promise<BlockBlobClient> {
  // Create blob
  const timestamp = Date.now();
  const blobName = `myblob-${timestamp}`;
  console.log(`creating blob ${blobName}`);

  const fileContentsAsString = `Hello from a string`;

  const tags: Tags = {};

  // Upload blob to cool tier
  const uploadOptions: BlockBlobUploadOptions = {
    // access tier setting
    // 'Hot', 'Cool', or 'Archive'
    tier: 'Cool',

    // other properties
    metadata: undefined,
    tags
  };

  // Create blob client from container client
  const blockBlobClient: BlockBlobClient =
    await containerClient.getBlockBlobClient(blobName);

  // Upload string
  const uploadResult = await blockBlobClient.upload(
    fileContentsAsString,
    fileContentsAsString.length,
    uploadOptions
  );

  if (uploadResult.errorCode) throw Error(uploadResult.errorCode);

  // Return client to continue with other operations
  return blockBlobClient;
}

Change a blob's access tier after upload

To change the access tier of a blob after it's uploaded to storage, use setAccessTier. Along with the tier, you can set the BlobSetTierOptions property rehydration priority to bring the block blob out of an archived state. Possible values are High or Standard.

async function main(blockBlobClient: BlockBlobClient): Promise<void> {
  const options: BlobGetPropertiesOptions = {};

  // Get current access tier
  const { errorCode, accessTier } = await blockBlobClient.getProperties(
    options
  );
  if (!errorCode) {
    console.log(`Current access tier: ${accessTier}`);
  }

  // 'Hot', 'Cool', or 'Archive'
  const newAccessTier = 'Cool';

  // Rehydrate priority: 'High' or 'Standard'
  const tierOptions: BlobSetTierOptions = {
    rehydratePriority: 'High'
  };

  const result: BlobSetTierResponse = await blockBlobClient.setAccessTier(
    newAccessTier,
    tierOptions
  );

  if (!result?.errorCode) {
    console.log(`Change to access was successful`);
  } else {
    console.log(result);
  }
}

Copy a blob into a different access tier

Use the BlobClient.beginCopyFromURL method to copy a blob. To change the access tier during the copy operation, use the BlobBeginCopyFromURLOptions tier property and specify a different access tier than the source blob.

async function copyBlobWithDifferentAccessTier(
  containerClient: ContainerClient
): Promise<void> {
  // create blob clients
  const sourceBlobClient: BlobClient = await containerClient.getBlobClient(
    originalBlob
  );
  const destinationBlobClient: BlobClient = await containerClient.getBlobClient(
    copyBlob
  );

  const copyOptions: BlobBeginCopyFromURLOptions = { tier: 'Hot' };

  // start copy, access tiers include `Hot`, `Cool`, `Archive`
  const copyPoller = await destinationBlobClient.beginCopyFromURL(
    sourceBlobClient.url,
    copyOptions
  );
  console.log('start copy from original to copy');

  // wait until done
  await copyPoller.pollUntilDone();
  console.log('copy finished');
}

Use a batch to change access tier for many blobs

The batch represents an aggregated set of operations on blobs, such as delete or set access tier. You need to pass in the correct credential to successfully perform each operation. In this example, the same credential is used for a set of blobs in the same container.

Create a BlobBatchClient. Use the client to create a batch with the createBatch() method. When the batch is ready, submit the batch for processing. Use the returned structure to validate each blob's operation was successful.

async function batchChangeAccessTier(
  containerClient: ContainerClient
): Promise<void> {
  // Prep array
  const blockBlobCount = 3;
  const blockBlobClients: BlockBlobClient[] = new Array(blockBlobCount);

  // Create container and blobs in `Hot` tier
  await prepContainer(containerClient, blockBlobCount, blockBlobClients);

  // Blob batch client and batch
  const containerScopedBatchClient: BlobBatchClient =
    containerClient.getBlobBatchClient();
  const blobBatch: BlobBatch = containerScopedBatchClient.createBatch();

  // Assemble batch to set tier to `Cool` tier
  for (let i = 0; i < blockBlobCount; i++) {
    await blobBatch.setBlobAccessTier(
      blockBlobClients[i].url,
      sharedKeyCredential,
      'Cool',
      {}
    );
  }

  // Submit batch request and verify response
  const resp = await containerScopedBatchClient.submitBatch(blobBatch, {});

  if (resp.errorCode) throw Error(resp.errorCode);

  console.log(
    `Requested ${blockBlobCount}, batched ${resp.subResponses.length}, success ${resp.subResponsesSucceededCount}, failure ${resp.subResponsesFailedCount}`
  );

  // Examine each batch item
  for (let i = 0; i < blockBlobCount; i++) {
    // Check blob tier set properly
    const resp2 = await blockBlobClients[i].getProperties();

    if (resp2.errorCode) throw Error(resp2.errorCode);

    console.log(
      `[${i}] access tier ${resp2.accessTier}, status ${resp.subResponses[i].status}, message ${resp.subResponses[i].statusMessage}`
    );
  }
}

Code samples

Next steps