.NET에서 Blob 스냅샷 만들기 및 관리

스냅샷은 특정 시점에 생성된 Blob의 읽기 전용 버전입니다. 이 문서에서는 .NET용 Azure Storage 클라이언트 라이브러리를 사용하여 Blob 스냅샷을 만들고 관리하는 방법을 보여 줍니다.

Azure Storage의 Blob 스냅샷에 대한 자세한 내용은 Blob 스냅샷을 참조하세요.

필수 조건

환경 설정

기존 프로젝트가 없는 경우 이 섹션에서는 .NET용 Azure Blob Storage 클라이언트 라이브러리로 작업하도록 프로젝트를 설정하는 방법을 보여 줍니다. 이 단계에는 패키지 설치, 지시문 추가 using 및 권한 있는 클라이언트 개체 만들기가 포함됩니다. 자세한 내용은 Azure Blob Storage 및 .NET 시작을 참조하세요.

패키지 설치

프로젝트 디렉터리에서 dotnet add package 명령을 사용하여 Azure Blob Storage 및 Azure ID 클라이언트 라이브러리용 패키지를 설치합니다. Azure 서비스에 암호 없이 연결하려면 Azure.Identity 패키지가 필요합니다.

dotnet add package Azure.Storage.Blobs
dotnet add package Azure.Identity

using 지시문 추가

코드 파일의 맨 위에 다음 using 지시문을 추가합니다.

using Azure.Identity;
using Azure.Storage.Blobs;
using Azure.Storage.Blobs.Models;
using Azure.Storage.Blobs.Specialized;

이 문서의 일부 코드 예제에는 추가 using 지시문이 필요할 수 있습니다.

클라이언트 개체 만들기

Blob Storage에 앱을 연결하려면 BlobServiceClient 인스턴스를 만듭니다. 다음 예에서는 권한 부여를 위해 DefaultAzureCredential을 사용하여 클라이언트 개체를 만드는 방법을 설명합니다.

public BlobServiceClient GetBlobServiceClient(string accountName)
{
    BlobServiceClient client = new(
        new Uri($"https://{accountName}.blob.core.windows.net"),
        new DefaultAzureCredential());

    return client;
}

.NET 앱에서 종속성 주입을 위해 서비스 클라이언트를 등록할 수도 있습니다. 클라이언트 개체 만들기 및 관리에 대한 자세한 내용은 데이터 리소스와 상호 작용하는 클라이언트 개체 만들기 및 관리를 참조하세요.

권한 부여

권한 부여 메커니즘에는 Blob 스냅샷을 사용하는 데 필요한 권한이 있어야 합니다. Microsoft Entra ID로 권한을 부여하려면(권장) Azure RBAC 기본 제공 역할 Storage Blob 데이터 기여자 이상이 필요합니다. 자세한 내용은 스냅샷 Blob에 대한 권한 부여 지침을 참조하세요.

스냅샷 만들기

블록 Blob의 스냅샷을 만들려면 다음 메서드 중 하나를 사용합니다.

다음 코드 예제에서는 스냅샷을 만드는 방법을 보여 줍니다. Microsoft Entra 자격 증명을 사용하여 서비스에 대한 요청을 승인하려면 Azure.Identity 라이브러리에 대한 참조를 포함합니다. DefaultAzureCredential 클래스를 사용하여 Azure Storage에 액세스할 수 있는 관리 ID를 인증하는 방법에 대한 자세한 내용은 .NET용 Azure ID 클라이언트 라이브러리를 참조하세요.

private static async Task CreateBlockBlobSnapshot(
    string accountName,
    string containerName, 
    string blobName,
    Stream data)
{
    const string blobServiceEndpointSuffix = ".blob.core.windows.net";
    Uri containerUri = 
        new Uri("https://" + accountName + blobServiceEndpointSuffix + "/" + containerName);

    // Get a container client object and create the container.
    BlobContainerClient containerClient = new BlobContainerClient(containerUri,
        new DefaultAzureCredential());
    await containerClient.CreateIfNotExistsAsync();

    // Get a blob client object.
    BlobClient blobClient = containerClient.GetBlobClient(blobName);

    try
    {
        // Upload text to create a block blob.
        await blobClient.UploadAsync(data);

        // Add blob metadata.
        IDictionary<string, string> metadata = new Dictionary<string, string>
        {
            { "ApproxBlobCreatedDate", DateTime.UtcNow.ToString() },
            { "FileType", "text" }
        };
        await blobClient.SetMetadataAsync(metadata);

        // Sleep 5 seconds.
        System.Threading.Thread.Sleep(5000);

        // Create a snapshot of the base blob.
        // You can specify metadata at the time that the snapshot is created.
        // If no metadata is specified, then the blob's metadata is copied to the snapshot.
        await blobClient.CreateSnapshotAsync();
    }
    catch (RequestFailedException e)
    {
        Console.WriteLine(e.Message);
        Console.ReadLine();
        throw;
    }
}

스냅샷 삭제

Blob을 삭제하려면 먼저 해당 Blob의 스냅샷을 삭제해야 합니다. 스냅샷을 개별적으로 삭제하거나 원본 Blob를 삭제할 때 모든 스냅샷을 삭제되도록 지정할 수 있습니다. 스냅샷이 있는 Blob을 삭제하려고 하면 오류가 발생합니다.

Blob 및 해당 스냅샷을 삭제하려면 다음 메서드 중 하나를 사용하고 DeleteSnapshotsOption 열거형을 포함합니다.

다음 코드 예제에서는 .NET에서 Blob 및 해당 스냅샷을 삭제하는 방법을 보여 줍니다. 여기서, blobClientBlobClient 유형의 개체입니다.

await blobClient.DeleteIfExistsAsync(DeleteSnapshotsOption.IncludeSnapshots, null, default);

기본 Blob을 통해 Blob 스냅샷 복사

기본 Blob이 온라인 계층(핫 또는 쿨)에 있는 한, 복사 작업을 수행하여 기본 Blob을 통해 스냅샷을 승격할 수 있습니다. 스냅샷은 그대로 유지되지만 읽고 쓸 수 있는 복사본으로 대상을 덮어씁니다.

다음 코드 예제에서는 기본 Blob을 통해 Blob 스냅샷 복사하는 방법을 보여 줍니다.

public static async Task<BlockBlobClient> CopySnapshotOverBaseBlobAsync(
    BlockBlobClient client,
    string snapshotTimestamp)
{
    // Instantiate BlockBlobClient with identical URI and add snapshot timestamp
    BlockBlobClient snapshotClient = client.WithSnapshot(snapshotTimestamp);

    // Restore the specified snapshot by copying it over the base blob
    await client.SyncUploadFromUriAsync(snapshotClient.Uri, overwrite: true);

    // Return the client object after the copy operation
    return client;
}

리소스

.NET용 Azure Blob Storage 클라이언트 라이브러리를 사용하여 Blob 스냅샷을 관리하는 방법에 대한 자세한 내용은 다음 리소스를 참조하세요.

사용되지 않는 .NET 버전 11.x SDK를 사용하는 관련 코드 샘플은 .NET 버전 11.x를 사용하는 샘플 코드를 참조하세요.

클라이언트 라이브러리 리소스

참고 항목