Deploy Nginx in EC2 and expose it using load-balancer

First let's genrate an ssh key.

In your terminal write the following command
ssh-keygen -t rsa
Then it will ask about the folder where it should be install (./id_rsa).

Now let's create a key_pair in main.tf file.

resource "aws_key_pair" "key-tf" {

key_name = "key-tf"

public_key = file("${path.module}/id_rsa.pub") }

Now let's create a security group.

resource "aws_security_group" "allow_tls" { name = "allow_tls" description = "Allow TLS inbound traffic"

ingress { description = "TLS from VPC" from_port = 22 to_port = 22 protocol = "tcp" cidr_blocks = ["0.0.0.0/0"] ipv6_cidr_blocks = ["::/0"] }

ingress { description = "TLS from VPC" from_port = 80 to_port = 80 protocol = "tcp" cidr_blocks = ["0.0.0.0/0"] ipv6_cidr_blocks = ["::/0"] }

ingress { description = "TLS from VPC" from_port = 443 to_port = 443 protocol = "tcp" cidr_blocks = ["0.0.0.0/0"] ipv6_cidr_blocks = ["::/0"] }

egress { from_port = 0 to_port = 0 protocol = "-1" cidr_blocks = ["0.0.0.0/0"] ipv6_cidr_blocks = ["::/0"] }

}

Here ingress means an inbound rule to allow incoming traffic. So that we can SSH into the instance.

Egress means an outbound rule to allow outgoing network traffic from a resource.
So that we can install the nginx.

Now let's write a code for EC2 instance.

data "aws_ami" "ubuntu" { most_recent = true

filter { name = "name" values = ["ubuntu/images/hvm-ssd/ubuntu-focal-20.04-amd64-server-*"] }

filter { name = "virtualization-type" values = ["hvm"] }

owners = ["099720109477"] # Canonical }

resource "aws_instance" "example_instance" { ami = data.aws_ami.ubuntu.id instance_type = "t2.micro" #subnet_id = aws_subnet.public_subnet.id key_name = "${aws_key_pair.key-tf.key_name}"

vpc_security_group_ids = ["${aws_security_group.allow_tls.id}"] tags = { Name = "HelloWorld" } user_data = <<EOF #!/bin/bash sudo apt-get update sudo apt-get install nginx -y EOF

}

Here user_data means whenever the instance is created run the following command.
So we have update the package and install the nginx

Now if we want to verify that instance is being created or not without console.
We can ssh into the instance.
ssh -i id_rsa ubuntu@3.86.89.65

Now let's create a Load-balancer

Create a new load balancer

resource "aws_elb" "bar" { name = "terraform-elb" availability_zones = ["ap-south-1a"]

listener { instance_port = 8000 instance_protocol = "http" lb_port = 80 lb_protocol = "http" }

health_check { healthy_threshold = 2 unhealthy_threshold = 2 timeout = 3 target = "HTTP:8000/" interval = 30 }

instances = ["${aws_instance.example_instance.id}"] cross_zone_load_balancing = true idle_timeout = 40

tags = { Name = "terraform-elb" } }

This is a very rough blog post, if you hate it feel free to leave a comment as to what you hated, if you liked it feel free to leave a comment as to why you liked it.