我在将现有 AWS 路由表导入 Terraform 时遇到了一些麻烦。它们导入,并且它们的路由记录在状态文件中,但运行plan
或apply
之后总是希望删除这些路由,即使它们也在 Terraform 中定义。
我在 Terraform 中定义了一个现有的 AWS 路由表,如下所示:
resource "aws_route_table" "public_staging" {
vpc_id = "${aws_vpc.staging.id}"
route {
cidr_block = "${aws_vpc.management.cidr_block}"
vpc_peering_connection_id = "${aws_vpc_peering_connection.management_to_staging.id}"
}
route {
cidr_block = "0.0.0.0/0"
gateway_id = "${aws_internet_gateway.staging.id}"
}
tags {
Name = "public staging (igw)"
environment = "staging"
}
}
然后像这样导入它;terraform import aws_route_table.public_management rtb-abc123
.
哪个输出:
aws_route_table.public_staging: Importing from ID "rtb-abc123"...
aws_route_table.public_staging: Import complete!
Imported aws_route_table (ID: rtb-abc123)
Imported aws_route (ID: r-rtb-abc123123456)
Imported aws_route (ID: r-rtb-abc123654321)
Imported aws_route_table_association (ID: rtbassoc-qwert765)
Imported aws_main_route_table_association (ID: rtbassoc-asdf9876)
aws_route.public_staging: Refreshing state... (ID: r-rtb-abc123123456)
aws_route_table.public_staging: Refreshing state... (ID: rtb-abc123)
aws_route.public_staging-1: Refreshing state... (ID: r-rtb-abc123654321)
aws_route_table_association.public_staging: Refreshing state... (ID: rtbassoc-qwert765)
aws_main_route_table_association.public_staging: Refreshing state... (ID: rtbassoc-asdf9876)
然后运行时terraform plan
,Terraform 想要删除aws_route
它在状态文件中生成的所有资源状态,并创建我们刚刚导入的路由表:
Terraform will perform the following actions:
- aws_route.public_staging
- aws_route.public_staging-1
+ aws_route_table.public_management
...
我还尝试在aws_route_table
资源之外单独定义路由,并通过 ID 将它们附加到路由表,如下所示:
resource "aws_route" "management_to_staging" {
route_table_id = "${aws_route_table.public_management.id}"
cidr_block = "${aws_vpc.staging.cidr_block}"
vpc_peering_connection_id = "${aws_vpc_peering_connection.management_to_staging.id}"
}
唯一会导致无更改状态的情况是,如果我在路由表上运行导入,还定义路由表之外的路由(作为aws_route
资源),然后进入并手动更改状态下生成的名称文件到我定义的 tf 文件。但是,我相信这实际上不会在新的运行中起作用,因为在 中定义的路由aws_route_table
以及作为单独aws_route
资源的路由会发生冲突。
编辑:
据我所知,最有可能的解释是,在导入时,Terraform 很乐意导入路由表中的路由,但随后plan
,它希望使用aws_route
资源显式声明它们。
问题是;你不能导入aws_route
资源,所以你永远不能让你当前的基础设施状态与你的 terraform 状态相匹配。
我认为事后明确声明它们的原因也不起作用,因为状态文件记录导入的路由的方式不同,如果它从import aws_route_table ...
命令获取它们,则如果它从apply
具有显式aws_route
定义的生成它们。
而现在我已经喘不过气来了。