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.
All files in your Terraform directory using the . tf file format will be automatically loaded during operations. Create a variables file, for example, variables.tf and open the file for edit. Add the below variable declarations to the variables file.
Terraform CLI defines the following optional arguments for variable declarations: default - A default value which then makes the variable optional. type - This argument specifies what value types are accepted for the variable. description - This specifies the input variable's documentation.
Command-line flags The most simple way to assign value to a variable is using the -var option in the command line when running the terraform plan and terraform apply commands.
Set the instance name with a variable Add a variable to define the instance name. Create a new file called variables.tf with a block defining a new instance_name variable. Note: Terraform loads all files in the current directory ending in . tf , so you can name your configuration files however you choose.
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}"
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With