Terraform
构建基础设施
在本教程中,您将创建一个 Terraform 配置来部署 Azure 资源组。该资源组是您将在后续教程中构建的基础设施的基础。
先决条件
如果您使用的是付费订阅,您可能需要为完成本教程所需的资源付费。
Terraform 1.2.0+ 安装在本地。
已安装 Azure CLI
安装 Azure CLI
您将使用 Azure CLI 进行 Azure 身份验证。
以管理员身份打开您的 PowerShell 提示符并运行以下命令
$ Invoke-WebRequest -Uri https://aka.ms/installazurecliwindows -OutFile .\AzureCLI.msi; Start-Process msiexec.exe -Wait -ArgumentList '/I AzureCLI.msi /quiet'; rm .\AzureCLI.msi
使用 Azure CLI 进行身份验证
Terraform 必须向 Azure 身份验证才能创建基础设施。
在您的终端中,使用 Azure CLI 设置您本地的帐户权限。
$ az login
您的浏览器将打开并提示您输入 Azure 登录凭据。 身份验证成功后,您的终端将显示您的订阅信息。
You have logged in. Now let us find all the subscriptions to which you have access...
[
{
"cloudName": "AzureCloud",
"homeTenantId": "0envbwi39-home-Tenant-Id",
"id": "35akss-subscription-id",
"isDefault": true,
"managedByTenants": [],
"name": "Subscription-Name",
"state": "Enabled",
"tenantId": "0envbwi39-TenantId",
"user": {
"name": "your-username@domain.com",
"type": "user"
}
}
]
找到您想要使用的订阅帐户的 id 列。
选择帐户订阅 ID 后,使用 Azure CLI 设置帐户。
$ az account set --subscription "35akss-subscription-id"
创建服务主体
接下来,创建一个服务主体。 服务主体是 Azure Active Directory 中的一个应用程序,它具有 Terraform 需要代表您执行操作的身份验证令牌。 使用您在上一步骤中指定的订阅 ID 更新 <SUBSCRIPTION_ID>。
$ az ad sp create-for-rbac --role="Contributor" --scopes="/subscriptions/<SUBSCRIPTION_ID>"
Creating 'Contributor' role assignment under scope '/subscriptions/35akss-subscription-id'
The output includes credentials that you must protect. Be sure that you do not include these credentials in your code or check the credentials into your source control. For more information, see https://aka.ms/azadsp-cli
{
"appId": "xxxxxx-xxx-xxxx-xxxx-xxxxxxxxxx",
"displayName": "azure-cli-2022-xxxx",
"password": "xxxxxx~xxxxxx~xxxxx",
"tenant": "xxxxx-xxxx-xxxxx-xxxx-xxxxx"
}
设置您的环境变量
HashiCorp 建议将这些值设置为环境变量,而不是将其保存在您的 Terraform 配置中。
在您的 Powershell 终端中,设置以下环境变量。 确保使用 Azure 在上一个命令中返回的值更新变量值。
$ $Env:ARM_CLIENT_ID = "<APPID_VALUE>"
$ $Env:ARM_CLIENT_SECRET = "<PASSWORD_VALUE>"
$ $Env:ARM_SUBSCRIPTION_ID = "<SUBSCRIPTION_ID>"
$ $Env:ARM_TENANT_ID = "<TENANT_VALUE>"
有关服务主体身份验证的更多信息,请访问 Azure 提供程序文档。
编写配置
创建一个名为 learn-terraform-azure 的文件夹。
$ New-Item -Path "c:\" -Name "learn-terraform-azure" -ItemType "directory"
创建一个名为 main.tf 的新文件,并粘贴下面的配置。
main.tf
# Configure the Azure provider
terraform {
required_providers {
azurerm = {
source = "hashicorp/azurerm"
version = "~> 3.0.2"
}
}
required_version = ">= 1.1.0"
}
provider "azurerm" {
features {}
}
resource "azurerm_resource_group" "rg" {
name = "myTFResourceGroup"
location = "westus2"
}
这是一个 Terraform 可以应用的完整配置。在接下来的部分中,您将更详细地查看配置的每个块。
Terraform 块
terraform {} 块包含 Terraform 设置,包括 Terraform 将用于配置您的基础设施的必需的提供程序。对于每个提供程序, source 属性定义了一个可选的主机名、命名空间和提供程序类型。Terraform 默认从 Terraform 注册表 安装提供程序。在此示例配置中, azurerm 提供程序的源被定义为 hashicorp/azurerm,这是 registry.terraform.io/hashicorp/azurerm 的简写。
您还可以在 required_providers 块中为每个提供程序定义版本约束。 version 属性是可选的,但我们建议使用它来强制提供程序版本。如果没有它,Terraform 将始终使用最新版本的提供程序,这可能会引入破坏性更改。
要了解更多信息,请参考 提供器源文档。
提供商
provider 块配置指定的提供商,在本例中为 azurerm。提供商是 Terraform 用来创建和管理资源的一种插件。您可以在 Terraform 配置中定义多个提供商块来管理来自不同提供商的资源。
资源
使用 resource 块定义您的基础设施组件。资源可以是物理组件,例如服务器,也可以是逻辑资源,例如 Heroku 应用程序。
资源块在块之前有两个字符串:资源类型和资源名称。在此示例中,资源类型为 azurerm_resource_group,名称为 rg。类型的 前缀映射到提供商的名称。在示例配置中,Terraform 使用 azurerm 提供商管理 azurerm_resource_group 资源。资源类型和资源名称共同构成资源的唯一标识符。例如,您的网络的 ID 为 azurerm_resource_group.rg。
资源块包含参数,您可以使用这些参数来配置资源。Azure 提供商文档记录了受支持的资源及其配置选项,包括 azurerm_resource_group 及其支持的参数。
初始化您的 Terraform 配置
在您的终端中初始化您的 learn-terraform-azure 目录。terraform 命令可以在任何操作系统上工作。您的输出应如下所示。
$ terraform init
Initializing the backend...
Initializing provider plugins...
- Finding hashicorp/azurerm versions matching "~> 3.0.2"...
- Installing hashicorp/azurerm v3.0.2...
- Installed hashicorp/azurerm v3.0.2 (signed by HashiCorp)
Terraform has been successfully initialized!
You may now begin working with Terraform. Try running "terraform plan" to see
any changes that are required for your infrastructure. All Terraform commands
should now work.
If you ever set or change modules or backend configuration for Terraform,
rerun this command to reinitialize your working directory. If you forget, other
commands will detect it and remind you to do so if necessary.
格式化并验证配置
我们建议在所有配置文件中使用一致的格式。 terraform fmt 命令会自动更新当前目录中的配置,以提高可读性和一致性。
格式化您的配置。Terraform 会打印出它修改过的文件的名称(如果有)。在本例中,您的配置文件已经正确格式化,因此 Terraform 不会返回任何文件名。
$ terraform fmt
您还可以使用 terraform validate 命令确保您的配置在语法上有效且内部一致。
验证您的配置。上述提供的示例配置是有效的,因此 Terraform 将返回一条成功消息。
$ terraform validate
Success! The configuration is valid.
应用您的 Terraform 配置
运行 terraform apply 命令以应用您的配置。
此输出显示执行计划,并在继续操作前会提示您批准。如果计划中的任何内容看起来不正确或危险,可以安全地在此处中止,而不会对您的基础设施进行任何更改。在确认提示处键入 yes 以继续。
$ terraform apply
An execution plan has been generated and is shown below.
Resource actions are indicated with the following symbols:
+ create
Terraform will perform the following actions:
# azurerm_resource_group.rg will be created
+ resource "azurerm_resource_group" "rg" {
+ id = (known after apply)
+ location = "westus2"
+ name = "myTFResourceGroup"
}
Plan: 1 to add, 0 to change, 0 to destroy.
Do you want to perform these actions?
Terraform will perform the actions described above.
Only 'yes' will be accepted to approve.
Enter a value: yes
azurerm_resource_group.rg: Creating...
azurerm_resource_group.rg: Creation complete after 1s [id=/subscriptions/c9ed8610-47a3-4107-a2b2-a322114dfb29/resourceGroups/myTFResourceGroup]
Apply complete! Resources: 1 added, 0 changed, 0 destroyed.
在您的网络浏览器中导航到 Azure 门户 以验证资源组。
检查您的状态
当您应用您的配置时,Terraform 会将数据写入名为 terraform.tfstate 的文件。该文件包含 Terraform 创建的资源的 ID 和属性,以便它可以管理或销毁这些资源。您的状态文件包含配置中的所有数据,也可能包含纯文本形式的敏感值,因此请不要共享它或将其检入源代码控制。
对于团队或大型项目,请考虑 远程存储您的状态。远程状态存储支持使用 Terraform 进行协作,但超出本教程的范围。
使用 terraform show 检查当前状态。
$ terraform show
# azurerm_resource_group.rg:
resource "azurerm_resource_group" "rg" {
id = "/subscriptions/c9ed8610-47a3-4107-a2b2-a322114dfb29/resourceGroups/myTFResourceGroup"
location = "westus2"
name = "myTFResourceGroup"
}
当 Terraform 创建此资源组时,它还会收集资源的属性和元数据。这些值可以被引用以配置其他资源或输出,您将在后续教程中遇到这些情况。
要查看您的状态文件中的信息,请使用 state 命令。如果您的状态文件很长,您可以使用 list 子命令查看您使用 Terraform 创建的资源列表。
$ terraform state list
azurerm_resource_group.rg
如果您运行 terraform state,您将看到一个完整的可用命令列表,用于查看和操作配置的状态。
$ terraform state
Usage: terraform state <subcommand> [options] [args]
This command has subcommands for advanced state management.
These subcommands can be used to slice and dice the Terraform state.
This is sometimes necessary in advanced cases. For your safety, all
state management commands that modify the state create a timestamped
backup of the state prior to making modifications.
The structure and output of the commands is specifically tailored to work
well with the common Unix utilities such as grep, awk, etc. We recommend
using those tools to perform more advanced state tasks.
Subcommands:
list List resources in the state
mv Move an item in the state
pull Pull current state and output to stdout
push Update remote state from a local state file
replace-provider Replace provider in the state
rm Remove instances from the state
show Show a resource in the state
下一步
有关本教程中使用的概念的更多详细信息
- 在 Terraform 文档 中阅读 Terraform 配置文件语言。
- 了解更多关于 Terraform 提供程序。
- 查看 Terraform 提供程序工程师提供的 Terraform Azure 提供程序 用法示例