# 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`
- **Domain:** terraform
- **Category:** runtime_error
- **Verification:** ai_generated
- **Fix Rate:** 85%

## Root Cause

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.

## Version Compatibility

| Version | Status | Introduced | Deprecated |
|---------|--------|------------|------------|
| Terraform v1.5 | active | — | — |
| Terraform v1.6 | active | — | — |
| Terraform v1.7 | active | — | — |

## Workarounds

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`.** (95% success)
   ```
   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.** (85% success)
   ```
   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.** (75% success)
   ```
   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.
   ```

## Dead Ends

- **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% fail)
- **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% fail)
- **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% fail)
