How to Create an AWS EC2 Instance in Terraform

The following Terraform code snippet creates an EC2 instance for you.

provider "aws" {
  region = "us-west-2"
}

resource "aws_instance" "example" {
  ami           = "ami-0c94855ba95c71c99"  # Amazon Linux 2 AMI
  instance_type = "t2.micro"
  key_name      = "example-keypair"

  tags = {
    Name = "example-instance"
  }
}

In this example, we’re using the aws_instance resource type to create an EC2 instance in the us-west-2 region. We’re using the ami parameter to specify the Amazon Linux 2 AMI ID, and the instance_type parameter to specify a t2.micro instance type. We’re also specifying a key pair to use for SSH access with the key_name parameter.

Finally, we’re adding a tags block to specify a Name tag for the instance. You can customize this block with any additional tags that you’d like to add.