How to Create an EC2 Instance with Terraform: Simple Guide
To create an EC2 instance with
Terraform, define an aws_instance resource in your Terraform configuration specifying the AMI, instance type, and other settings. Then run terraform init, terraform plan, and terraform apply to deploy the instance.Syntax
The basic syntax to create an EC2 instance in Terraform uses the resource block with the type aws_instance. You specify a unique name, the Amazon Machine Image (AMI) ID, and the instance type. Optional settings include tags, key pairs, and security groups.
- resource: Declares a resource to create.
- aws_instance: The resource type for EC2 instances.
- name: A unique name for the resource.
- ami: The ID of the machine image to use.
- instance_type: The size/type of the instance (e.g., t2.micro).
terraform
resource "aws_instance" "example" { ami = "ami-0c55b159cbfafe1f0" instance_type = "t2.micro" }
Example
This example creates a simple EC2 instance using the latest Amazon Linux 2 AMI in the us-east-1 region. It sets a tag for easy identification.
terraform
provider "aws" { region = "us-east-1" } resource "aws_instance" "example" { ami = "ami-0c55b159cbfafe1f0" instance_type = "t2.micro" tags = { Name = "ExampleInstance" } }
Output
Apply complete! Resources: 1 added, 0 changed, 0 destroyed.
Outputs:
instance_id = i-0abcd1234efgh5678
Common Pitfalls
Common mistakes when creating EC2 instances with Terraform include:
- Using an incorrect or unavailable AMI ID for the chosen region.
- Not setting the AWS provider region, causing errors or deploying in unexpected regions.
- Forgetting to run
terraform initbefore planning or applying. - Not having AWS credentials configured properly.
- Using instance types not supported in the account or region.
Always verify your AMI ID matches your AWS region and check your AWS credentials before applying.
terraform
/* Wrong: AMI ID from a different region */ resource "aws_instance" "wrong" { ami = "ami-0abcdef1234567890" # AMI not in us-east-1 instance_type = "t2.micro" } /* Right: Correct AMI for region */ resource "aws_instance" "right" { ami = "ami-0c55b159cbfafe1f0" # Amazon Linux 2 in us-east-1 instance_type = "t2.micro" }
Quick Reference
Remember these key points when creating EC2 instances with Terraform:
- Always specify the
providerwith the correct AWS region. - Use the correct
amiID for your region. - Choose an instance type that fits your needs and is available.
- Run
terraform initonce before planning or applying. - Use tags to organize and identify your instances.
Key Takeaways
Define an aws_instance resource with ami and instance_type to create an EC2 instance.
Always set the AWS provider region to match your AMI and deployment target.
Run terraform init before terraform plan and terraform apply to prepare your environment.
Verify your AWS credentials and permissions before deploying resources.
Use tags to label your instances for easy management.