# Blob Storage

Source: /azure/services/blob-storage/

## Introduction

Azure Blob Storage is a highly scalable object storage solution optimized for storing massive volumes of unstructured data, such as text and binary content. It supports block blobs, append blobs, and page blobs, and is commonly used for serving documents, images, and streaming media. For more information, see [Introduction to Azure Blob Storage](https://learn.microsoft.com/en-us/azure/storage/blobs/storage-blobs-introduction).

LocalStack for Azure provides a local environment for building and testing applications that make use of Azure Blob Storage.
The supported APIs are available on our [API Coverage section](#api-coverage), which provides information on the extent of Blob Storage's integration with LocalStack.

## Getting started

This guide is designed for users new to Blob Storage and assumes basic knowledge of the Azure CLI and our `lstk az` proxy.

Launch LocalStack using your preferred method. For more information, see [Introduction to LocalStack for Azure](/azure/getting-started/). Once the container is running, enable Azure CLI interception by running:

```bash
lstk az start-interception
```

### Create a resource group

Create a resource group to contain your storage resources:

```bash
az group create \
  --name rg-blob-demo \
  --location westeurope
```

```bash title="Output"
{
  "id": "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/rg-blob-demo",
  "location": "westeurope",
  "managedBy": null,
  "name": "rg-blob-demo",
  "properties": {
    "provisioningState": "Succeeded"
  },
  "tags": null,
  "type": "Microsoft.Resources/resourceGroups"
}
```

### Create a storage account

Create a storage account in the resource group:

```bash
az storage account create \
  --name stblobdemols \
  --resource-group rg-blob-demo \
  --location westeurope \
  --sku Standard_LRS \
  --only-show-errors
```

```bash title="Output"
{
  ...
  "id": "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/rg-blob-demo/providers/Microsoft.Storage/storageAccounts/stblobdemols",
  ...
  "name": "stblobdemols",
  ...
  "placement": null,
  "primaryEndpoints": {
    "blob": "https://stblobdemols.blob.core.azure.localhost.localstack.cloud:456",
    ...
  },
  ....
}
```

### Authentication

There are three ways to authenticate storage container commands against the emulator:

#### Storage account key

Retrieve the account key and pass it with `--account-name` and `--account-key`:

```bash
ACCOUNT_KEY=$(az storage account keys list \
  --account-name stblobdemols \
  --resource-group rg-blob-demo \
  --query "[0].value" \
  --output tsv)

az storage container list \
  --account-name stblobdemols \
  --account-key "$ACCOUNT_KEY"
```

#### Login credentials

Use `--auth-mode login` to authenticate with the current session credentials:

```bash
az storage container list \
  --account-name stblobdemols \
  --auth-mode login
```

#### Connection string

Bundle the account name and key into a single value:

```bash
CONNECTION_STRING=$(az storage account show-connection-string \
  --name stblobdemols \
  --resource-group rg-blob-demo \
  --query connectionString -o tsv)

az storage container list \
  --connection-string "$CONNECTION_STRING"
```

The remaining examples in this guide use connection strings for brevity.

### Create and inspect a blob container

Create a container in the storage account:

```bash
az storage container create \
  --name documents \
  --connection-string "$CONNECTION_STRING"
```

```bash title="Output"
{
  "created": true
}
```

Verify the container exists:

```bash
az storage container exists \
  --name documents \
  --connection-string "$CONNECTION_STRING"
```

```bash title="Output"
{
  "exists": true
}
```

List containers in the storage account:

```bash
az storage container list \
  --connection-string "$CONNECTION_STRING"
```

```bash title="Output"
[
  {
    ...
    "name": "documents",
    "properties": {
      ...
      "lease": {
        ...
      },
      ...
    },
    ...
  }
]
```

### Upload, list, and download blobs

Upload a local file as a block blob:

```bash
echo "Hello from LocalStack" > /tmp/hello.txt

az storage blob upload \
  --container-name documents \
  --name hello.txt \
  --file /tmp/hello.txt \
  --connection-string "$CONNECTION_STRING"
```

```bash title="Output"
{
  "client_request_id": "...",
  "content_md5": "...",
  "date": "...",
  "etag": "...
  ...
}
```

List blobs in the container:

```bash
az storage blob list \
  --container-name documents \
  --connection-string "$CONNECTION_STRING" \
  --output table
```

Download the blob to a local file:

```bash
az storage blob download \
  --container-name documents \
  --name hello.txt \
  --file /tmp/hello-downloaded.txt \
  --connection-string "$CONNECTION_STRING"
```

```bash title="Output"
Finished[#############################################################]  100.0000%
{
  "container": "documents",
  ...
}
```

Delete the blob:

```bash
az storage blob delete \
  --container-name documents \
  --name hello.txt \
  --connection-string "$CONNECTION_STRING"
```

## Immutability and legal holds

A container immutability policy keeps blobs from being modified or deleted during a retention period, and a legal hold protects a container until you clear it. For more information, see [Overview of immutable storage for blob data](https://learn.microsoft.com/en-us/azure/storage/blobs/immutable-storage-overview).

Create a container and apply a time-based retention policy of one day:

```bash
az storage container create \
  --name worm \
  --connection-string "$CONNECTION_STRING"

az storage container immutability-policy create \
  --account-name stblobdemols \
  --resource-group rg-blob-demo \
  --container-name worm \
  --period 1
```

```bash title="Output"
{
  "allowProtectedAppendWrites": null,
  "allowProtectedAppendWritesAll": null,
  "etag": "\"3faf76b8653cea\"",
  "immutabilityPeriodSinceCreationInDays": 1,
  "name": "default",
  "state": "Unlocked",
  ...
}
```

Upload a blob, then try to overwrite and delete it. The emulator refuses both while the blob is within the retention period:

```bash
az storage blob upload \
  --container-name worm \
  --name hello.txt \
  --file /tmp/hello.txt \
  --connection-string "$CONNECTION_STRING"

az storage blob delete \
  --container-name worm \
  --name hello.txt \
  --connection-string "$CONNECTION_STRING"
```

```bash title="Output"
ERROR: This operation is not permitted as the blob is immutable due to a policy.
ErrorCode:BlobImmutableDueToPolicy
```

Lock the policy, then extend the retention period. A locked policy can only be extended, and the container can't be deleted while it holds a blob within retention:

```bash
ETAG=$(az storage container immutability-policy show \
  --account-name stblobdemols \
  --resource-group rg-blob-demo \
  --container-name worm \
  --query etag -o tsv)

az storage container immutability-policy lock \
  --account-name stblobdemols \
  --resource-group rg-blob-demo \
  --container-name worm \
  --if-match "$ETAG"
```

```bash title="Output"
{
  ...
  "state": "Locked",
  ...
}
```

```bash
az storage container delete \
  --name worm \
  --connection-string "$CONNECTION_STRING"
```

```bash title="Output"
ERROR: The requested operation is not allowed as the container has a locked immutability policy.
ErrorCode:ContainerImmutabilityPolicyLocked
```

Set a legal hold on a container:

```bash
az storage container legal-hold set \
  --account-name stblobdemols \
  --resource-group rg-blob-demo \
  --container-name held \
  --tags audit
```

```bash title="Output"
{
  "allowProtectedAppendWritesAll": null,
  "hasLegalHold": true,
  "tags": [
    "audit"
  ]
}
```

Deleting the container, or changing a blob in it, returns `ContainerHasLegalHold` or `BlobImmutableDueToLegalHold`. Clear the hold with `az storage container legal-hold clear`.

:::note
- A legal hold protects its container even when it's empty. A time-based policy blocks container deletion only while the container holds a blob that is still within the retention period.
- Tier, tag, and lease changes are allowed on an immutable blob, as on Azure.
- `allowProtectedAppendWrites` and `allowProtectedAppendWritesAll` exempt only Append Block. Put Block, Put Block List, and Put Page on an existing blob stay refused.
:::

## Features

The Blob Storage emulator supports the following features:

- **Data plane REST API**: Blob CRUD, message operations (put, peek, get, delete), container metadata, stored access policies, and SAS token generation.
- **Data plane authentication**: Shared Key, SharedKeyLite, and account, service, stored access policy, and user delegation SAS requests are validated. See [Storage Account: Data plane authentication](/azure/services/storage-accounts/#data-plane-authentication).
- **Control plane REST API**: Create, delete, get, and list containers, and get and set blob service properties via Azure Resource Manager.
- **Immutability policies**: Create, get, delete, lock, and extend a container's time-based retention policy. See [Immutability and legal holds](#immutability-and-legal-holds).
- **Legal holds**: Set and clear legal hold tags on a container.
- **Container leases**: Acquire and release a lease on a container. Deleting a leased container without its lease ID fails with `LeaseIdMissing`.
- **Object-level immutability**: Object-level WORM (write once, read many) for containers.
- **Blob service properties**: Setting service properties stores what you send (CORS, delete retention, versioning, change feed, and restore policy), validated as Azure does, and getting them returns the stored values. Setting an empty value echoes an empty resource.
- **Persistence**: With persistence enabled, blob data survives a restart.
- **Multiple authentication modes**: Storage account key, login credentials, and connection strings.

## Limitations

- **Persistence must be enabled**: Blob data survives a restart only when persistence is on. Without it, blob data is lost when the LocalStack emulator is stopped or restarted.
- **Service properties are stored, not applied**: The emulator stores and returns the settings you set, such as CORS rules, but doesn't act on them.
- **Unsupported control plane operations**: Container update, blob service list, and management policies are not yet supported.
- **Immutability enforcement is limited to recorded operations**: The emulator refuses Delete Blob, Put Blob, Put Block, Put Block List, Put Page, Append Block, Set Blob Metadata, Set Blob Properties, and Snapshot Blob on a blob under a policy or legal hold. Any other blob write succeeds.
- **Container deletion checks the first page of blobs only**: When a container has an immutability policy, the emulator reads only the first 5,000 blobs. A container whose in-retention blobs all fall after that page can be deleted.
- **Unreadable creation time counts as in retention**: A blob whose creation time the emulator can't read is treated as still within the retention period.
- **Storage account keys**: Keys are emulator-generated rather than managed by Azure.
- **Header validation**: Unsupported request headers or parameters are silently accepted instead of being rejected.
- **API version enforcement**: The emulator does not validate the `x-ms-version` header; all API versions are accepted.
- **RBAC enforcement is opt-in**: By default, data-plane operations succeed regardless of role assignments. Set `LS_AZURE_ENFORCE_RBAC` to require the caller to hold a role such as `Storage Blob Data Contributor`; see [Role Assignment: Enabling RBAC enforcement](/azure/services/role-assignment/#enabling-rbac-enforcement).

## Event Grid events

Blob Storage publishes events to the [Event Grid](/azure/services/event-grid/) system topic whose source is the storage account. Create the system topic and an event subscription first, because the emulator doesn't create system topics automatically.

| Event type | Raised by |
|------------|-----------|
| `Microsoft.Storage.BlobCreated` | `PutBlob` and `PutBlockList` |
| `Microsoft.Storage.BlobDeleted` | `DeleteBlob` |

:::note
The emulator doesn't raise events for copy operations, `PutBlobFromUrl`, Data Lake operations, or deletes scoped to a snapshot or a version. It always reports `accessTier` as `Default` in `BlobCreated` events.
:::

## Samples

The following samples demonstrate how to use Azure Blob Storage with LocalStack for Azure:

- [Azure Functions Sample with LocalStack for Azure](https://github.com/localstack/localstack-azure-samples/tree/main/samples/function-app-storage-http/dotnet)
- [Azure Functions App with Managed Identity](https://github.com/localstack/localstack-azure-samples/tree/main/samples/function-app-managed-identity/python)
- [Function App and Service Bus](https://github.com/localstack/localstack-azure-samples/samples/function-app-service-bus/dotnet/README.md)
- [Azure Web App with Managed Identity](https://github.com/localstack/localstack-azure-samples/tree/main/samples/web-app-managed-identity/python)

## API Coverage


### Blob Storage API coverage

Source service: `blob-storage`. 17 of 17 tracked operations are implemented.

Service documentation: /azure/services/blob-storage/

| Operation | Status |
| --- | --- |
| BlobContainers.ClearLegalHold | Implemented |
| BlobContainers.Create | Implemented |
| BlobContainers.CreateOrUpdateImmutabilityPolicy | Implemented |
| BlobContainers.Delete | Implemented |
| BlobContainers.DeleteImmutabilityPolicy | Implemented |
| BlobContainers.ExtendImmutabilityPolicy | Implemented |
| BlobContainers.Get | Implemented |
| BlobContainers.GetImmutabilityPolicy | Implemented |
| BlobContainers.Lease | Implemented |
| BlobContainers.List | Implemented |
| BlobContainers.LockImmutabilityPolicy | Implemented |
| BlobContainers.ObjectLevelWorm | Implemented |
| BlobContainers.SetLegalHold | Implemented |
| BlobContainers.Update | Implemented |
| BlobServices.GetServiceProperties | Implemented |
| BlobServices.List | Implemented |
| BlobServices.SetServiceProperties | Implemented |
