Query for a Blob Storage endpoint using the Azure Storage management library
Article
A Blob Storage endpoint forms the base address for all objects within a storage account.
When your application creates a service client object that connects to Blob Storage data resources, you pass a URI referencing the endpoint to the service client constructor. You can construct the URI string manually, or you can query for the service endpoint at runtime using the Azure Storage management library.
Important
When referencing a service endpoint in a client application, it's recommended that you avoid taking a dependency on a cached IP address. The storage account IP address is subject to change, and relying on a cached IP address may result in unexpected behavior.
Additionally, it's recommended that you honor the time-to-live (TTL) of the DNS record and avoid overriding it. Overriding the DNS TTL may result in unexpected behavior.
The Azure Storage management library provides programmatic access to the Azure Storage resource provider. The resource provider is the Azure Storage implementation of the Azure Resource Manager. The management library enables developers to manage storage accounts and account configuration, as well as configure lifecycle management policies, object replication policies, and immutability policies.
In this article, you learn how to query a Blob Storage endpoint using the Azure Storage management library. Then you use that endpoint to create a BlobServiceClient object to connect with Blob Storage data resources.
Set up your project
To work with the code examples in this article, follow these steps to set up your project.
Install packages
Install packages to work with the libraries used in this example.
Add azure-sdk-bom to take a dependency on the latest version of the library. In the following snippet, replace the {bom_version_to_target} placeholder with the version number. Using azure-sdk-bom keeps you from having to specify the version of each individual dependency. To learn more about the BOM, see the Azure SDK BOM README.
Then add the following dependency elements to the group of dependencies. The azure-identity dependency is needed for passwordless connections to Azure services.
Add the necessary using or import directives to the code. Note that the code examples may split out functionality between files, but in this section all directives are listed together.
using Azure.Core;
using Azure.Identity;
using Azure.Storage.Blobs;
using Azure.ResourceManager;
using Azure.ResourceManager.Resources;
using Azure.ResourceManager.Storage;
Client library information:
Azure.Identity: Provides Microsoft Entra token authentication support across the Azure SDK, and is needed for passwordless connections to Azure services.
Azure.ResourceManager.Storage: Supports management of Azure Storage resources, including resource groups and storage accounts.
Azure.Storage.Blobs: Contains the primary classes that you can use to work with Blob Storage data resources.
com.azure.identity: Provides Microsoft Entra token authentication support across the Azure SDK, and is needed for passwordless connections to Azure services.
com.azure.storage.blob: Contains the primary classes that you can use to work with Blob Storage data resources.
@azure/identity: Provides Microsoft Entra token authentication support across the Azure SDK, and is needed for passwordless connections to Azure services.
@azure/storage-blob: Contains the primary classes that you can use to work with Blob Storage data resources.
@azure/arm-resources: Supports management of Azure resources and resource groups.
@azure/arm-storage: Supports management of Azure Storage resources, including resource groups and storage accounts.
Add the following import statements:
from azure.identity import DefaultAzureCredential
from azure.storage.blob import BlobServiceClient
from azure.mgmt.resource import ResourceManagementClient
from azure.mgmt.storage import StorageManagementClient
Client library information:
azure-identity: Provides Microsoft Entra token authentication support across the Azure SDK, and is needed for passwordless connections to Azure services.
azure-storage-blob: Contains the primary classes that you can use to work with Blob Storage data resources.
azure-mgmt-resource: Supports management of Azure resources and resource groups.
azure-mgmt-storage: Supports management of Azure Storage resources, including resource groups and storage accounts.
Register the Storage resource provider with a subscription
A resource provider must be registered with your Azure subscription before you can work with it. This step only needs to be done once per subscription, and only applies if the resource provider Microsoft.Storage is not currently registered with your subscription.
You can also use the Azure management libraries to check the registration status and register the Storage resource provider, as shown in the following examples:
public static async Task RegisterSRPInSubscription(SubscriptionResource subscription)
{
ResourceProviderResource resourceProvider =
await subscription.GetResourceProviderAsync("Microsoft.Storage");
// Check the registration state of the resource provider and register, if needed
if (resourceProvider.Data.RegistrationState == "NotRegistered")
resourceProvider.Register();
}
public void RegisterSRPInSubscription(AzureResourceManager armClient) {
// Check the registration state of the resource provider and register, if needed
if (armClient.providers().getByName("Microsoft.Storage").registrationState() == "NotRegistered")
armClient.providers().register("Microsoft.Storage");
}
async function registerSRPInSubscription(resourceMgmtClient /*: ResourceManagementClient*/) {
// Check the registration state of the resource provider and register, if needed
if (resourceMgmtClient.providers.get("Microsoft.Storage").registrationState == "NotRegistered")
resourceMgmtClient.providers.register("Microsoft.Storage");
}
def register_srp_in_subscription(self, resource_mgmt_client: ResourceManagementClient):
if (resource_mgmt_client.providers.get("Microsoft.Storage").registration_state == "NotRegistered"):
resource_mgmt_client.providers.register("Microsoft.Storage")
Note
To perform the register operation, you'll need permissions for the following Azure RBAC action: Microsoft.Storage/register/action. This permission is included in the Contributor and Owner roles.
Query for the Blob Storage endpoint
To retrieve the Blob Storage endpoint for a given storage account, we need to get the storage account properties by calling the Get Properties operation. The following code samples use both the data access and management libraries to get a Blob Storage endpoint for a specified storage account:
This method returns a StorageAccountResource object, which represents the storage account.
public static async Task<Uri> GetBlobServiceEndpoint(
string storageAccountName,
TokenCredential credential)
{
// TODO: replace with your subscription ID and resource group name
// You can locate your subscription ID on the Subscriptions blade
// of the Azure portal (https://portal.azure.cn)
const string subscriptionId = "<subscription-id>";
const string rgName = "<resource-group-name>";
ArmClient armClient = new(credential, subscriptionId, new ArmClientOptions { Environment = ArmEnvironment.AzureChina });
// Create a resource identifier, then get the subscription resource
ResourceIdentifier resourceIdentifier = new($"/subscriptions/{subscriptionId}");
SubscriptionResource subscription = armClient.GetSubscriptionResource(resourceIdentifier);
// Get a resource group
ResourceGroupResource resourceGroup = await subscription.GetResourceGroupAsync(rgName);
// Get a collection of storage account resources
StorageAccountCollection accountCollection = resourceGroup.GetStorageAccounts();
// Get the properties for the specified storage account
StorageAccountResource storageAccount = await accountCollection.GetAsync(storageAccountName);
// Return the primary endpoint for the blob service
return storageAccount.Data.PrimaryEndpoints.BlobUri;
}
To get the properties for a specified storage account, use the following method from an AzureResourceManager object:
This method returns a StorageAccount object, which represents the storage account.
def get_blob_service_endpoint(self, storage_account_name, credential: DefaultAzureCredential) -> str:
subscription_id = "<subscription-id>"
rg_name = "<resource-group-name>"
storage_mgmt_client = StorageManagementClient(
credential=credential,
subscription_id=subscription_id,
base_url="https://management.chinacloudapi.cn"
)
# Get the properties for the specified storage account
storage_account = storage_mgmt_client.storage_accounts.get_properties(
resource_group_name=rg_name,
account_name=storage_account_name
)
# Get blob service endpoint
endpoint = storage_account.primary_endpoints.blob
return endpoint
Create a client object using the endpoint
Once you have the Blob Storage endpoint for a storage account, you can instantiate a client object to work with data resources. The following code sample creates a BlobServiceClient object using the endpoint we retrieved in the earlier example:
// Create an instance of DefaultAzureCredential for authorization
TokenCredential credential = new DefaultAzureCredential();
// TODO: replace with your storage account name
string storageAccountName = "<storage-account-name>";
// Call out to our function that retrieves the blob service endpoint for the given storage account
Uri blobURI = await AccountProperties.GetBlobServiceEndpoint(storageAccountName, credential);
Console.WriteLine($"URI: {blobURI}");
// Now that we know the endpoint, create the client object
BlobServiceClient blobServiceClient = new(blobURI, credential);
// Do something with the storage account or its resources ...
String saName = "<storage-account-name>";
DefaultAzureCredential credential = new DefaultAzureCredentialBuilder().build();
AccountProperties accountProps = new AccountProperties();
String blobEndpoint = accountProps.GetBlobServiceEndpoint(saName, credential);
System.out.printf("URI: %s", blobEndpoint);
BlobServiceClient blobServiceClient = new BlobServiceClientBuilder()
.endpoint(blobEndpoint)
.credential(credential)
.buildClient();
// Do something with the storage account or its resources ...
// For client-side applications running in the browser, use InteractiveBrowserCredential instead of DefaultAzureCredential.
// See https://aka.ms/azsdk/js/identity/examples for more details.
const saName = "<storage-account-name>";
const credential = new DefaultAzureCredential();
// Call out to our function that retrieves the blob service endpoint for a storage account
const endpoint = await getBlobServiceEndpoint(saName, credential)
console.log(endpoint);
// Now that we know the endpoint, create the client object
const blobServiceClient = new BlobServiceClient(
endpoint,
credential);
// Do something with the storage account or its resources ...
storage_account_name = "<storage-account-name>"
credential = DefaultAzureCredential()
sample = BlobEndpointSample()
# Call out to our function that retrieves the blob service endpoint for a storage account
endpoint = sample.get_blob_service_endpoint(storage_account_name, credential)
print(f"URL: {endpoint}")
# Now that we know the endpoint, create the client object
blob_service_client = BlobServiceClient(account_url=endpoint, credential=credential)
# Do something with the storage account or its resources ...