Terraform
使用输出值查询数据
在之前的教程中,您使用了输入变量来参数化您的 Terraform 配置。在本教程中,您将使用输出值来组织数据,以便轻松查询和显示给 Terraform 用户。
在构建复杂的基础设施时,Terraform 会存储所有资源数百或数千个属性值。作为 Terraform 的用户,您可能只对少数重要的值感兴趣。输出指定要显示哪些数据。在调用 apply 时,会输出这些数据,并且可以使用 terraform output 命令进行查询。
定义输出
在您的 learn-terraform-azure 目录中创建一个名为 outputs.tf 的文件。将以下输出定义添加到 outputs.tf 中。
outputs.tf
output "resource_group_id" {
value = azurerm_resource_group.rg.id
}
这定义了一个名为 resource_group_id 的输出变量。如果变量要用作其他模块的输入,则变量名称必须符合 Terraform 变量命名约定。value 字段指定值,即您的资源组的 id 属性。
您可以定义多个 output 块来指定多个输出变量。
观察您的资源输出
当您将输出添加到先前应用的配置时,必须重新运行 terraform apply 才能观察新的输出。
应用您的配置。请记住用 yes 确认应用。
$ terraform apply
## ...
Changes to Outputs:
+ resource_group_id = "/subscriptions/c9ed8610-47a3-4107-a2b2-a322114dfb29/resourceGroups/myTFResourceGroup"
You can apply this plan to save these new output values to the Terraform state, without changing any real infrastructure.
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
Apply complete! Resources: 0 added, 0 changed, 0 destroyed.
Outputs:
resource_group_id = "/subscriptions/c9ed8610-47a3-4107-a2b2-a322114dfb29/resourceGroups/myTFResourceGroup"
请注意,apply 运行会返回输出。使用 output 命令和输出 ID 查询输出。
$ terraform output resource_group_id
"/subscriptions/c9ed8610-47a3-4107-a2b2-a322114dfb29/resourceGroups/myTFResourceGroup"