教程:使用 HTTP 触发的 Azure 函数创建容器组Tutorial: Use an HTTP-triggered Azure function to create a container group

Azure Functions 是一项无服务器计算服务,它可以运行脚本或代码来响应各种事件,例如 HTTP 请求、计时器或 Azure 存储队列中的消息。Azure Functions is a serverless compute service that can run scripts or code in response to a variety of events, such as an HTTP request, a timer, or a message in an Azure Storage queue.

在本教程中,我们将创建一个 Azure 函数,该函数接受 HTTP 请求并触发对容器组的部署。In this tutorial, you create an Azure function that takes an HTTP request and triggers deployment of a container group. 此示例演示通过 Azure Functions 在 Azure 容器实例中自动创建资源的基本步骤。This example shows the basics of using Azure Functions to automatically create resources in Azure Container Instances. 对于更复杂的方案或其他事件触发器,请修改或扩展此示例。Modify or extend the example for more complex scenarios or other event triggers.

你将学习如何执行以下操作:You learn how to:

  • 将 Visual Studio Code 与 Azure Functions 扩展配合使用,创建基本的 HTTP 触发的 PowerShell 函数。Use Visual Studio Code with the Azure Functions extension to create a basic HTTP-triggered PowerShell function.
  • 在函数应用中启用一个标识,并为其授予创建 Azure 资源的权限。Enable an identity in the function app and give it permissions to create Azure resources.
  • 修改并重新发布用于自动部署单容器容器组的 PowerShell 函数。Modify and republish the PowerShell function to automate deployment of a single-container container group.
  • 验证对容器进行的 HTTP 触发的部署。Verify the HTTP-triggered deployment of the container.

重要

适用于 Azure Functions 的 PowerShell 当前为预览版。PowerShell for Azure Functions is currently in preview. 需同意补充使用条款才可使用预览版。Previews are made available to you on the condition that you agree to the supplemental terms of use. 在正式版 (GA) 推出之前,此功能的某些方面可能会有所更改。Some aspects of this feature may change prior to general availability (GA).

先决条件Prerequisites

请参阅在 Azure 中创建第一个函数,了解在 OS 上安装 Visual Studio Code 并将其与 Azure Functions 配合使用的先决条件。See Create your first function in Azure for prerequisites to install and use Visual Studio Code with the Azure Functions on your OS.

本文中的一些步骤使用 Azure CLI。Some steps in this article use the Azure CLI. 可以使用本地安装的 Azure CLI 来完成这些步骤。You can use the local installation of the Azure CLI to complete these steps. 如果需要进行安装或升级,请参阅安装 Azure CLIIf you need to install or upgrade, see Install Azure CLI.

创建基本的 PowerShell 函数Create a basic PowerShell function

请按在 Azure 中创建第一个 PowerShell 函数中的步骤操作,使用“HTTP 触发器”模板创建 PowerShell 函数。Follow steps in Create your first PowerShell function in Azure to create a PowerShell function using the HTTP Trigger template. 使用默认的 Azure 函数名称 HttpTriggerUse the default Azure function name HttpTrigger. 按快速入门中的演示操作,在本地测试函数,并将项目发布到 Azure 中的函数应用。As shown in the quickstart, test the function locally, and publish the project to a function app in Azure. 此示例是一个基本的 HTTP 触发的函数,返回文本字符串。This example is a basic HTTP-triggered function that returns a text string. 在本文后面的步骤中,我们通过修改该函数来创建容器组。In later steps in this article, you modify the function to create a container group.

本文假定你在一个 Azure 资源组中使用名称 myfunctionapp 发布项目,该资源组自动根据函数应用名称(也是 myfunctionapp)命名。This article assumes you publish the project using the name myfunctionapp, in an Azure resource group automatically named according to the function app name (also myfunctionapp). 请在后面的步骤中将上述名称替换为自己的唯一函数应用名称和资源组名称。Substitute your unique function app name and resource group name in later steps.

在函数应用中启用 Azure 托管标识Enable an Azure-managed identity in the function app

现在,在函数应用中启用系统分配的托管标识Now enable a system-assigned managed identity in your function app. 运行此应用的 PowerShell 主机可以使用此标识自动进行身份验证,使函数能够在标识有权访问的 Azure 服务上执行操作。The PowerShell host running the app can automatically authenticate using this identity, enabling functions to take actions on Azure services to which the identity has been granted access. 在本教程中,我们授予托管标识在函数应用的资源组中创建资源的权限。In this tutorial, you grant the managed identity permissions to create resources in the function app's resource group.

首先使用 az group show 命令获取函数应用的资源组的 ID 并将其存储在环境变量中。First use the az group show command to get the ID of the function app's resource group and store it in an environment variable. 以下示例假定你在 Bash shell 中运行该命令。This example assumes you run the command in a Bash shell.

rgID=$(az group show --name myfunctionapp --query id --output tsv)

运行 az functionapp identity app assign,为函数应用分配本地标识,为资源组分配参与者角色。Run az functionapp identity app assign to assign a local identity to the function app and assign a contributor role to the resource group. 此角色允许标识在资源组中创建其他资源,例如容器组。This role allows the identity to create additional resources such as container groups in the resource group.

az functionapp identity assign \
  --name myfunctionapp \
  --resource-group myfunctionapp \
  --role contributor --scope $rgID

修改 HttpTrigger 函数Modify HttpTrigger function

可以通过修改 HttpTrigger 函数的 PowerShell 代码来创建容器组。Modify the PowerShell code for the HttpTrigger function to create a container group. 在函数的 run.ps1 文件中,找到以下代码块。In file run.ps1 for the function, find the following code block. 此代码显示名称值(如果在函数 URL 中以查询字符串的形式传递了一个名称值):This code displays a name value, if one is passed as a query string in the function URL:

[...]
if ($name) {
    $status = [HttpStatusCode]::OK
    $body = "Hello $name"
}
[...]

请将该代码替换为以下示例块。Replace this code with the following example block. 在这里,如果在查询字符串中传递了某个名称值,则会通过 New-AzContainerGroup cmdlet 使用该值来命名并创建容器组。Here, if a name value is passed in the query string, it is used to name and create a container group using the New-AzContainerGroup cmdlet. 请确保将资源组名称 myfunctionapp 替换为函数应用的资源组的名称:Make sure to replace the resource group name myfunctionapp with the name of the resource group for your function app:

[...]
if ($name) {
    $status = [HttpStatusCode]::OK
    New-AzContainerGroup -ResourceGroupName myfunctionapp -Name $name `
        -Image alpine -OsType Linux `
        -Command "echo 'Hello from an Azure container instance triggered by an Azure function'" `
        -RestartPolicy Never
    $body = "Started container group $name"
}
[...]

此示例创建一个容器组,该容器组包含的单个容器实例运行 alpine 映像。This example creates a container group consisting of a single container instance running the alpine image. 该容器运行单个 echo 命令,然后终止。The container runs a single echo command and then terminates. 在实际示例中,我们可能会触发创建操作,创建一个或多个用于运行批处理作业的容器组。In a real-world example, you might trigger creation of one or more container groups for running a batch job.

在本地测试函数应用Test function app locally

请确保函数在本地正常运行,然后再将函数应用项目重新发布到 Azure。Ensure that the function runs properly locally before republishing the function app project to Azure. PowerShell 快速入门所示,请在 PowerShell 脚本中插入一个本地断点,然后在其上插入 Wait-Debugger 调用。As shown in the PowerShell quickstart, insert a local breakpoint in the PowerShell script and a Wait-Debugger call above it.

重新发布 Azure 函数应用Republish Azure function app

验证该函数可以在本地计算机上正确运行以后,即可将项目重新发布到 Azure 中的现有函数应用。After you've verified that the function runs correctly on your local computer, it's time to republish the project to the existing function app in Azure.

备注

将函数发布到 Azure 之前,请记得删除对 Wait-Debugger 的所有调用。Remember to remove any calls to Wait-Debugger before you publish your functions to Azure.

  1. 在 Visual Studio Code 中打开命令面板。In Visual Studio Code, open the Command Palette. 搜索并选择 Azure Functions: Deploy to function app...Search for and select Azure Functions: Deploy to function app....
  2. 选择当前的用于压缩和部署的工作文件夹。Select the current working folder to zip and deploy.
  3. 选择订阅,然后选择现有函数应用的名称 (myfunctionapp)。Select the subscription and then the name of the existing function app (myfunctionapp). 确认要覆盖以前的部署。Confirm that you want to overwrite the previous deployment.

创建函数应用并应用了部署包之后,会显示一个通知。A notification is displayed after your function app is created and the deployment package is applied. 在此通知中选择“查看输出” 以查看创建和部署结果,其中包括已更新的 Azure 资源。Select View Output in this notification to view the creation and deployment results, including the Azure resources that you updated.

在 Azure 中运行函数Run the function in Azure

部署成功完成以后,请获取函数 URL。After the deployment completes successfully, get the function URL. 例如,使用 Visual Studio Code 中的“Azure: Functions”区域复制 HttpTrigger 函数 URL,或者在 Azure 门户中获取函数 URL。For example, use the Azure: Functions area in Visual Studio code to copy the HttpTrigger function URL, or get the function URL in the Azure portal.

函数 URL 包含唯一代码,采用以下形式:The function URL includes a unique code and is of the form:

https://myfunctionapp.chinacloudsites.cn/api/HttpTrigger?code=bmF/GljyfFWISqO0GngDPCtCQF4meRcBiHEoaQGeRv/Srx6dRcrk2M==

在不传递名称的情况下运行函数Run function without passing a name

首次测试时,请运行 curl 命令,传递没有追加 name 查询字符串的函数 URL。As a first test, run the curl command and pass the function URL without appending a name query string. 请确保包括函数的唯一代码。Make sure to include your function's unique code.

curl --verbose "https://myfunctionapp.chinacloudsites.cn/api/HttpTrigger?code=bmF/GljyfFWISqO0GngDPCtCQF4meRcBiHEoaQGeRv/Srx6dRcrk2M=="

此函数返回状态代码 400 和文本“Please pass a name on the query string or in the request body”:The function returns status code 400 and the text Please pass a name on the query string or in the request body:

[...]
> GET /api/HttpTrigger?code=bmF/GljyfFWISqO0GngDPCtCQF4meRcBiHEoaQGeRv/Srx6dRcrk2M== HTTP/2
> Host: myfunctionapp.chinacloudsites.cn
> User-Agent: curl/7.54.0
> Accept: */*
> 
* Connection state changed (MAX_CONCURRENT_STREAMS updated)!
< HTTP/2 400 
< content-length: 62
< content-type: text/plain; charset=utf-8
< date: Mon, 05 Aug 2019 22:08:15 GMT
< 
* Connection #0 to host myfunctionapp.chinacloudsites.cn left intact
Please pass a name on the query string or in the request body.

运行函数并传递容器组的名称Run function and pass the name of a container group

现在请运行 curl 命令,方法是:将容器组的名称 (mycontainergroup) 以查询字符串 &name=mycontainergroup 的形式追加:Now run the curl command by appending the name of a container group (mycontainergroup) as a query string &name=mycontainergroup:

curl --verbose "https://myfunctionapp.chinacloudsites.cn/api/HttpTrigger?code=bmF/GljyfFWISqO0GngDPCtCQF4meRcBiHEoaQGeRv/Srx6dRcrk2M==&name=mycontainergroup"

此函数返回状态代码 200 并触发一项创建容器组的操作:The function returns status code 200 and triggers the creation of the container group:

[...]
> GET /api/HttpTrigger?ode=bmF/GljyfFWISqO0GngDPCtCQF4meRcBiHEoaQGeRv/Srx6dRcrk2M==&name=mycontainergroup HTTP/2
> Host: myfunctionapp.chinacloudsites.cn
> User-Agent: curl/7.54.0
> Accept: */*
> 
* Connection state changed (MAX_CONCURRENT_STREAMS updated)!
< HTTP/2 200 
< content-length: 28
< content-type: text/plain; charset=utf-8
< date: Mon, 05 Aug 2019 22:15:30 GMT
< 
* Connection #0 to host myfunctionapp.chinacloudsites.cn left intact
Started container group mycontainergroup

使用 az container logs 命令验证容器是否已运行:Verify that the container ran with the az container logs command:

az container logs --resource-group myfunctionapp --name mycontainergroup

示例输出:Sample output:

Hello from an Azure container instance triggered by an Azure function

清理资源Clean up resources

如果不再需要在本教程中创建的任何资源,可以执行 az group delete 命令,删除资源组和其中包含的所有资源。If you no longer need any of the resources you created in this tutorial, you can execute the az group delete command to remove the resource group and all resources it contains. 此命令将删除创建的容器注册表、正在运行的容器和所有相关资源。This command deletes the container registry you created, as well as the running container, and all related resources.

az group delete --name myfunctionapp

后续步骤Next steps

在本教程中,我们创建了一个 Azure 函数,该函数接受 HTTP 请求并触发对容器组的部署。In this tutorial, you created an Azure function that takes an HTTP request and triggers deployment of a container group. 你已了解如何:You learned how to:

  • 将 Visual Studio Code 与 Azure Functions 扩展配合使用,创建基本的 HTTP 触发的 PowerShell 函数。Use Visual Studio Code with the Azure Functions extension to create a basic HTTP-triggered PowerShell function.
  • 在函数应用中启用一个标识,并为其授予创建 Azure 资源的权限。Enable an identity in the function app and give it permissions to create Azure resources.
  • 修改用于自动部署单容器容器组的 PowerShell 函数代码。Modify the PowerShell function code to automate deployment of a single-container container group.
  • 验证对容器进行的 HTTP 触发的部署。Verify the HTTP-triggered deployment of the container.

有关如何启动并监视容器化作业的详细示例,请参阅博客文章 Event-Driven Serverless Containers with PowerShell Azure Functions and Azure Container Instances(将事件驱动型无服务器容器与 PowerShell Azure Functions 和 Azure 容器实例配合使用)和随附的代码示例For a detailed example to launch and monitor a containerized job, see the blog post Event-Driven Serverless Containers with PowerShell Azure Functions and Azure Container Instances and accompanying code sample.

请参阅 Azure Functions 文档,获取有关如何创建 Azure Functions 和发布 Functions 项目的详细指南。See the Azure Functions documentation for detailed guidance on creating Azure functions and publishing a functions project.