Skip to main content

AWS VPC Setup with Terraform

Objective#

Complete the Terraform setup to create an AWS VPC with public and private subnets, launch a bastion EC2 instance in the public subnet, and launch a private EC2 instance in the private subnet.

Gitlab Repository#

Gitlab Repo

Environment Setup#

  1. Install Terraform on your local machine.

  2. Clone the repository containing the Terraform code.

    git clone <repository_url>
  3. Configure AWS Credentials:

    • Create a file named terraform.tfvars in the project directory.
    • Setup AWS credentials using the command:
      aws configure
  4. Customize Infrastructure Configuration:

    • Open the variables.tf file in the project directory.
    • Modify the variables as needed:
      • aws_region: The AWS region to deploy the infrastructure in.
      • vpc_cidr_block: The CIDR block for the VPC.
      • private_subnet_1_cidr_block: The CIDR block for the first private subnet.
      • private_subnet_2_cidr_block: The CIDR block for the second private subnet.
      • public_subnet_cidr_block: The CIDR block for the public subnet.
      • public_ec2_key_name: The key pair name for the public EC2 instance.
      • private_ec2_key_name: The key pair name for the private EC2 instance.
  5. Deploy Infrastructure:

    • Open a terminal and navigate to the project directory.
    • Initialize Terraform:
      terraform init
    • Preview the changes that will be applied:
      terraform plan
    • Apply the Terraform configuration to create the infrastructure:
      terraform apply
      Confirm the changes by typing "yes" when prompted.
  6. Access Bastion Host:

    • Once the infrastructure is created, obtain the public IP of the bastion EC2 instance from the Terraform output.
    • Open a terminal and run the following command to SSH into the bastion host:
      ssh -i id_ed25519 ec2-user@<bastion_public_ip>
    • Create a file named id_ed25519 inside the /home/ec2-user/.ssh/ directory and paste the public IP into it.
    • Change the permissions of the key file:
      chmod 400 id_ed25519
  7. SSH into Private Server:

    • Obtain the private IP of the private EC2 instance from the Terraform output.
    • Open a terminal and run the following command to SSH into the private server:
      ssh -i id_ed25519 ec2-user@<private_ip>
  8. Infrastructure Destruction:

    • To delete the infrastructure and clean up resources, run the following command:
      terraform destroy