根模块不声明该名称的变量。要使用此值,请将 "variable" 块添加到配置中

root module does not declare a variable of that name. To use this value, add a "variable" block to the configuration

我的目录结构

.
├── README.md
├── ec2
│   ├── ec2.tf
│   ├── outputs.tf
│   └── vars.tf
├── main.tf

main.tf

provider "aws" {
  region = "us-east-1"
}

module "ec2" {
  source = "./ec2"
}

ec2/ec2.tf

data "aws_ami" "example" {
  most_recent = true
  owners = [
    "amazon"]

  filter {
    name = "image-id"
    values = [
      "ami-0323c3dd2da7fb37d"]
  }

  filter {
    name = "root-device-type"
    values = [
      "ebs"]
  }

  filter {
    name = "virtualization-type"
    values = [
      "hvm"]
  }
}

resource "aws_instance" "web" {
  ami = data.aws_ami.example.id
  instance_type = "t2.micro"
  subnet_id = var.subnet_id
  tags = {
    Name = "HelloWorld"
  }
}

ec2/avrs.tf

variable "subnet_id" {
  default = {}
}

当我尝试从外部传递 subnet_id 时出现错误。

terraform plan -var subnet_id=$subnet_name

错误:未声明变量的值 在命令行上分配了一个名为 "subnet_id" 的变量,但是根 模块不声明该名称的变量。要使用此值,请添加一个 "variable" 阻止配置。

如果你们对这个问题有任何想法,请帮助我。

您也需要在使用模块的根模块中定义变量。在您的情况下,您使用 main.tf 处的模块,因此在模块中添加变量,如下所示:

地形 12

provider "aws" {
  region = "us-east-1"
}

module "ec2" {
  source = "./ec2"
  subnet_id = var.subnet_id
}

地形 11

provider "aws" {
  region = "us-east-1"
}

module "ec2" {
  source = "./ec2"
  subnet_id = "${var.subnet_id}"
}