To launch and manage an EC2 instance, define a Terraform resource rather than issuing a sequence of vendor-specific commands. A resource block represents a piece of infrastructure; its type identifies the kind of object, and a provider connects that type to the underlying system. section 2.5 section 1.2
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 AWS instance configuration sets an AMI and subnet from data-source lookups, then selects a small instance type for testing. section 2.1.5
A resource block has a type, a name, and type-specific arguments. Type and name together must be unique within a module or workspace. Unlike a resource, a data source reads existing information without creating or modifying it. section 2.5.1 section 2.6
When putting resources to work:
- Use values from other resources or data sources as arguments. References let Terraform infer dependencies and create objects in the needed order; circular dependencies require a workaround. section 1.3.2 section 1.3.3
- Initialize the configuration, inspect the plan, and apply it. An apply can create, update, or delete resources; check its completion counts and errors. section 2.1.6 section 1.4.4
- Account for state: it records identifying metadata, the provider, and attributes that map managed infrastructure back to configuration. section 6.3.4
A provider exposes resource types and implements their behavior. Beyond reading, a resource interface supports create, update, delete, and import operations. Test those operations—not just initial creation—when developing a provider resource. section 12.6 section 12.6.8
