In this article we are going to Learn the steps to launch an EC2 instance using Terraform.

Introduction:

In the world of cloud computing and infrastructure as code (IaC), provisioning resources with ease and consistency is paramount. In this tutorial, we’ll explore how to create an Amazon Elastic Compute Cloud (EC2) instance using Terraform, a popular IaC tool. By the end of this guide, you’ll be able to launch your own EC2 instance with just a few simple commands.

Prerequisites:

Before we dive into the tutorial, ensure you have the following prerequisites in place:

  • An AWS account with an IAM user and the necessary permissions.
  • Terraform installed on your local machine. You can download it from the official website.
  • AWS CLI installed and configured with your IAM user credentials.

Steps to Launch an EC2 Instance using Terraform

Step 1: Setting Up Your Working Directory

To get started, let’s create a dedicated directory for our Terraform project and navigate to it in the terminal:

mkdir terraform-ec2
cd terraform-ec2

Step 2: Creating a Terraform Configuration File

Inside your project directory, create a new Terraform configuration file (e.g., ec2-instance.tf) to define your EC2 instance:

# Define the AWS provider
provider "aws" {
  region = "ap-south-1" # Change to your desired AWS region
  access_key = "AKIA2C3YBHP4NQNKZ3P2"
  secret_key = "dT1W0BM1MuYpCFT4yr1S4urqz0iG8lJ46uvLr7g8"
}

# Create a basic EC2 instance
resource "aws_instance" "Myfirst-ec2-instance-using-terraform" {
  ami           = "ami-0f5ee92e2d63afc18" # ubuntu 22.04  AMI ID (Change to your desired AMI)
  instance_type = "t2.micro"             # EC2 instance type
  key_name      = "your-key-pair-name"   # Name of your SSH key pair

  tags = {
    Name = "MyEC2Instance" # Replace with a name for your instance
  }
}

In this configuration, we specify the AWS region, the Amazon Machine Image (AMI) for ubuntu, and the EC2 instance type. Customize these values according to your preferences.

Step 3: Initializing the Terraform Workspace

Before we proceed, we need to initialize the Terraform workspace. Run the following command:

terraform init

output:

Initializing the backend...

Initializing provider plugins...
- Finding latest version of hashicorp/aws...
- Installing hashicorp/aws v5.19.0...
- Installed hashicorp/aws v5.19.0 (signed by HashiCorp)

Terraform has created a lock file .terraform.lock.hcl to record the provider  
selections it made above. Include this file in your version control repository
so that Terraform can guarantee to make the same selections by default when   
you run "terraform init" in the future.

Terraform has been successfully initialized!

This command will download the necessary provider plugins and set up your working directory for Terraform.

Step 4: Review and Apply Changes

Now, let’s review the changes Terraform will make to your infrastructure using the plan command:

terraform plan

Output:

Terraform used the selected providers to generate the following execution plan. Resource actions are indicated with the following symbols:      
  + create

Terraform will perform the following actions:

  # aws_instance.Myfirst-ec2-instance-using-terraform will be created
  + resource "aws_instance" "Myfirst-ec2-instance-using-terraform" {
      + ami                                  = "ami-0f5ee92e2d63afc18"
      + arn                                  = (known after apply)
      + associate_public_ip_address          = (known after apply)
      + availability_zone                    = (known after apply)
      + cpu_core_count                       = (known after apply)
      + cpu_threads_per_core                 = (known after apply)
      + disable_api_stop                     = (known after apply)
      + disable_api_termination              = (known after apply)

      + user_data_replace_on_change          = false
      + vpc_security_group_ids               = (known after apply)
    }

Plan: 1 to add, 0 to change, 0 to destroy.

Carefully examine the plan to ensure it aligns with your expectations. If everything looks good, apply the changes to create the EC2 instance:

terraform apply
Plan: 1 to add, 0 to change, 0 to destroy.

Do you want to perform these actions?
  Terraform will perform the actions described above.
  Only 'yes' will be accepted to approve.

  Enter a value: yes

aws_instance.Myfirst-ec2-instance-using-terraform: Creating...
aws_instance.Myfirst-ec2-instance-using-terraform: Still creating... [10s elapsed]
aws_instance.Myfirst-ec2-instance-using-terraform: Still creating... [20s elapsed]
aws_instance.Myfirst-ec2-instance-using-terraform: Still creating... [30s elapsed]
aws_instance.Myfirst-ec2-instance-using-terraform: Creation complete after 31s [id=i-0b7268eba21ce83a7]

Apply complete! Resources: 1 added, 0 changed, 0 destroyed.

You’ll be prompted to confirm the changes; type yes and press Enter to proceed.

Step 5: Verifying the EC2 Instance

Once Terraform completes the apply process, it will display information about the created resources. Look for the public_ip or public_dns of your EC2 instance in the output.

Step 6: Accessing Your EC2 Instance

To access your EC2 instance, SSH into it using the public_ip or public_dns:

ssh -i /path/to/your/key.pem ec2-user@<your-instance-public-ip>

Replace /path/to/your/key.pem with the path to your SSH key and <your-instance-public-ip> with the EC2 instance’s address.

Step 7: Destroying Resources (Optional)

If you want to remove the resources created by Terraform, you can use the terraform destroy command:

terraform destroy

output:

Plan: 0 to add, 0 to change, 1 to destroy.

Do you really want to destroy all resources?
  Terraform will destroy all your managed infrastructure, as shown above.
  There is no undo. Only 'yes' will be accepted to confirm.

  Enter a value: yes

aws_instance.Myfirst-ec2-instance-using-terraform: Destroying... [id=i-0b7268eba21ce83a7]
aws_instance.Myfirst-ec2-instance-using-terraform: Still destroying... [id=i-0b7268eba21ce83a7, 10s elapsed]
aws_instance.Myfirst-ec2-instance-using-terraform: Still destroying... [id=i-0b7268eba21ce83a7, 20s elapsed]
aws_instance.Myfirst-ec2-instance-using-terraform: Destruction complete after 30s

Destroy complete! Resources: 1 destroyed.

Use this command with caution, especially in production environments.

Conclusion:

Congratulations! You’ve successfully created an EC2 instance using Terraform, automating the provisioning process with ease. This Infrastructure as Code approach simplifies resource management and is a fundamental skill for DevOps and cloud professionals.

This tutorial provides a foundation for working with Terraform and AWS. Explore Terraform’s extensive capabilities to manage complex infrastructures effortlessly. We hope this guide has been helpful on your journey to mastering Terraform and creating AWS resources programmatically.

Happy provisioning!

Reference:

Please visit the official website of Terraform

Any queries pls contact

@Rushi-InfoTech

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *