错误:data.aws_subnet.selected:数据源引用了尚未创建的资源
Error: data.aws_subnet.selected: data source refers to resource that has not yet been created
ID: terraform/data-source-refers-to-resource-not-yet-created
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| Terraform v1.5 | active | — | — | — |
| Terraform v1.6 | active | — | — | — |
| Terraform v1.7 | active | — | — | — |
根因分析
数据源配置为读取依赖于另一个资源先创建的 AWS 资源,但未正确声明依赖关系,导致计划时错误。
English
A data source is configured to read from an AWS resource that depends on another resource being created first, but the dependency is not properly declared, causing a plan-time error.
官方文档
https://developer.hashicorp.com/terraform/language/data-sources#data-resource-dependencies解决方案
-
Ensure the data source has a direct or indirect reference to the resource: change `data.aws_subnet.selected` to reference a subnet ID from the created resource, e.g., `vpc_id = aws_vpc.main.id`.
-
Use a local value to compute the dependency: `locals { subnet_id = aws_subnet.main.id }` then reference `local.subnet_id` in the data source's filter. -
If the resource must be created before the data source, use `terraform apply -target=aws_subnet.main` first to create the resource, then run the full plan.
无效尝试
常见但无效的做法:
-
Adding `depends_on` to the data source pointing to the resource
100% 失败
Data sources cannot use `depends_on` in Terraform; they are read-only and must rely on explicit references to infer dependencies.
-
Moving the data source inside a module and calling the module with depends_on
80% 失败
While modules can use depends_on, the data source itself still cannot depend on resources; the error persists because the data source has no reference to the resource.
-
Using `terraform refresh` before plan to pre-populate the data source
90% 失败
Refresh only updates existing state; it doesn't create missing resources. The data source will still fail if the underlying resource doesn't exist.