快速入门:从 Terraform 创建和部署 Azure Functions 资源

在本快速入门中,你将使用 Terraform 在 Azure Functions 中的 Flex Consumption 计划中创建函数应用,以及其他所需的 Azure 资源。 Flex Consumption 计划提供无服务器托管,使你可以按需运行代码,而无需显式预配或管理基础结构。 它用于处理数据、集成系统、物联网计算以及构建简单的 API 和微服务。 在此配置中创建的资源包括唯一资源组、存储帐户、Blob 存储容器、弹性消耗计划和函数应用本身。 函数应用在 Linux 上运行,并配置为将 Blob 存储用于代码部署。

使用 Terraform 可以定义、预览和部署云基础结构。 使用 Terraform 时,请使用 HCL 语法来创建配置文件。 利用 HCL 语法,可指定 Azure 这样的云提供程序和构成云基础结构的元素。 创建配置文件后,请创建一个执行计划,利用该计划,可在部署基础结构更改之前先预览这些更改。 验证了更改后,请应用该执行计划以部署基础结构。

  • 创建具有唯一名称的 Azure 资源组。
  • 生成一个 13 个小写字母的随机字符串来命名资源。
  • 在 Azure 中创建存储帐户。
  • 在存储帐户中创建 Blob 存储容器。
  • 在 Azure Functions 中创建 Flex 消耗计划。
  • 在 Azure 中使用 Flex Consumption 计划创建函数应用。
  • 输出资源组、存储帐户、服务计划、函数应用和 Azure Functions 弹性消耗计划的名称。

先决条件

实现 Terraform 代码

本文中的示例代码位于 Azure Terraform GitHub 存储库中。 你可以查看包含当前和以前 Terraform 版本的测试结果的日志文件。

  1. 创建用于测试和运行示例 Terraform 代码的目录,并将其设为当前目录。

  2. 创建名为 main.tf 的文件并插入以下代码:

# This Terraform configuration creates a Flex Consumption plan app in Azure Functions 
# with the required Storage account and Blob Storage deployment container.

# Create a random pet to generate a unique resource group name
resource "random_pet" "rg_name" {
  prefix = var.resource_group_name_prefix
}

# Create a resource group
resource "azurerm_resource_group" "example" {
  location = var.resource_group_location
  name     = random_pet.rg_name.id
}

# Random String for unique naming of resources
resource "random_string" "name" {
  length  = 8
  special = false
  upper   = false
  lower   = true
  numeric = false
}

# Create a storage account
resource "azurerm_storage_account" "example" {
  name                     = coalesce(var.sa_name, random_string.name.result)
  resource_group_name      = azurerm_resource_group.example.name
  location                 = azurerm_resource_group.example.location
  account_tier             = var.sa_account_tier
  account_replication_type = var.sa_account_replication_type
}

# Create a storage container
resource "azurerm_storage_container" "example" {
  name                  = "example-flexcontainer"
  storage_account_id    = azurerm_storage_account.example.id
  container_access_type = "private"
}

# Create a Log Analytics workspace for Application Insights
resource "azurerm_log_analytics_workspace" "example" {
  name                = coalesce(var.ws_name, random_string.name.result)
  location            = azurerm_resource_group.example.location
  resource_group_name = azurerm_resource_group.example.name
  sku                 = "PerGB2018"
  retention_in_days   = 30
}

# Create an Application Insights instance for monitoring
resource "azurerm_application_insights" "example" {
  name                = coalesce(var.ai_name, random_string.name.result)
  location            = azurerm_resource_group.example.location
  resource_group_name = azurerm_resource_group.example.name
  application_type    = "web"
  workspace_id = azurerm_log_analytics_workspace.example.id
}

# Create a service plan
resource "azurerm_service_plan" "example" {
  name                = coalesce(var.asp_name, random_string.name.result)
  resource_group_name = azurerm_resource_group.example.name
  location            = azurerm_resource_group.example.location
  sku_name            = "FC1"
  os_type             = "Linux"
}

# Create a function app
resource "azurerm_function_app_flex_consumption" "example" {
  name                = coalesce(var.fa_name, random_string.name.result)
  resource_group_name = azurerm_resource_group.example.name
  location            = azurerm_resource_group.example.location
  service_plan_id     = azurerm_service_plan.example.id

  storage_container_type      = "blobContainer"
  storage_container_endpoint  = "${azurerm_storage_account.example.primary_blob_endpoint}${azurerm_storage_container.example.name}"
  storage_authentication_type = "StorageAccountConnectionString"
  storage_access_key          = azurerm_storage_account.example.primary_access_key
  runtime_name                = var.runtime_name
  runtime_version             = var.runtime_version
  maximum_instance_count      = 50
  instance_memory_in_mb       = 2048
  
  site_config {
  }
}
  1. 创建名为 outputs.tf 的文件并插入以下代码:
output "resource_group_name" {
  value = azurerm_resource_group.example.name
}

output "sa_name" {
  value = azurerm_storage_account.example.name
}

output "asp_name" {
  value = azurerm_service_plan.example.name
}

output "fa_name" {
  value = azurerm_function_app_flex_consumption.example.name
}

output "fa_url" {
  value = "https://${azurerm_function_app_flex_consumption.example.name}.chinacloudsites.cn"
}
  1. 创建名为 providers.tf 的文件并插入以下代码:
terraform {
  required_version = ">=1.0"

  required_providers {
    azurerm = {
      source  = "hashicorp/azurerm"
      version = "~>4.0"
    }
    random = {
      source  = "hashicorp/random"
      version = "~>3.0"
    }
  }
}

provider "azurerm" {
  features {}
}
  1. 创建名为 variables.tf 的文件并插入以下代码:
variable "resource_group_name" {
  type        = string
  default     = ""
  description = "The name of the Azure resource group. If blank, a random name will be generated."
}

variable "resource_group_name_prefix" {
  type        = string
  default     = "rg"
  description = "Prefix of the resource group name that's combined with a random ID so name is unique in your Azure subscription."
}

variable "resource_group_location" {
  type        = string
  default     = "chinanorth2"
  description = "Location of the resource group."
}

variable "sa_account_tier" {
  description = "The tier of the storage account. Possible values are Standard and Premium."
  type        = string
  default     = "Standard"
}

variable "sa_account_replication_type" {
  description = "The replication type of the storage account. Possible values are LRS, GRS, RAGRS, and ZRS."
  type        = string
  default     = "LRS"
}

variable "sa_name" {
  description = "The name of the storage account. If blank, a random name will be generated."
  type        = string
  default     = ""
}

variable "ws_name" {
  description = "The name of the Log Analytics workspace. If blank, a random name will be generated."
  type        = string
  default     = ""
}

variable "ai_name" {
  description = "The name of the Application Insights instance. If blank, a random name will be generated."
  type        = string
  default     = ""
}

variable "asp_name" {
  description = "The name of the App Service Plan. If blank, a random name will be generated."
  type        = string
  default     = ""
}

variable "fa_name" {
  description = "The name of the Function App. If blank, a random name will be generated."
  type        = string
  default     = ""
}

variable "runtime_name" {
  description = "The name of the language worker runtime."
  type        = string
  default     = "node" # Allowed: dotnet-isolated, java, node, powershell, python
}

variable "runtime_version" {
  description = "The version of the language worker runtime."
  type        = string
  default     = "20" # Supported versions: see https://aka.ms/flexfxversions
}

重要

如果使用 4.x azurerm 提供程序,则必须在运行 Terraform 命令之前 显式指定要向 Azure 进行身份验证的 Azure 订阅 ID

一种指定 Azure 订阅 ID 的方法是在名为 providers 的环境变量中指定订阅 ID,而不是将其放在 ARM_SUBSCRIPTION_ID 块中。

有关详细信息,请参阅 Azure 提供程序参考文档

初始化 Terraform

运行 terraform init,将 Terraform 部署进行初始化。 此命令将下载管理 Azure 资源所需的 Azure 提供程序。

terraform init -upgrade

要点

  • 参数 -upgrade 可将必要的提供程序插件升级到符合配置版本约束的最新版本。

创建 Terraform 执行计划

运行 terraform plan 以创建执行计划。

terraform plan -out main.tfplan

要点

  • terraform plan 命令将创建一个执行计划,但不会执行它。 相反,它会确定需要执行哪些操作,以创建配置文件中指定的配置。 此模式允许你在对实际资源进行任何更改之前验证执行计划是否符合预期。
  • 使用可选 -out 参数可以为计划指定输出文件。 使用 -out 参数可以确保所查看的计划与所应用的计划完全一致。

应用 Terraform 执行计划

运行 terraform apply 以将执行计划应用到您的云基础架构。

terraform apply main.tfplan

要点

  • 示例 terraform apply 命令假设你先前运行了 terraform plan -out main.tfplan
  • 如果为 -out 参数指定了不同的文件名,请在对 terraform apply 的调用中使用该相同文件名。
  • 如果未使用 -out 参数,请调用不带任何参数的 terraform apply

验证结果

  1. 获取 Azure 资源组名称。

    resource_group_name=$(terraform output -raw resource_group_name)
    
  2. 获取存储帐户名称。

    sa_name=$(terraform output -raw sa_name)
    
  3. 获取服务计划名称。

    asp_name=$(terraform output -raw asp_name)
    
  4. 获取函数应用计划名称。

    fa_name=$(terraform output -raw fa_name)
    
  5. 运行 az functionapp show 以查看 Azure Functions 弹性消耗计划。

    az functionapp show --name $function_app_name --resource-group $resource_group_name  
    

打开浏览器并输入以下 URL:https://< fa_name.chinacloudsites.cn>。 将占位符 <fa_name> 替换为 Terraform 输出的值。

Azure Functions 应用“欢迎页面”的屏幕截图。

清理资源

不再需要通过 Terraform 创建的资源时,请执行以下步骤:

  1. 运行 terraform plan 并指定 destroy 标志。

    terraform plan -destroy -out main.destroy.tfplan
    

要点

  • terraform plan 命令将创建一个执行计划,但不会执行它。 相反,它会确定需要执行哪些操作,以创建配置文件中指定的配置。 此模式允许你在对实际资源进行任何更改之前验证执行计划是否符合预期。
  • 使用可选 -out 参数可以为计划指定输出文件。 使用 -out 参数可以确保所查看的计划与所应用的计划完全一致。
  1. 运行 terraform apply 来应用执行计划。

    terraform apply main.destroy.tfplan
    

Azure 上的 Terraform 故障排除

排查在 Azure 上使用 Terraform 时遇到的常见问题

后续步骤

现在可以将代码项目部署到在 Azure 中创建的函数应用资源。

可以从这些本地环境创建、验证代码项目并将其部署到新的函数应用: