liveBook · Manning

Aws_instance

As explained in Terraform in Depth: Infrastructure as Code with Terraform and OpenTofu

aws_instance is a Terraform resource type representing an Amazon EC2 virtual machine instance.

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

How Terraform in Depth: Infrastructure as Code with Terraform and OpenTofu covers it

How deep it goes
Walks through resource arguments, lookup references, and variable substitutions; stops short of instance lifecycle or deployment commands.
Examples
Uses a `t3.micro` instance with a looked-up Ubuntu AMI and subnet, then replaces fixed inputs with variables.
What it assumes
Introduces data sources as read-only lookups while assuming familiarity with basic Terraform resource and variable syntax.
What you can do after
Build it from scratch as a Terraform resource, then configure its subnet and instance type through module inputs.
How it connects
Connects EC2 instances to Terraform resources, data sources, AMIs, subnets, input variables, and modules.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Terraform in Depth: Infrastructure as Code with Terraform and OpenTofu. The section links point to the parts of the book it draws on.