'Terraform AWS provider not finding route table from subnet_id

I'm trying to get the route table associated with a subnet. It seems like the AWS provider is not correctly finding the subnet? I attempted to follow the documentation, but I get this error:

│ Error: query returned no results. Please change your search criteria and try again
│
│   with data.aws_route_table.selected,
│   on main.tf line 1, in data "aws_route_table" "selected":
│  1: data "aws_route_table" "selected" {
│

Here is the relevant documentation I'm following:

https://registry.terraform.io/providers/hashicorp/aws/latest/docs/data-sources/route_table

Here is the example I used as a reference:

data "aws_route_table" "selected" {
  subnet_id = var.subnet_id
}

Here's what I wrote:

data "aws_route_table" "selected" {
  subnet_id = "subnet-1234567890abcdefg"
}

If I use the route table ID, then it works:

data "aws_route_table" "selected" {
  route_table_id = "rtb-1234567890abcdefg"
}

I noticed that if I do a terraform state show data.aws_route_table.selected on the working example, there is no subnet_id listed as an attribute.



Solution 1:[1]

It appears that the aws_route_table and aws_route_tables resources will only return route tables explicitly associated with the subnet. If the subnet uses the main route table, then terraform won't return that.

In my example, there was no explicit subnet association - the subnet was using the main route table. As soon as I added an explicit subnet association, the data block started working as expected.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Swiss