如何配置 CosmosDB 以使用托管身份触发 typeScript Azure 函数?

问题描述 投票:0回答:1

我成功配置了 TypeScript Azure 函数“functionInsertDataInCosmosDb”,以在本地开发环境中使用托管标识将消息写入 CosmosDB。

这是我的

local.settings.json

{
  "IsEncrypted": false,
  "Values": {
    "AZUREWEBJOBSSTORAGE": "XXXXXXXXX",
    "FUNCTIONS_WORKER_RUNTIME": "node",
    "COSMOS_DB_ENDPOINT": "https://test-dev-store-emails.documents.azure.com:443/",
    "COSMOS_DB_DATABASE": "cosmosdb--test-database",
    "cosmosdb__accountEndpoint": "https://test-dev-store-emails.documents.azure.com:443/"
  }
}

现在,我正在配置另一个名为“receiveMessageFromCosmosDb”的 TypeScript Azure 函数,以使用带有托管标识的 CosmosDB 触发器来处理消息。这是我的“receiveMessageFromCosmosDb”函数代码:

import { app, InvocationContext } from "@azure/functions";
export async function reciveMessageFromCosmosDb(
  documents: unknown[],
  context: InvocationContext
): Promise<void> {
  context.log(`Cosmos DB function processed ${documents} documents`);

}

app.cosmosDB('reciveMessageFromCosmosDb', {
  connection: 'cosmosdb__accountEndpoint',
  databaseName: 'COSMOS_DB_DATABASE',
  containerName: 'emails',
  createLeaseContainerIfNotExists: true,
  handler: reciveMessageFromCosmosDb
});

我已将所需的 RBAC 权限“Cosmos DB 内置数据贡献者”分配给我的 Function App。但是,当我调试函数时,“receiveMessageFromCosmosDb”中出现以下错误:

The 'reciveMessageFromCosmosDb' function is in error:
Microsoft.Azure.WebJobs.Host: Error indexing method 
'Functions.reciveMessageFromCosmosDb'. Microsoft.Azure.WebJobs.Extensions.CosmosDB: Cannot create container 
information for emails in database COSMOS_DB_DATABASE with lease leases in
 database COSMOS_DB_DATABASE : Cosmos DB connection configuration 
'cosmosdb__accountEndpoint' does not exist. Make sure that it is a defined App Setting. Microsoft.Azure.WebJobs.Extensions.CosmosDB: Cosmos DB 
connection configuration 'cosmosdb__accountEndpoint' does not exist. Make 
sure that it is a defined App Setting.

有人可以帮助我吗? 谢谢。

azure-functions azure-cosmosdb
1个回答
0
投票

请参阅评论中所述的Azure Function cosmosDB 触发器托管标识不起作用。这是同样的场景。

您的代码正在定义:

 connection: 'cosmosdb__accountEndpoint',

这是错误的,

connection
的值应该是同时包含accountEndpoint
credential
前缀
的值。

应该是:

 connection: 'cosmosdb',

您的设置文件:

{
  "IsEncrypted": false,
  "Values": {
    "AZUREWEBJOBSSTORAGE": "XXXXXXXXX",
    "FUNCTIONS_WORKER_RUNTIME": "node",
    "COSMOS_DB_DATABASE": "cosmosdb--test-database",
    "cosmosdb": {
      "accountEndpoint": "https://test-dev-store-emails.documents.azure.com:443/",
      <here you need to add the MSI properties>
    }
  }
}

本地运行时使用哪些 MSI 属性由您决定,但您可以参考 https://learn.microsoft.com/azure/azure-functions/functions-reference?tabs=cosmos&pivots=programming-language-csharp#具有基于身份的连接的本地开发

当将其部署到 Azure 时,应用程序设置 将使用

__
语法:

"cosmosdb__accountEndpoint": "https://test-dev-store-emails.documents.azure.com:443/"

"cosmosdb__credential": "managedidentity"

顺便说一句,代码也错误地使用了

COSMOS_DB_DATABASE
。如果您希望将值替换为配置值,则需要使用 Bindings Expression:

databaseName: '%COSMOS_DB_DATABASE%',
© www.soinside.com 2019 - 2024. All rights reserved.