Skip to content

Commit 7c9a1eb

Browse files
authored
Updates for keywords and simplify the scenario
Adding updates for keywords and for simplifying the scenario. (hand commit)
1 parent 4498857 commit 7c9a1eb

File tree

1 file changed

+52
-52
lines changed

1 file changed

+52
-52
lines changed
Lines changed: 52 additions & 52 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
---
22
title: How to use a system-assigned managed identity to access Azure Cosmos DB data.
3-
description: Learn how to configure an Azure AD system-assigned managed identity to access keys from Azure Cosmos DB.
3+
description: Learn how to configure an Azure AD system-assigned managed identity to access keys from Azure Cosmos DB. msi, managed service identity, aad, azure active directory, identity
44
author: j-patrick
55
ms.service: cosmos-db
66
ms.topic: conceptual
@@ -12,15 +12,13 @@ ms.reviewer: sngun
1212

1313
# How to use a system-assigned managed identity to access Azure Cosmos DB data.
1414

15-
In this article you will set up a **robust, key rotation agnostic,** solution to manage Azure Cosmos DB keys by leveraging [Managed Identities](../active-directory/managed-identities-azure-resources/services-support-managed-identities.md). The example in this article uses an Azure Function. However, you can achieve this solution by using any service that supports managed identities.
15+
In this article you will set up a **robust, key rotation agnostic,** solution to access Azure Cosmos DB keys by leveraging [managed identities](../active-directory/managed-identities-azure-resources/services-support-managed-identities.md). The example in this article uses an Azure Function. However, you can achieve this solution by using any service that supports managed identities.
1616

17-
You'll learn how to create an Azure Function that can access Azure Cosmos DB without copying a key.
17+
You'll learn how to create an Azure Function that can access Azure Cosmos DB without needing to copy any Azure Cosmos DB keys. The function will wake up every minute and record the current temperature of an aquarium fish tank. To learn how to set up a timer triggered Azure Function see the [Create a function in Azure that is triggered by a timer](../azure-functions/functions-create-scheduled-function.md) article.
1818

19-
You will build an Azure Function that handles summarizing the last hour of sales information. The Azure Function runs every hour, it reads a set of sale receipts from Azure Cosmos DB. Then the function will create an hourly summary of sales and store it back in the Azure Cosmos container. To simplify the scenario, the processed receipts are deleted by a configured [Time To Live](./time-to-live.md) setting.
19+
To simplify the scenario, cleanup of older temperature documents is handled by an already configured [Time To Live](./time-to-live.md) setting.
2020

21-
Setting up a timer triggered Azure Function is outlined in [Create a function in Azure that is triggered by a timer](../azure-functions/functions-create-scheduled-function.md) article.
22-
23-
## Assign a system-assigned Managed Identity to an Azure Function
21+
## Assign a system-assigned managed identity to an Azure Function
2422

2523
In this step, you'll assign a system-assigned managed identity to your Azure Function.
2624

@@ -45,9 +43,9 @@ In this step, you'll assign a role to the Azure Function's system-assigned manag
4543
> RBAC support in Azure Cosmos DB is applicable to control plane operations only. Data plane operations are secured using master keys or resource tokens. To learn more, see the [Secure access to data](secure-access-to-data.md) article.
4644
4745
> [!TIP]
48-
> When assigning roles, only assign the needed access. If your service only requires reading data, then assign the Managed Identity to **Cosmos DB Account Reader** role. For more information about the importance of least privilege access, see the [lower exposure of privileged accounts](../security/fundamentals/identity-management-best-practices.md#lower-exposure-of-privileged-accounts) article.
46+
> When assigning roles, only assign the needed access. If your service only requires reading data, then assign the managed identity to **Cosmos DB Account Reader** role. For more information about the importance of least privilege access, see the [lower exposure of privileged accounts](../security/fundamentals/identity-management-best-practices.md#lower-exposure-of-privileged-accounts) article.
4947
50-
For your scenario, you will read the sale receipt documents, summarize them, and then write back that summary to a container in Azure Cosmos DB. Because you have to write the data, you will use the **DocumentDB Account Contributor** role.
48+
For your scenario, you will read the temperature, then write back that data to a container in Azure Cosmos DB. Because you have to write the data, you will use the **DocumentDB Account Contributor** role.
5149

5250
1. Sign in to the Azure portal and navigate to your Azure Cosmos account. Open the **Access Management (IAM) Pane**, and then the **Role Assignments** tab:
5351
![IAM Pane](./media/managed-identity-based-authentication/cosmos-db-iam-tab.png)
@@ -64,11 +62,11 @@ For your scenario, you will read the sale receipt documents, summarize them, and
6462

6563
![Select Assignment](./media/managed-identity-based-authentication/cosmos-db-iam-tab-add-role-pane-filled.png)
6664

67-
1. Select the function app and click **Save**.
65+
1. After the function app's identity is selected click **Save**.
6866

6967
## Programmatically access the Azure Cosmos DB keys from the Azure Function
7068

71-
Now we have a function app that has a system-assigned managed identity. That identity is given the **DocumentDB Account Contributor** role in the Azure Cosmos DB permissions. The following function app code will get the Azure Cosmos DB keys, create a CosmosClient object, and run the business logic to summarize the sales receipt.
69+
Now we have a function app that has a system-assigned managed identity. That identity is given the **DocumentDB Account Contributor** role in the Azure Cosmos DB permissions. The following function app code will get the Azure Cosmos DB keys, create a CosmosClient object, get the temperature, then save this to Cosmos DB.
7270

7371
This sample uses the [List Keys API](https://docs.microsoft.com/rest/api/cosmos-db-resource-provider/DatabaseAccounts/ListKeys) to access your Azure Cosmos account keys.
7472

@@ -89,12 +87,26 @@ namespace SummarizationService
8987
}
9088
```
9189

92-
You will use the [Microsoft.Azure.Services.AppAuthentication](https://www.nuget.org/packages/Microsoft.Azure.Services.AppAuthentication) library to get the system-assigned Managed Identity token. To learn other ways to get the token and more information about the `Microsoft.Azure.Service.AppAuthentication` library, see the [Service To Service Authentication](../key-vault/service-to-service-authentication.md) article.
90+
The example also uses a simple document called "TemperatureRecord", which is defined as follows:
91+
```csharp
92+
using System;
9393

94+
namespace Monitor
95+
{
96+
public class TemperatureRecord
97+
{
98+
public string id { get; set; } = Guid.NewGuid().ToString();
99+
public DateTime RecordTime { get; set; }
100+
public int Temperature { get; set; }
101+
102+
}
103+
}
104+
```
105+
106+
You will use the [Microsoft.Azure.Services.AppAuthentication](https://www.nuget.org/packages/Microsoft.Azure.Services.AppAuthentication) library to get the system-assigned managed identity token. To learn other ways to get the token and more information about the `Microsoft.Azure.Service.AppAuthentication` library, see the [Service To Service Authentication](../key-vault/service-to-service-authentication.md) article.
94107

95108
```csharp
96109
using System;
97-
using System.Collections.Generic;
98110
using System.Net.Http;
99111
using System.Net.Http.Headers;
100112
using System.Threading.Tasks;
@@ -103,49 +115,47 @@ using Microsoft.Azure.Services.AppAuthentication;
103115
using Microsoft.Azure.WebJobs;
104116
using Microsoft.Extensions.Logging;
105117

106-
namespace SummarizationService
118+
namespace Monitor
107119
{
108-
public static class SummarizationFunction
120+
public static class TemperatureMonitor
109121
{
110-
private static string subscriptionId =
122+
private static string subscriptionId =
111123
"<azure subscription id>";
112-
private static string resourceGroupName = "
113-
<name of your azure resource group>";
114-
private static string accountName =
124+
private static string resourceGroupName =
125+
"<name of your azure resource group>";
126+
private static string accountName =
115127
"<Azure Cosmos DB account name>";
116-
private static string cosmosDbEndpoint =
128+
private static string cosmosDbEndpoint =
117129
"<Azure Cosmos DB endpoint>";
118-
private static string databaseName =
130+
private static string databaseName =
119131
"<Azure Cosmos DB name>";
120132
private static string containerName =
121-
"<container where the sales receipts are>";
122-
private static string indexToQuery =
123-
"<index to query for the sale receipts>";
133+
"<container to store the temperature in>";
124134

125-
[FunctionName("SummarizationService")]
126-
public static async Task Run([TimerTrigger("0 5 * * * *")]TimerInfo myTimer, ILogger log)
135+
[FunctionName("TemperatureMonitor")]
136+
public static async Task Run([TimerTrigger("0 * * * * *")]TimerInfo myTimer, ILogger log)
127137
{
128-
log.LogInformation($"Starting receipt processing: {DateTime.Now}");
138+
log.LogInformation($"Starting temperature monitoring: {DateTime.Now}");
129139

130140
// AzureServiceTokenProvider will help us to get the Service Managed token.
131141
var azureServiceTokenProvider = new AzureServiceTokenProvider();
132142

133143
// In order to get the Service Managed token we need to authenticate to the Azure Resource Manager.
134144
string accessToken = await azureServiceTokenProvider.GetAccessTokenAsync("https://management.azure.com/");
135-
145+
136146
// To get the Azure Cosmos DB keys setup the List Keys API:
137147
string endpoint = $"https://management.azure.com/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/listKeys?api-version=2019-12-12";
138-
148+
139149
// setup an HTTP Client and add the access token.
140150
HttpClient httpClient = new HttpClient();
141151
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
142-
152+
143153
// Post to the endpoint to get the keys result.
144154
var result = await httpClient.PostAsync(endpoint, new StringContent(""));
145155

146156
// Get the Result back as a DatabaseAccountListKeysResult.
147157
DatabaseAccountListKeysResult keys = await result.Content.ReadAsAsync<DatabaseAccountListKeysResult>();
148-
158+
149159
log.LogInformation("Starting to create the client");
150160

151161
CosmosClient client = new CosmosClient(cosmosDbEndpoint, keys.primaryMasterKey);
@@ -154,32 +164,23 @@ namespace SummarizationService
154164

155165
var database = client.GetDatabase(databaseName);
156166
var container = database.GetContainer(containerName);
157-
158-
// get all the receipts that are for "sales"
159-
QueryDefinition query = new QueryDefinition($"SELECT * FROM {containerName} f WHERE f.type = @type")
160-
.WithParameter("@type", "sales");
161167

162-
SummarySalesReceipt summarySales = new SummarySalesReceipt();
168+
log.LogInformation("Get the temperature.");
163169

164-
FeedIterator<SalesReceipt> resultSetIterator =
165-
container.GetItemQueryIterator<SalesReceipt>(query,
166-
requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey(indexToQuery) });
170+
var tempRecord = new TemperatureRecord() { RecordTime = DateTime.UtcNow, Temperature = GetTemperature() };
167171

168-
while (resultSetIterator.HasMoreResults)
169-
{
170-
// Get all the sales receipts
171-
FeedResponse<SalesReceipt> response = await resultSetIterator.ReadNextAsync();
172+
log.LogInformation("Store temperature");
172173

173-
// ... summarization logic for sales receipts.
174-
// The summary is then added to the summarySales document.
175-
// Note: another function will handle cleanup ...
174+
await container.CreateItemAsync<TemperatureRecord>(tempRecord);
176175

177-
}
176+
log.LogInformation($"Ending temperature monitor: {DateTime.Now}");
177+
}
178178

179-
log.LogInformation("Finished the summarization");
180-
await container.CreateItemAsync<SummarySalesReceipt>(summarySales);
181-
182-
log.LogInformation($"Ending receipt processing: {DateTime.Now}");
179+
private static int GetTemperature()
180+
{
181+
// fake the temperature sensor for this demo
182+
Random r = new Random(DateTime.UtcNow.Second);
183+
return r.Next(0, 120);
183184
}
184185
}
185186
}
@@ -190,5 +191,4 @@ You are now ready to [deploy your Azure Function.](../azure-functions/functions-
190191

191192
* [Certificate-based authentication with Azure Cosmos DB and Active Directory](certificate-based-authentication.md)
192193
* [Secure Azure Cosmos keys using Azure Key Vault](access-secrets-from-keyvault.md)
193-
194194
* [Security baseline for Azure Cosmos DB](security-baseline.md)

0 commit comments

Comments
 (0)