🌿let's Create A Small Project Using Terraform🌿

🌿let's Create A Small Project Using Terraform🌿

🔎IN THIS PROJECT I CREATED A SMALL INFRASTRUCTRE ON AWS USING TERRAFORM,WHAT WE HAVE GOING TO CREATE:- AWS EC2 SERVER WITH EBS VOLUME AND PRE-INSTALLED NGINX .

1. Install Terraform

If you haven’t already installed Terraform on your local machine. You can download it from the official website: https://developer.hashicorp.com/terraform/downloads

Make sure to set up environment variables so that you can use Terraform for all instances of the directory. After installing Terraform, you can confirm if it’s installed by opening a command prompt or terminal and typing: terraform version

2. Configure AWS Credentials

I’ll be creating a new IAM user on AWS to enhance security and avoid using the admin account for regular tasks.

  • Create a New IAM User
    -> Log in to your AWS Management Console > Search “IAM”
    -> In the IAM dashboard, click on “Users” in the sidebar
    -> Click the “Create user” button > Choose a username for the new user
    -> Create Group for “Admin Access” > Add user to the group
    -> Click Next > Next > Click on the user that you’ve created just now.
    -> Click on “Create access key” > Select Use case as “Local code” > Next
    -> A confirmation page will display the “Access key ID” and “Secret access key” for the user.

Important: Make sure to save the secret access key in a secure location. It’s only shown once. If you lose it, you’ll need to generate a new key pair.

  • Create a Directory for Your Project This is where you’ll store your configuration files.

  • Use AWS credentials You’re now ready to use these credentials to deploy an EC2 instance using Terraform. Terraform offers multiple ways to authenticate, but we’ll focus on three common methods: directly hardcoding credentials (not recommended), using the AWS CLI, and using environment variables.

Hardcoding credentials (not recommended):

# Configure the AWS Provider
provider "aws" {
  region     = "us-east-1"
  access_key = "AKIA----------"
  secret_key = "9dIj-------------------------"
}

AWS CLI (recommended):

By running the aws configure command, you can set your credentials for the current environment. Terraform will then use these credentials for authentication. Ensure you have the AWS CLI installed and configured.

Using Environment Variables:

Environment variables are another secure way to provide credentials to Terraform. Set the following environment variables before running Terraform commands:

Windows:

set AWS_ACCESS_KEY_ID=Your_Access_Key
set AWS_SECRET_ACCESS_KEY=Your_Secred_Access_Key
set AWS_DEFAULT_REGION=Your_AWS_Region

Mac or Linux Flavours:

export AWS_ACCESS_KEY_ID=Your_Access_Key 
export AWS_SECRET_ACCESS_KEY=Your_Secred_Access_Key 
export AWS_DEFAULT_REGION=Your_AWS_Region

3. Write the Terraform Configuration to deploy an EC2 instance

Use a provider.tf file to define the configuration for a specific ☁️ or service provider. This file specifies the 🔑, endpoints, and other settings required for Terraform to interact with that provider’s API and manage resources.

terraform {
  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 5.0"
    }
  }
}

# Configure the AWS Provider
provider "aws" {
  region = "us-east-1"
}

🔐 Creating an SSH key pair on your local system serves as a secure and convenient method for authenticating yourself when connecting to remote servers, such as instances on AWS 🔑and We installing nginx on ec2 for installing nginx server on ec2 .terraform need a key to connect ec2 server.

This will generate terra-key*and **terra-key.pub files in our current directory. you can check using ls command.We will add the Public Key (**terra-key.pub) to the AWS instance and use the Private key (terra-key**) to authenticate ourselves when connecting to remote servers using SSH.*

you can Store your both private and public key in a separate directory(Keys)

Now, we will be creating variables.tf and terraform.tfvars files

🌟Create terraform.tfvars and put your own key path ..

Here,the terraform.tfvars configuration file.

key_pair_public_key_path = "C:/Users/HP/Documents/devops/terra-project/ec2/keys/terra-key.pub"
private_key_path         = "C:/Users/HP/Documents/devops/terra-project/ec2/keys/terra-key"
ami_id                   = "ami-0cd59ecaf368e5ccf"
instance_type            = "t2.micro"
ssh_user                 = "ubuntu"
vpc_cidr_block           = "0.0.0.0/0"
ebs_volume_size          = 2
ebs_device_name          = "/dev/xvdb"

These files play distinct roles and help improve the maintainability and flexibility of our Terraform configurations.

The variables.tf file is used to define input variables that will be used throughout your Terraform configuration. Input variables allow you to parameterize your code and make it more dynamic.

The terraform.tfvars file is used to assign specific values to the input variables defined in variables.tf. It provides a way to set values for these variables without modifying the main Terraform code. This is especially useful when working in a team or when deploying infrastructure for different environments.

📚Now,Create a Variables.tf file

variable "key_pair_public_key_path" {}
variable "private_key_path" {}
variable "ami_id" {}
variable "instance_type" {}
variable "ssh_user" {}
variable "vpc_cidr_block" {}
variable "ebs_volume_size" {}
variable "ebs_device_name" {}

📚Now create a main.tf file

Here, the terraform main.tf configuration file

🌟main.tf:

resource "aws_key_pair" "key_pair" {
  key_name   = "terra-key"
  public_key = file(var.key_pair_public_key_path)
}

resource "aws_default_vpc" "default" {}

resource "aws_security_group" "terra_sg" {
  name   = "my-security-group"
  vpc_id = aws_default_vpc.default.id

  ingress {
    description = "SSH access"
    from_port   = 22
    to_port     = 22
    protocol    = "tcp"
    cidr_blocks = [var.vpc_cidr_block]
  }

  ingress {
    description = "HTTP access"
    from_port   = 80
    to_port     = 80
    protocol    = "tcp"
    cidr_blocks = [var.vpc_cidr_block]
  }

  egress {
    description = "Outgoing traffic"
    from_port   = 0
    to_port     = 0
    protocol    = "-1"
    cidr_blocks = [var.vpc_cidr_block]
  }
}

resource "aws_instance" "web" {
  ami           = var.ami_id
  instance_type = var.instance_type
  key_name      = aws_key_pair.key_pair.key_name
  security_groups = [aws_security_group.terra_sg.name]

  tags = {
    Name = "terra-instance"
  }

  provisioner "remote-exec" {
    inline = [
      "sudo apt update",
      "sudo apt install nginx -y",
      "sudo systemctl start nginx"
    ]
  }

  connection {
    type        = "ssh"
    user        = var.ssh_user
    private_key = file(var.private_key_path)
    host        = self.public_ip
  }
}

resource "aws_ebs_volume" "myebsvol" {
  availability_zone = aws_instance.web.availability_zone
  size              = var.ebs_volume_size
  # You can customize other properties of the EBS volume here
}

resource "aws_volume_attachment" "ebs_att" {
  device_name = var.ebs_device_name
  instance_id = aws_instance.web.id
  volume_id   = aws_ebs_volume.myebsvol.id
}

🌟Now save all these files and apply the configurations

🔎TO CHECK SYNTAX:

terraform validate

🔎TO CHECK WHAT IS GOING TO CREATE,MODIFY AND DESTROY:

terraform plan

🔎APPLY CONFIGURATION:

terraform apply

📝Now, Go to AWS EC2 and check ec2 server is created or not with EBS Volume and copy public ip and paste on browser to check nginx is running or not.