快速入门:使用 Terraform 模板创建应用服务应用

通过使用 Terraform 将应用部署到云中,开始使用 Azure 应用服务。 由于使用的是免费应用服务层,因此完成本快速入门不会产生费用。

使用 Terraform 可以在 Azure 中定义和创建完整的基础结构部署。 以用户可读格式生成 Terraform 模板,用于以一致且可重现的方式创建和配置 Azure 资源。 本文介绍如何使用 Terraform 创建应用。

先决条件

  • 一份 Azure 订阅。 如果没有 Azure 订阅,可在开始前创建一个试用帐户

  • Terraform 配置。 使用以下选项之一:

查看模板

选择以下 Linux 或 Windows 模板以创建应用服务计划和应用服务应用。 Linux 将从 Hello World存储库创建示例 Node.js 应用。 Windows 容器模板将从 Microsoft容器注册表创建一个示例 ASP.NET 应用。

# Configure the Azure provider
terraform {
  required_providers {
    azurerm = {
      source  = "hashicorp/azurerm"
      version = "~> 3.0.0"
    }
  }
  required_version = ">= 0.14.9"
}
provider "azurerm" {
  features {}
}

# Generate a random integer to create a globally unique name
resource "random_integer" "ri" {
  min = 10000
  max = 99999
}

# Create the resource group
resource "azurerm_resource_group" "rg" {
  name     = "myResourceGroup-${random_integer.ri.result}"
  location = "chinaeast"
}

# Create the Linux App Service Plan
resource "azurerm_service_plan" "appserviceplan" {
  name                = "webapp-asp-${random_integer.ri.result}"
  location            = azurerm_resource_group.rg.location
  resource_group_name = azurerm_resource_group.rg.name
  os_type             = "Linux"
  sku_name            = "B1"
}

# Create the web app, pass in the App Service Plan ID
resource "azurerm_linux_web_app" "webapp" {
  name                  = "webapp-${random_integer.ri.result}"
  location              = azurerm_resource_group.rg.location
  resource_group_name   = azurerm_resource_group.rg.name
  service_plan_id       = azurerm_service_plan.appserviceplan.id
  depends_on            = [azurerm_service_plan.appserviceplan]
  https_only            = true
  site_config { 
    minimum_tls_version = "1.2"
    application_stack {
      node_version = "24-lts"
    }
  }
}

#  Deploy code from a public GitHub repo
resource "azurerm_app_service_source_control" "sourcecontrol" {
  app_id             = azurerm_linux_web_app.webapp.id
  repo_url           = "https://github.com/Azure-Samples/nodejs-docs-hello-world"
  branch             = "main"
  use_manual_integration = true
  use_mercurial      = false
}

该模板定义了以下四个 Azure 资源。 有关更多详细信息和使用情况信息,请参阅 Azure 提供程序 Terraform 注册表