Episode 2.3 : Deploying a Cluster of Web Server with Terraform

December 5, 2024 (4d ago)

Episode 2.3 : Deploying a Cluster of Web Server with Terraform

Hi there, It's Dilan 🤓!

In this second episode of the blog series, after what we saw on the previous episode we will now continue with deploying a cluster of web servers with Terraform on AWS.

But before we beging let's make sure we are on the same page, so in the previous articles, we have deployed a single server and then a configurable web server using the power of variables and now we are tyring to deploy a cluster (or group) of web servers.

But why do we even need a cluster of servers? Can't we handle everything with our one single server of before? the answer to this question is NO, why? Because imagine you have your application on that one server, one night suddently the server craches (yeah it can happen) and your application dies with it. What will you do? Your users won't be able to access your app for a while.That's what we call single point of faillure, when you have in your system one component that when it's dammaged, the whole system will suffer, and that's the type of design to avoid.

AWS povides us with what they call Auto Scalling Group (ASG) wwhich automatically adjust the size of the cluster in response to load.

The first thing we need to do is tell our ASG what type of EC instance we want to run on each server on the cluster , and to do that we can use a launch configuration.

It's comparable to the aws_instance resource, but here we don't have tags, and no need for user_data_replace_on_change since ASG will launch new instances by default so we don't need the parameter.

Note also that ami changes to image_id and vpc_security_group_ids to **security_groups`.

resource "aws_launch_configuration" "example" {
   image_id = "ami-0453ec754f44f9a4a"
   instance_type = "t2.micro"
 
   security_groups = [ aws_security_group.instace.id]
   user_data                   = <<-EOF
             #!/bin/bash
             netstat -tlpen | grep 8080
             echo "Hello World!" > index.html
             nohup busybox httpd -f -p ${var.server_port} &
             EOF
}

After the creation of the launch configuration, let's create the ASG itself:

resource "aws_autoscalling_group" "example" {
   launch_configuration = aws_launch_configuration.example.name
   // Run between 2 and 10 EC2 instances
   min_size = 2
   max_size = 10
 
   tag {
       key  = "Name"
       value = "terraform-asg-example"
       propagae_at_launch = true
   }
}

It's all for today, and just like that you made you code DRY by using variables!!


It was Dilan, GDGoC ( Google Developer Groups On Campus) Lead. See you soon! 👋