• Articles

How to Create an AWS EC2 Instance With Terraform?

In this blog, we will guide you through the step-by-step process of creating an AWS EC2 instance using Terraform. Starting from the initial setup of your AWS account to effectively managing the lifecycle of your instance, we will cover it all.

Check out this insightful video on AWS Tutorial for Beginners

Understanding AWS EC2 and Terraform

AWS EC2 (Elastic Compute Cloud) is a web service provided by Amazon Web Services (AWS) that allows users to launch and manage virtual servers, known as instances in the cloud. 

It provides a flexible and scalable infrastructure for running various types of applications and workloads. With Terraform EC2, users have complete control over their virtual servers, including the ability to choose the type, operating system, and storage options of instance.

On the other hand, Terraform is an open-source infrastructure as a code tool developed by HashiCorp. It enables users to define and provision infrastructure resources using a declarative language. Terraform supports multiple cloud providers, including AWS, Azure, and Google Cloud Platform, allowing users to manage their infrastructure consistently across different platforms.

Do you need the best AWS training in your area? Attend the AWS Course at Intellipaat immediately!

Setting Up AWS Account and Access Key

To get started with AWS EC2 Terraform, you first need to set up an AWS account. Look into the following steps to create an AWS account:

  1. Go to the AWS Management Console https://console.aws.amazon.com/.
  2. Click “Create a new AWS account” and read the instructions. Verify your identity using the provided verification method.
  3. Provide the necessary information, such as your email address, password, and payment details.
  4. Once your account is created, you can sign in to the AWS Management Console.

Next, you need to generate an access key to authenticate Terraform with your AWS account. Here’s how to do it:

  1. Sign in to the AWS Management Console.
  2. Open the “IAM” (Identity and Access Management) service.
  3. Choose “Users” from the sidebar and select click on “Add user.”
  4. Give a username and select “Programmatic access” as the access type.
  5. Attach the necessary permissions to the user (e.g., EC2 full access).
  6. Review the user details and create the user.
  7. On the final screen, you will see the access key ID and secret access key. Save this information securely as it will be required when configuring Terraform.

Interested in learning more? Go through this AWS Tutorial to gain a better understanding of AWS.

Cloud Computing EPGC IITR iHUB

Installing and Configuring Terraform

To work with Terraform, you need to install it on your local machine and configure it with your AWS access key. Follow these steps:

  • Download the appropriate Terraform package for your operating system from the official website (https://developer.hashicorp.com/terraform/install).
  • Take out the downloaded package to a directory of your choice. Add the Terraform executable to your system’s PATH environment variable to make it accessible from any location.
  • Open a terminal or command prompt and run the command terraform version to verify the installation.

Next, configure Terraform with your AWS access key:

  • Open a terminal or command prompt.
  • Run the command terraform login to authenticate Terraform with your AWS account.
  • Enter your access key ID and secret access key when prompted.
  • Terraform will securely store the credentials on your machine, allowing you to interact with AWS resources.

Go through this blog on AWS Interview Questions to crack the next job interview!

Creating a Terraform Project

After you’ve installed and configured Terraform, it’s time to start a new Terraform project. Here’s an example of how you could organize your project:

  • Make a new project directory and navigate to it.
  • Make a file called main.tf in the project directory. The core Terraform configuration code will be contained in this file.
  • Create a file called variables.tf if you want to define any variables in your setup.
  • Additional files can be created to modularize your code or to store provider-specific configurations.
  • You will define the infrastructure resources you want to create in the main.tf file, such as VPCs, subnets, security groups, and AWS EC2 terraform instances. Terraform’s declarative language is used to define each resource, allowing you to declare the desired state of the resource.

For example, to create a terraform EC2 instance, you would define a resource block like this:

resource "aws_instance" "example" { ami = "ami-0c94855ba95c71c99" instance_type = "t2.micro" subnet_id = aws_subnet.example.id tags = { Name = "Example Instance" } }

In this example, we specify the Amazon Machine Image (AMI), instance type, subnet ID, and tags for the EC2 instance. Terraform will use this configuration to create the specified EC2 instance when you apply the configuration.

Get 100% Hike!

Master Most in Demand Skills Now !

Writing Infrastructure as Code with Terraform

Writing Infrastructure as Code with Terraform

Infrastructure as Code (IaC) is a methodology that allows you to manage and provision infrastructure resources using code rather than manual processes. Terraform, being an IaC tool, enables you to define your infrastructure in a declarative language and maintain it as version-controlled code. Let’s explore how to write infrastructure as code with Terraform and create an AWS EC2 terraform instance.

  • Defining Provider and Variables:
    The first step in writing Terraform code is to define the provider, which describes the cloud provider and the required credentials. In our situation, we’ll be using AWS. In your Terraform configuration file, define the AWS provider as seen in the following example:
provider "aws" {
  access_key = var.aws_access_key
  secret_key = var.aws_secret_key
  region     = var.aws_region
}

In the above code, we use variables to store sensitive information like access keys and secret keys. Variables provide flexibility and allow us to reuse the same code across different environments or teams. You can define variables in a separate file or directly within the Terraform configuration file.

  • Creating a VPC and Subnet
    A Virtual Private Cloud is a logically isolated section of the AWS cloud where your resources can be launched. To create a VPC and subnet with the help of  Terraform, you’ll need to define the necessary resources and their configurations. Here’s an example of creating a VPC with a subnet:
resource "aws_vpc" "my_vpc" { cidr_block = "10.0.0.0/16" } resource "aws_subnet" "my_subnet" { vpc_id = aws_vpc.my_vpc.id cidr_block = "10.0.0.0/24" }

In the above code, we define an AWS VPC resource with a specific CIDR block (IP range) and an AWS subnet resource associated with the VPC. This will create the networking infrastructure required for our terraform EC2 instance.

  • Configuring Security Groups
    Security groups act as virtual firewalls, controlling inbound and outbound traffic for your AWS EC2 terraform instance. To configure security groups using Terraform, you’ll define the rules and permissions. Here’s an example:
resource "aws_security_group" "my_sg" {
  name        = "my-security-group"
  description = "Allow inbound SSH and HTTP traffic"
  ingress {
    from_port   = 22
    to_port     = 22
    protocol    = "tcp"
    cidr_blocks = ["0.0.0.0/0"]
  }
  ingress {
    from_port   = 80
    to_port     = 80
    protocol    = "tcp"
    cidr_blocks = ["0.0.0.0/0"]
  }
  egress {
    from_port   = 0
    to_port     = 0
    protocol    = "-1"
    cidr_blocks = ["0.0.0.0/0"]
  }
}

In the above code, we define an AWS security group resource with inbound rules to allow SSH and HTTP traffic, and an outbound rule to allow all traffic. Adjust the rules according to your specific requirements.

  • Defining an EC2 Instance
    Now that we have the networking infrastructure and security groups set up, let’s define the EC2 terraform instance itself. Here’s an example:
resource "aws_instance" "my_instance" {
  ami           = var.ec2_ami
  instance_type = var.ec2_instance_type
  subnet_id     = aws_subnet.my_subnet.id
  vpc_security_group_ids = [aws_security_group.my_sg.id
  tags = {
    Name = "my-ec2-instance"
  }
}

In the above code, we define an AWS EC2 terraform instance resource with the specified AMI (Amazon Machine Image), instance type, subnet, and security group. Also, we assigned a tag to the instance for identification.

Check out the Terraform Interview Questions to prepare for the interviews.

Initializing and Applying the Terraform Configuration

After writing the Terraform code, you need to initialize the project by running the following command:

terraform init

This command initializes the working directory, downloads the necessary provider plugins, and sets up the backend configuration.

To apply the Terraform configuration and create the EC2 terraform instance, run the following command:

terraform apply

Terraform will show you the execution plan, including the resources to be created, modified, or destroyed. If everything looks good, you can confirm the plan, and Terraform will provision your EC2 instance.

Bootcamp in Cloud Computing and DevOps

Accessing and Managing Your EC2 Instance

Accessing and Managing Your EC2 Instance

By following the below mentioned steps, you can effectively manage the lifecycle of your EC2 instances, connect to them securely via SSH, and clean up the resources when they are no longer needed. 

Connecting to Your Instance via SSH

Once you have successfully launched an EC2 instance using Terraform, the next step is to connect and manage. The most common method to access your EC2 instance is through SSH (Secure Shell), which provides a secure and encrypted connection between your local machine and the remote server.

To connect to your AWS EC2 terraform instance via SSH, you’ll need the public IP address or public DNS name of the instance, along with the private key file (.pem) you specified during instance creation. Follow these steps to establish an SSH connection:

  1. Open your preferred terminal application and navigate to the directory where your private key file is stored.
  2. Set the permissions of the private key file to restrict access:
chmod 400 key.pem
  1. Connect to your EC2 instance using SSH and the private key file:
ssh -i key.pem ec2-user@<public-ip-or-dns>

Note: Replace “key.pem” with the actual name of your private key file, and “<public-ip-or-dns>” with the IP address or DNS name of your EC2 instance.

  1. If prompted, confirm the SSH fingerprint authenticity.

    Congratulations! You are now connected to your EC2 instance via SSH and have full control over it.

Managing the EC2 Instance Lifecycle

Once you have access to your terraform EC2 instance, you can manage its lifecycle according to your requirements. Here are some important management tasks:

  • Starting and Stopping the Instance
    You can start and stop your AWS EC2 terraform instance according to the requirement. This allows you to save costs by stopping the instance when it’s not in use and starting it again when required. You can use the AWS Management Console, AWS CLI, or SDKs to control the instance’s state.
  • Rebooting the Instance
    Rebooting an EC2 instance can be useful if you need to troubleshoot or perform maintenance tasks. Rebooting doesn’t change the instance’s public or private IP address.
  • Terminating the Instance
    When you no longer need an EC2 instance, you can terminate it to stop incurring costs. Terminating an instance permanently deletes all data on it, so make sure to back up any important data beforehand. You can terminate an instance using the AWS Management Console, CLI, or SDKs.

Cleaning Up and Destroying Resources

Cleaning up and destroying AWS resources is an essential step to prevent unnecessary costs and maintain a tidy infrastructure. Here’s how you can clean up the resources created by your AWS EC2 terraform instance:

  • Terminating the EC2 Instance
    As mentioned earlier, terminating the terraform EC2 instance will remove it permanently, including any associated storage and data. Make sure to take backups if needed before terminating the instance.
  • Removing Terraform Resources
    To ensure that all resources created by Terraform are properly destroyed, you need to run the terraform destroy command. This command will analyze the Terraform state and remove all the resources managed by Terraform, including the VPC, subnet, security groups, and any other resources defined in your Terraform configuration.

    Run the following command in the directory where your Terraform project is located:
terraform destroy

Confirm the destruction when prompted, and Terraform will proceed with removing the resources.

Conclusion

Creating an AWS EC2 instance with Terraform provides an efficient and scalable way to deploy virtual servers in the cloud. Throughout this guide, we have covered the basics of AWS EC2 and Terraform, from setting up your AWS account and configuring Terraform to writing infrastructure as code and managing the EC2 instance lifecycle.

By using Terraform, you can define your infrastructure in code, enabling you to version control, automate, and replicate your infrastructure across different environments. With the power of Terraform modules, you can easily reuse and share infrastructure configurations, reducing duplication and promoting consistency.

Visit our AWS Community for additional information if you’re still unsure about AWS.

Course Schedule

Name Date Details
AWS Certification 11 May 2024(Sat-Sun) Weekend Batch
View Details
AWS Certification 18 May 2024(Sat-Sun) Weekend Batch
View Details
AWS Certification 25 May 2024(Sat-Sun) Weekend Batch
View Details