如何将已有VPC导入terraform-aws-modules/vpc/aws模块?
导入现有VPC资源到Terraform模块的问题与解决方法
模块定义
使用terraform-aws-modules/vpc/aws模块管理现有VPC,模块配置如下:
module "vpc" { source = "terraform-aws-modules/vpc/aws" name = "eks-dev" cidr = "10.0.0.0/16" azs = ["us-east-1b", "us-east-1a"] public_subnets = ["10.0.2.0/24", "10.0.1.0/24"] enable_nat_gateway = false enable_vpn_gateway = false tags = { Terraform = "true" Environment = "dev" } }
Terraform Plan输出
执行terraform plan后,输出显示资源将被创建(实际为现有资源,需导入):
# module.vpc.module.vpc.aws_vpc.this[0] will be created + resource "aws_vpc" "this" { + arn = (known after apply) + cidr_block = "10.0.0.0/16" + default_network_acl_id = (known after apply) + default_route_table_id = (known after apply) + default_security_group_id = (known after apply) + dhcp_options_id = (known after apply) + enable_dns_hostnames = true + enable_dns_support = true + enable_network_address_usage_metrics = (known after apply) + id = (known after apply) + instance_tenancy = "default" + ipv6_association_id = (known after apply) + ipv6_cidr_block = (known after apply) + ipv6_cidr_block_network_border_group = (known after apply) + main_route_table_id = (known after apply) + owner_id = (known after apply) + tags = { + "Environment" = "dev" + "Name" = "eks-dev" + "Terraform" = "true" } + tags_all = { + "Environment" = "dev" + "Name" = "eks-dev" + "Terraform" = "true" } }
导入错误
尝试执行导入命令时,出现资源地址不存在的错误:
导入VPC时的错误
❯ terraform import module.vpc.aws_vpc.this vpc-0d8bf51e96d3bc819 Error: resource address "module.vpc.aws_vpc.this" does not exist in the configuration. Before importing this resource, please create its configuration in module.vpc. For example: resource "aws_vpc" "this" { # (resource arguments) }
导入公有子网时的错误
❯ terraform import "module.vpc.aws_subnet.public" "subnet-0d958d42eec08c493" Error: resource address "module.vpc.aws_subnet.public" does not exist in the configuration. Before importing this resource, please create its configuration in module.vpc. For example: resource "aws_subnet" "public" { # (resource arguments) }
解决方案
使用terraform plan输出中显示的完整资源地址执行导入命令即可成功,以VPC为例:
❯ terraform import 'module.vpc.module.vpc.aws_vpc.this[0]' vpc-0d8bf51e96d3bc819 module.vpc.module.vpc.aws_vpc.this[0]: Importing from ID "vpc-0d8bf51e96d3bc819"... module.vpc.module.vpc.aws_vpc.this[0]: Import prepared! Prepared aws_vpc for import module.vpc.module.vpc.aws_vpc.this[0]: Refreshing state... [id=vpc-0d8bf51e96d3bc819] Import successful! The resources that were imported are shown above. These resources are now in your Terraform state and will henceforth be managed by Terraform.
同理,导入公有子网时需使用对应的完整资源地址,比如module.vpc.module.vpc.aws_subnet.public[0](根据实际索引调整)。
内容的提问来源于stack exchange,提问作者anish
相关产品推荐
相关产品推荐

