vpc_id 此处不应有参数

vpc_id argument is not expected here

我是在 Terraform 中使用模块的新手,我在我的根模块中的 main.tf 中收到错误消息,提示“此处不应有参数 vpc_id”,并且出现此错误发生在底部的“sg”模块块中。

这是我的根模块main.tf

  access_key = var.my_access_key
  secret_key = var.my_secret_key
  region     = var.region
}

provider "random" {
}

resource "random_id" "prefix" {
  byte_length = 8
}

module "ec2" {
  source = "./modules/ec2"
  infra_env = var.infra_env
  public_ssh_key = var.public_ssh_key
  allow_rdp = module.sg.allow_rdp.id
  allow_winrm = module.sg.allow_winrm.id
}

module "iam" {
  source = "./modules/iam"
  infra_env = var.infra_env
}

module "s3" {
  source = "./modules/s3"
  infra_env = var.infra_env
}

module "sg" {
  source = "./modules/sg" 
  infra_env = var.infra_env
  vpc_id = module.vpc.vpc_1.id
  }

module "vpc" {
  source = "./modules/vpc"
  infra_env = var.infra_env
}

这是我的“SG”模块的 Main.tf——我以为我只需要输入“module.vpc.vpc_1.id”就可以从该模块获得输入

terraform {
  required_version = ">= 1.1.5"
}

  module "vpc" {
    source = "../vpc"

    infra_env = var.infra_env
  }

# Allow WinRM to set adminstrator password
resource "aws_security_group" "allow_winrm" {
  name        = "allow_winrm"
  description = "Allow access the instances via WinRM over HTTP and HTTPS"
  vpc_id      = module.vpc.vpc_1.id

  ingress {
    description = "Access the instances via WinRM over HTTP and HTTPS"
    from_port   = 5985
    to_port     = 5986
    protocol    = "tcp"
    cidr_blocks = ["0.0.0.0/0"]
  }

  egress {
    from_port   = 0
    to_port     = 0
    protocol    = "-1"
    cidr_blocks = ["0.0.0.0/0"]
  }

  tags = {
    Name = "${var.infra_env}-allow-winrm"
  }
}

# Allow RDP connectvity to EC2 instances
resource "aws_security_group" "allow_rdp" {
  name        = "allow_rdp"
  description = "Allow access the instances via RDP"
  vpc_id      = module.vpc.vpc_1.id

  ingress {
    description = "Allow access the instances via RDP"
    from_port   = 3389
    to_port     = 3389
    protocol    = "tcp"
    cidr_blocks = ["0.0.0.0/0"]
  }

  tags = {
    Name = "${var.infra_env}-allow-rdp"
  }
}

这是我的 VPC 模块的输出,位于我的 VPC 模块中:

output "subnet_1" {
  value = aws_subnet.subnet_1
}

output "vpc_1" {
  value = aws_vpc.vpc_1.id
}

output "gw_1" {
  value = aws_internet_gateway.gw_1
}

您的代码有几个问题。在输出中,你写了这个:

output "vpc_1" {
  value = aws_vpc.vpc_1.id
}

这意味着输出值已经提供了您想要的 VPC ID。仅通过名称引用它就足够了:module.vpc.vpc_1。 [1].

中提供了有关引用模块输出的更多信息

这里的第二个问题是您试图在另一个子模块 (SG) 中引用一个子模块 (VPC) 的输出:

vpc_id      = module.vpc.vpc_1.id

但是,在子模块(即 SG)中指定一个变量就足够了。例如,您可以这样定义一个变量:

variable "vpc_id" {
  description = "VPC ID."
  type        = string
}

那么,你只要把上面的写成:

vpc_id      = var.vpc_id

调用SG模块时,可以使用:

module "sg" {
  source = "./modules/sg"
 
  infra_env = var.infra_env
  vpc_id    = module.vpc.vpc_1
}

请注意,在引用 module.vpc.vpc_1.idSG 模块中的任何地方都应该对 var.vpc_id 进行相同的更改。


[1] https://www.terraform.io/language/values/outputs#accessing-child-module-outputs