Narendra Pinnaka
Narendra Pinnaka

Reputation: 215

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

my directory structure

.
├── 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 = {}
}

when i try to pass the subnet_id from outside i'm getting error.

terraform plan -var subnet_id=$subnet_name

Error: Value for undeclared variable A variable named "subnet_id" was assigned on the command line, but the root module does not declare a variable of that name. To use this value, add a "variable" block to the configuration.

if any of you have idea about this issue please help me.

Upvotes: 9

Views: 24269

Answers (1)

Fauzan
Fauzan

Reputation: 755

You need to define the variable in the root module too, where you use the module. In your case you use the module at main.tf, so add the variable inside your module like this :

Terraform 12

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

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

Terraform 11

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

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

Upvotes: 12

Related Questions