vagrant@tools:~/terraform/module/ec2-instance$ cat main.tf provider "aws" { region =…
- User
vagrant@tools:~/terraform/module/ec2-instance$ cat main.tf provider "aws" { region = "us-east-2" }
Create a VPC
resource "aws_vpc" "main" { cidr_block = "10.0.0.0/16" }
Create a subnet
resource "aws_subnet" "public" { vpc_id = aws_vpc.main.id cidr_block = "10.0.1.0/24" availability_zone = "us-east-2a" # Must match provider region }
Output the subnet ID
output "subnet_id" { value = aws_subnet.public.id }
resource "aws_instance" "example" { ami = var.ami_value instance_type = var.instance_type_value subnet_id = var.subnet_id_value
}
vagrant@tools:~/terraform/module/ec2-instance$ cat variable.tf variable "ami_value" { description = "value of ami" type = string }
variable "instance_type_value" { description = "value of instance type" type = string }
variable "subnet_id_value" { description = "value of subnet id" type = string }
vagrant@tools:~/terraform/module/ec2-instance$ cat output.tf output "public_ip" { value = aws_instance.example.public_ip }
provider "aws" { region = "us-east-2" }
module "ec2_instance" { source = "/home/vagrant/terraform/module/ec2-instance" ami_value = ami-0c55b159cbfafe1f0 instance_type_value = t2.micro subnet_id_value = subnet-0123456789abcdef0
}
terraform plan ╷ │ Error: Invalid reference │ │ on main.tf line 9, in module "ec2_instance": │ 9: ami_value = ami-0c55b159cbfafe1f0 │ │ A reference to a resource type must be followed by at least one attribute access, specifying the resource name. ╵ ╷ │ Error: Reference to undeclared resource │ │ on main.tf line 10, in module "ec2_instance": │ 10: instance_type_value = t2.micro │ │ A managed resource "t2" "micro" has not been declared in the root module. ╵ ╷ │ Error: Invalid reference │ │ on main.tf line 11, in module "ec2_instance": │ 11: subnet_id_value = subnet-0123456789abcdef0 │ │ A reference to a resource type must be followed by at least one attribute access, specifying the resource name. ╵
- Assistant
- User
aws_subnet.public.id
- Assistant
aws_subnet.public.idis the correct way to reference the ID attribute of the subnet resource namedpublicdefined in your Terraform configuration.Explanation
aws_subnetis the resource typepublicis the resource name (fromresource "aws_subnet" "public" { ... }).idis an attribute of that resource that gives you the subnet ID (e.g., )