将函数定义作为 CI 流程的一部分导入 API 管理

Ben*_*Ben 6 c# azure azure-devops azure-functions apim

我们希望在每次部署 azure 函数时自动化将函数定义导入 CD 流程的过程。在 azure 门户中,有一种非常简单的方法可以通过 UI 导入函数定义,但它们似乎没有任何 api/cli/powershell 库来自动化此过程。

Azure Portal Function 应用导入

我们已经成功创建了一个解决方法,其中涉及使用 C# OpenApi 库使我们的函数应用程序定义保持最新,然后使用az apim importcli 命令作为部署管道的一部分,但感觉需要额外的工作来保持 OpenApi 定义的最新和准确我们函数的每个端点,当您导入函数应用程序时,最好自动化门户在后台执行的操作(这不需要在源代码中保持最新的 openapi 定义)。任何帮助将不胜感激。

我们正在使用 Azure DevOps 进行 CI/CD 管道和发布。

Cha*_*ase 1

为此,您有几种选择。您没有指定您是否已经拥有一些现有的基础设施 CI 工具,但我最熟悉在 terraform 中执行此操作。

有关如何将 terraform 设置到管道中的教程。

集成 terraform 后,您可以轻松地将 API 定义添加到 APIM 实例中。并将其链接到您的函数后端。

文章和其中的一些代码示例:

resource "azurerm_api_management_backend" "example" {
  name                = "example-backend"
  resource_group_name = data.azurerm_resource_group.example.name
  api_management_name = data.azurerm_api_management.example.name
  protocol            = "http"
  url                 = "https://${azurerm_function_app.example.name}.azurewebsites.net/api/"

  credentials {
    header = {
      "x-functions-key" = "${data.azurerm_function_app_host_keys.example.default_function_key}"
    }
  }
}

resource "azurerm_api_management_api" "example" {
  name                = "example-api"
  resource_group_name = data.azurerm_resource_group.example.name
  api_management_name = data.azurerm_api_management.example.name
  revision            = "1"
  display_name        = "Example API"
  path                = "example"
  protocols           = ["https"]

  import {
    content_format = "openapi"
    content_value  = file("${path.module}/FuncOpenAPI3.yml")
  }
}

resource "azurerm_api_management_api_policy" "example" {
  api_name            = azurerm_api_management_api.example.name
  api_management_name = azurerm_api_management_api.example.api_management_name
  resource_group_name = azurerm_api_management_api.example.resource_group_name

  xml_content = <<XML
<policies>
  <inbound>
    <base/>
    <set-backend-service backend-id="example-backend" />
  </inbound>
</policies>
XML
}
Run Code Online (Sandbox Code Playgroud)

现在,正如您在本文中看到的,它讨论了导入 OpenApi 文件来定义实际的 api。没有一个很好的方法可以自动执行此操作,但有一种方法可以使用 swagger 的内置 tofile 工具:

<Target Name="PostBuild" AfterTargets="PostBuildEvent">
    <Exec Command="dotnet tool restore" />
    <Exec Command="dotnet swagger tofile --output swagger.json $(OutputPath)\$(AssemblyName).dll v1 " />
</Target>
Run Code Online (Sandbox Code Playgroud)

当您在管道中运行构建时,将生成此文件,然后您可以在基础设施阶段引用它,以使用该 OpenAPI 文件在 APIM 中自动生成该 API。