部署AWS VPC对等连接时Terraform Provider配置缺失报错如何修复
问题分析与修复方案
你这个报错的核心问题是引用了一个未定义的AWS Provider别名——代码里的data "aws_vpc" "accepter"指定了provider = aws.accepter,但你只配置了默认的AWS Provider,根本没定义名为accepter的Provider实例,Terraform找不到对应的配置,所以抛出这个错误。此外代码里还有一个语法错误:vpc_id = "{$var.requester_vpc_id}"里的花括号前多了个$,属于变量引用格式错误。
修复后的完整代码(跨账号/跨区域场景)
如果你的接受方VPC和请求方VPC不在同一个AWS账号或区域,需要配置Provider别名来分别访问两个环境:
terraform { required_providers { aws = { source = "hashicorp/aws" version = "~> 4.1" } } } # 默认Provider:对应请求方VPC所在的账号/区域 provider "aws" { region = "us-east-1" # 若需指定凭证,可添加profile或access_key/secret_key配置 # profile = "requester-aws-profile" } # 定义名为accepter的Provider别名:对应接受方VPC所在的账号/区域 provider "aws" { alias = "accepter" region = "us-east-1" # 接受方VPC在其他区域时,替换为对应区域 # 配置接受方账号的凭证,比如使用不同的AWS配置文件 # profile = "accepter-aws-profile" } data "aws_vpc" "accepter" { provider = aws.accepter # 现在该Provider别名已存在,可正常调用 id = var.accepter_vpc_id } locals { accepter_account_id = element(split(":", data.aws_vpc.accepter.arn), 4) } resource "aws_vpc_peering_connection" "requester" { description = "peer_to_${var.accepter_profile}" vpc_id = var.requester_vpc_id # 修正变量引用的语法错误 peer_vpc_id = data.aws_vpc.accepter.id peer_owner_id = local.accepter_account_id } # 补充变量定义(避免terraform validate提示变量未定义) variable "accepter_vpc_id" { type = string description = "接受方VPC的ID" } variable "requester_vpc_id" { type = string description = "请求方VPC的ID" } variable "accepter_profile" { type = string description = "接受方账号的AWS配置文件名称" }
简化版代码(同账号同区域场景)
如果接受方和请求方VPC在同一个账号、同一区域,完全不需要Provider别名,直接删除多余的provider引用即可:
terraform { required_providers { aws = { source = "hashicorp/aws" version = "~> 4.1" } } } provider "aws" { region = "us-east-1" } data "aws_vpc" "accepter" { id = var.accepter_vpc_id # 移除provider = aws.accepter,使用默认Provider } locals { accepter_account_id = element(split(":", data.aws_vpc.accepter.arn), 4) } resource "aws_vpc_peering_connection" "requester" { description = "peer_to_${var.accepter_profile}" vpc_id = var.requester_vpc_id # 修正语法错误 peer_vpc_id = data.aws_vpc.accepter.id peer_owner_id = local.accepter_account_id } variable "accepter_vpc_id" { type = string description = "接受方VPC的ID" } variable "requester_vpc_id" { type = string description = "请求方VPC的ID" } variable "accepter_profile" { type = string description = "接受方账号的AWS配置文件名称" }
内容的提问来源于stack exchange,提问作者Brian G
相关产品推荐
相关产品推荐

