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

标签 c# azure azure-devops azure-functions apim

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

Azure Portal Function app import

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

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

最佳答案

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

Tutorial on how to setup terraform into your pipeline.

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

Article and some code samples from it:

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
}

现在,正如您在本文中看到的,它讨论了导入 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>

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

关于c# - 将函数定义作为 CI 流程的一部分导入 API 管理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72830747/

相关文章:

c# - Unity3d 如何从另一个脚本引用滑动控件?

c# - 使用注释 block 更改实现抽象类模板

azure - 无法从逻辑应用程序查看Azure Functions

c# - Azure 云服务 - 部署错误

azure-devops - Az CLI : Cannot run pipeline with runtime parameters

.net - 5秒查看部署状态

json - 使用 Azure 发布管道在开发、阶段和生产槽上部署期间替换/更新 json 文件的值

c# - 将用户控件从类型名称转换为自定义控件类型?

c# - new String() 不在 C# 中创建新的引用对象?

html - 我可以在自定义的 Azure AD B2C 用户界面中使用 SVG 吗?