教程:使用 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.

先决条件Prerequisites

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

本文中的其他步骤使用 Azure PowerShell。Additional steps in this article use Azure PowerShell. 如果需要进行安装或升级,请参阅安装 Azure PowerShell登录到 AzureIf you need to install or upgrade, see Install Azure PowerShell and Sign into Azure.

创建基本的 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

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

向函数应用添加标识Add an identity to the function app:

Update-AzFunctionApp -Name myfunctionapp `
    -ResourceGroupName myfunctionapp `
    -IdentityType SystemAssigned

将参与者角色范围的标识分配给资源组:Assign the identity the contributor role scoped to the resource group:

$SP=(Get-AzADServicePrincipal -DisplayName myfunctionapp).Id
$RG=(Get-AzResourceGroup -Name myfunctionapp).ResourceId
New-AzRoleAssignment -ObjectId $SP -RoleDefinitionName "Contributor" -Scope $RG

修改 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) {
    $body = "Hello, $name. This HTTP triggered function executed successfully."
}
[...]

请将该代码替换为以下示例块。Replace this code with the following example block. 在这里,如果在查询字符串中传递了某个名称值,则会通过 New-AzContainerGroup cmdlet 使用该值来命名并创建容器组。Here, if a name value is passed in the query string, it's 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) {
    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
    if ($?) {
        $body = "This HTTP triggered function executed successfully. Started container group $name"
    }
    else  {
        $body = "There was a problem starting the container group."
    }
[...]

此示例创建一个容器组,该容器组包含的单个容器实例运行 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 locally before republishing the function app project to Azure. 在本地运行时,函数不会创建 Azure 资源。When run locally, the function doesn't create Azure resources. 但是,不管是否有没有在查询字符串中传递名称值,你都可以测试函数流。However, you can test the function flow with and without passing a name value in a query string. 若要调试函数,请参阅在本地调试 PowerShell Azure FunctionsTo debug the function, see Debug PowerShell Azure Functions locally.

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

验证该函数可以在本地运行以后,请将项目重新发布到 Azure 中的现有函数应用。After you've verified that the function runs locally, republish the project to the existing function app in 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 is of the form:

https://myfunctionapp.chinacloudsites.cn/api/HttpTrigger

在不传递名称的情况下运行函数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.

curl --verbose "https://myfunctionapp.chinacloudsites.cn/api/HttpTrigger"

此函数返回状态代码 200 和文本“This HTTP triggered function executed successfully. Pass a name in the query string or in the request body for a personalized response”:The function returns status code 200 and the text This HTTP triggered function executed successfully. Pass a name in the query string or in the request body for a personalized response:

[...]
> GET /api/HttpTrigger? HTTP/1.1
> Host: myfunctionapp.chinacloudsites.cn
> User-Agent: curl/7.64.1
> Accept: */*
> 
* Connection state changed (MAX_CONCURRENT_STREAMS updated)!
< HTTP/1.1 200 OK
< Content-Length: 135
< Content-Type: text/plain; charset=utf-8
< Request-Context: appId=cid-v1:d0bd0123-f713-4579-8990-bb368a229c38
< Date: Wed, 10 Jun 2020 17:50:27 GMT
< 
* Connection #0 to host myfunctionapp.chinacloudsites.cn left intact
This HTTP triggered function executed successfully. Pass a name in the query string or in the request body for a personalized response.* Closing connection 0

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

现在请运行 curl 命令,并将容器组的名称 (mycontainergroup) 以查询字符串 ?name=mycontainergroup 的形式进行追加:Now run the curl command and append the name of a container group (mycontainergroup) as a query string ?name=mycontainergroup:

curl --verbose "https://myfunctionapp.chinacloudsites.cn/api/HttpTrigger?name=mycontainergroup"

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

[...]
> GET /api/HttpTrigger1?name=mycontainergroup HTTP/1.1
> Host: myfunctionapp.chinacloudsites.cn
> User-Agent: curl/7.64.1
> Accept: */*
> 
< HTTP/1.1 200 OK
< Content-Length: 92
< Content-Type: text/plain; charset=utf-8
< Request-Context: appId=cid-v1:d0bd0123-f713-4579-8990-bb368a229c38
< Date: Wed, 10 Jun 2020 17:54:31 GMT
< 
* Connection #0 to host myfunctionapp.chinacloudsites.cn left intact
This HTTP triggered function executed successfully. Started container group mycontainergroup* Closing connection 0

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

Get-AzContainerInstanceLog -ResourceGroupName myfunctionapp `
  -ContainerGroupName mycontainergroup 

示例输出:Sample output:

Hello from an Azure container instance triggered by an Azure function

清理资源Clean up resources

如果不再需要在本教程中创建的任何资源,可以执行 [az group delete][az-group-delete] 命令,删除资源组和其中包含的所有资源。If you no longer need any of the resources you created in this tutorial, you can execute the [az group delete][az-group-delete] command to remove the resource group and all resources it contains. 此命令将删除创建的函数应用、正在运行的容器和所有相关资源。This command deletes the function app 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.