# 错误：data.aws_subnet.selected：数据源引用了尚未创建的资源

- **ID:** `terraform/data-source-refers-to-resource-not-yet-created`
- **领域:** terraform
- **类别:** runtime_error
- **验证级别:** ai_generated
- **修复率:** 85%

## 根因

数据源配置为读取依赖于另一个资源先创建的 AWS 资源，但未正确声明依赖关系，导致计划时错误。

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| Terraform v1.5 | active | — | — |
| Terraform v1.6 | active | — | — |
| Terraform v1.7 | active | — | — |

## 解决方案

1. ```
   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`.
   ```
2. ```
   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.
   ```
3. ```
   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** — Data sources cannot use `depends_on` in Terraform; they are read-only and must rely on explicit references to infer dependencies. (100% 失败率)
- **Moving the data source inside a module and calling the module with depends_on** — 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. (80% 失败率)
- **Using `terraform refresh` before plan to pre-populate the data source** — Refresh only updates existing state; it doesn't create missing resources. The data source will still fail if the underlying resource doesn't exist. (90% 失败率)
