Terraform 数据源含义

Terraform Data Source Meaning

我是 Terraform 的新手,正在尝试了解数据源。我已经阅读了documentation and this Whosebug ,但我仍然不清楚数据源的用例。

我有以下代码块:

resource "azurerm_resource_group" "rg" {
  name     = "example-resource-group"
  location = "West US 2"
}


data "azurerm_resource_group" "test" {
  name = "example-resource-group"
}

但是我收到 404 错误:

  • data.azurerm_resource_group.test: data.azurerm_resource_group.test: resources.GroupsClient#Get: Failure responding to request: StatusCode=404 -- Original Error: autorest/azure: Service returned an error. Status=404 Code="ResourceGroupNotFound" Message="Resource group 'example-resource-group' could not be found."

我不明白为什么找不到资源组。另外,我不清楚 datavariable 之间的区别,什么时候应该使用 which.

谢谢

将数据源视为您要从其他地方读取的值。

变量是您在 运行 代码中定义的东西。

当您将 data source 用于 azurerm_resource_group 时,terraform 将搜索具有您在数据源块中定义的名称的现有资源。

示例

    data "azurerm_resource_group" "test" {
      name = "example-resource-group"
    }

从下面关于 404 错误的评论中引用@ydaetskcoR:

It's 404ing because the data source is running before the resource creates the thing you are looking for. You would use a data source when the resource has already been created previously, not in the same run as the resource you are creating.

我已经在这个 中详细解释了什么是数据源。总结一下:

  • 数据源 提供有关实体的动态 信息,这些实体不受当前 Terraform 配置
  • 变量提供静态信息

您的代码块不起作用,因为您的数据源引用的资源尚未创建。在规划阶段,Terraform 将尝试查找名为 example-resource-group 的资源组,但找不到,因此它会中止整个 运行。块的顺序对其应用顺序没有影响。

如果删除 data 块,运行 terraform apply,然后 添加 data 块,它应该工作。但是,数据源用于检索有关不受 Terraform 配置管理的实体的数据。在你的情况下,你不需要 data.azurerm_resource_group.test 数据源,你可以简单地使用 exported attributes from the resource. In the case of azurerm_resource_group, this is a single id attribute.