Creating an EC2 Instance Using Terraform: A Comprehensive Guide

1. Introduction

Terraform is a popular open-source Infrastructure as Code (IaC) tool, which allows developers to define and provision data center infrastructure using a simple, human-readable language. It helps in managing a wide variety of service providers as well as custom in-house solutions (source).

In contrast, Amazon EC2 (Elastic Compute Cloud) is a part of Amazon’s cloud-computing platform, AWS (Amazon Web Services). It allows users to rent virtual computers to run their own applications.

In this article, we’ll delve into how you can automate the creation of an EC2 instance using Terraform, showcasing the power and utility of IaC in real-world applications.

2. Prerequisites

Before we get started, you’ll need to have Terraform installed on your machine, as well as an AWS account. If you’re unsure about how to do this, follow the steps in our detailed Terraform setup guide and AWS setup guide.

Understanding Terraform Authentication with AWS

When Terraform interacts with AWS, it needs a way to authenticate. This is usually done by providing your AWS access keys. These keys consist of an access key ID and a secret access key, which can be created in the AWS Management Console.

Terraform supports several methods to authenticate with AWS:

  1. Explicitly specifying your access keys in your Terraform configuration. This method is not recommended due to the security risk of storing sensitive credentials in plain text files.
  2. Setting your access keys as environment variables (AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY).
  3. Using the shared credentials file. This file is located by default at ~/.aws/credentials on Linux and macOS, or "%USERPROFILE%\.aws\credentials" on Windows.
  4. Using EC2 instance profiles if you’re running Terraform on an EC2 instance.

In an enterprise setting, using environment variables or the shared credentials file is often the best way to manage your AWS credentials. It ensures the security of your sensitive information while also giving Terraform the access it needs to manage your resources.

3. Basics of Terraform

Terraform uses a declarative language called HashiCorp Configuration Language (HCL). This means you only need to specify what resources you need, not how to create them.

In Terraform, providers are a logical abstraction of an upstream API. This includes cloud service providers such as AWS.

Lastly, resources in Terraform are the most important aspect in a Terraform configuration. Each resource block describes one or more infrastructure objects.

4. Creating an EC2 Instance with Terraform

To get started, we’ll need to create a Terraform configuration file.

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

resource "aws_instance" "example" {
  ami           = "ami-0c94855ba95c574c8"
  instance_type = "t2.micro"

In this block, we define AWS as our provider and specify the region as ‘us-west-2‘. Then, we define an AWS instance resource.

The ami stands for Amazon Machine Image. It’s a template that contains the software configuration (operating system, application server, and applications) required to launch your instance. You can select an AMI provided by AWS, our user community, or the AWS Marketplace. You can also create your own AMIs.

AMIs are identified by their unique AMI ID.

You can find AMI IDs in the EC2 console under the ‘Instances’ or ‘AMIs’ sections. The ID will be listed under the ‘AMI ID’ column.

One important note here is that AMI IDs are region-dependent. The same AMI will have different IDs in different regions. You should therefore choose the appropriate AMI ID that for the region you’ve specified in the provider block.

instance_type is the type of instance to start. Each instance type offers different compute, memory, and storage capabilities and are grouped in instance families based on these capabilities. In our example, we’ve selected a ‘t2.micro’ instance, which is a general-purpose instance type.

The instance types available depend on the region you’ve specified in your provider block. A comprehensive list of available instance types can be found in the AWS documentation.

Once you’ve defined your configuration, the next step is to initialize your Terraform workspace. The terraform init command is used to initialize a working directory containing Terraform configuration files.

$ terraform init

The next step is to create an execution plan. Terraform performs a refresh, unless explicitly disabled, and then determines what actions are necessary to achieve the desired state specified in the configuration files. This is accomplished using the terraform plan command.

$ terraform plan

Finally, to apply the desired changes and reach the desired state of the configuration, you can use the terraform apply command.

$ terraform apply

5. Configuring Your EC2 Instance

The initial example we shared is a simplified version of a Terraform configuration file to create an AWS EC2 instance. However, in a real-world scenario, there are additional details you need to consider and specify in order to effectively manage your EC2 instances and overall AWS infrastructure.

Here’s an expanded version of the EC2 instance resource:

resource "aws_instance" "example" {
  ami           = "ami-0c94855ba95c574c8"
  instance_type = "t2.micro"
  key_name               = "my_key_pair"
  vpc_security_group_ids = ["sg-01234567890abcdef"]
  subnet_id              = "subnet-01234567890abcdef"
  tags = {
    Name = "ExampleInstance"

In this configuration, in addition to ami and instance_type, we’ve defined some more parameters.

  • key_name specifies the key pair to use when logging into your instance. This should match the name of the key pair you’ve created in the AWS console or through the AWS CLI.
  • The vpc_security_group_ids parameter is a list of security group identifiers to assign to the instance. A security group acts as a virtual firewall that controls the traffic for one or more instances. It’s important to ensure that your EC2 instance is associated with the right security groups in order to control access appropriately. You can find more about AWS Security Groups in our security guide.
  • subnet_id allows you to specify which subnet to associate your EC2 instance with. Subnets are subdivisions of your VPC’s IP address range where you can place groups of isolated resources. Specifying the right subnet is crucial for organizing your resources and managing access to your instances.
  • Finally, tags allow you to assign metadata to your AWS resources, which can help you manage, identify, organize, search for, and filter resources.

As you become more familiar with AWS and Terraform, you’ll find there are many more parameters that you can define depending on your specific needs. It is always a good idea to refer to the official Terraform AWS Provider documentation for a complete list of arguments and attributes for creating an EC2 instance.

6. Managing State with Terraform

In the world of Terraform, “state” is an incredibly important concept. State, in simple terms, is a snapshot of your resources at a specific point in time. It’s a JSON file that maps your resources in the real world to your configuration files, and stores metadata about your resources and configuration. It helps Terraform remember what it has created in the past, and what it needs to do in the future.

By default, Terraform stores the state locally in a file named terraform.tfstate. After you run terraform apply, you can inspect this file to see the current state of your resources.

$ terraform show

This command outputs a human-readable version of your terraform.tfstate file. It’s particularly useful when you want to verify what Terraform will do before you decide to execute.

When you’re working with an EC2 instance, the state file includes information about the instance, such as its ID, instance type, AMI, subnet, security group IDs, and much more.

While the local state works well when you’re working alone, it’s not sufficient for a team-based workflow, as the state could become outdated if multiple people are making changes simultaneously. In this case, remote state is a better solution. With remote state, Terraform writes the state data to a remote data store, which can be shared between all members of your team.

To destroy or remove the infrastructure that you’ve created, you use the terraform destroy command. This will terminate the EC2 instance that was created:

$ terraform destroy

This command is particularly useful when you want to clean up the resources that you’ve created to avoid incurring unnecessary costs.

Remember, managing the state of your EC2 instances correctly is a vital part of using Terraform effectively. This involves not only tracking and updating the state as you change your resources, but also protecting the state file as it contains sensitive information.

Related Reading: Learn more about Terraform Workspace – a Terraform feature that allows you to manage multiple environments, such as development, staging, and production, within a single Terraform configuration.

7. Best Practices for Using Terraform with AWS

When it comes to using Terraform effectively with AWS, one of the best practices is in the area of managing your Terraform code effectively. As your infrastructure grows, your Terraform code can become messy. Organizing your code into modules will help keep it clean and readable.

Using Terraform in a team presents its own set of challenges, including managing remote states, avoiding conflicts, and enforcing standards. Check out our best practices guide for more detailed recommendations.

8. Conclusion

Creating an EC2 instance using Terraform is an efficient way to manage your AWS infrastructure. It saves time, increases repeatability, and reduces the risk of human error. It also allows you to keep your infrastructure in version control, enabling collaboration and transparency.

For further reading, consider our guide on Terraform interview questions and learn how to setup an EKS cluster using Terraform to further deepen your understanding.


1. What is Terraform?

Terraform is an open-source Infrastructure as Code (IaC) tool, which allows developers to define and provision data center infrastructure using a simple, human-readable language.

2. What is Amazon EC2?

Amazon EC2 (Elastic Compute Cloud) is a part of Amazon’s cloud-computing platform, AWS (Amazon Web Services). It allows users to rent virtual computers to run their own applications.

3. How to create an EC2 instance using Terraform?

To create an EC2 instance using Terraform, you define an aws_instance resource in your Terraform configuration file, specify the necessary parameters like ami and instance_type, then run terraform init to initialize your workspace, followed by terraform apply to create the instance.

4. What are the best practices when using Terraform with AWS?

Some best practices include organizing your code into modules, managing your Terraform state effectively, using version control, and adhering to AWS’s best security practices.

5. How do I destroy infrastructure created with Terraform?

You can destroy the infrastructure you’ve created using the terraform destroy command.

6. What is the aws_instance resource in Terraform?

aws_instance is a resource type provided by Terraform for managing AWS EC2 instances.

7. What are some common use cases for Terraform aws_instance?

Terraform’s aws_instance can be used to deploy single or multiple AWS instances or to integrate with other AWS services like RDS, S3, or Auto Scaling.

8. How does Terraform handle updates to aws_instance?

When you modify the configuration of an aws_instance resource and run terraform apply again, Terraform will calculate the difference and perform the necessary actions.

9. How do I terminate an aws_instance managed by Terraform?

You can remove its resource block from your Terraform configuration and run terraform apply, or use terraform destroy to remove all resources.