To launch an Amazon EC2 virtual machine with Terraform, declare an `aws_instance` resource. Its configuration needs an AMI and instance type; it can also specify a subnet. The resource creates the instance, while read-only data sources can look up values to pass into it. section 2.1.4 section 2.1.5
Listing 2.3 Defining an AWS instance with code
resource "aws_instance" "hello_world" { #1
ami = data.aws_ami.ubuntu.id
subnet_id = data.aws_subnets.default.ids[0]
instance_type = "t3.micro" #2
}
The resource uses a looked-up AMI ID, the first ID returned by a subnet lookup, and a low-cost `t3.micro` instance type for testing. section 2.1.5
Avoid hardcoding the AMI when you want newly published images with bug fixes and security updates; a lookup using `most_recent` can return a different AMI after a new one is published. Hardcoding a subnet ID ties the configuration to an account. Taking `ids[0]` is simple, but more complex networks may need subnet filters, such as tags, to select the intended subnet. section 2.1.4 section 2.1.5
Listing 3.33 Using input variables
resource "aws_instance" "hello_world" {
ami = data.aws_ami.ubuntu.id
subnet_id = var.subnet_id #1
instance_type = var.instance_type #2
}
For a reusable module, pass `var.subnet_id` and `var.instance_type` to the resource instead of fixing those choices in the resource block. section 3.8.2
An input variable can retain `t3.micro` as its default while allowing callers to choose another instance type. A subnet input can also be validated against the expected ID pattern before it is passed to `aws_instance`. section 3.8.2
