Terraform, Lambda, and Event Bridge: The perfect trio for AWS cost optimization
Tags: terraform, awsinstance, awscostcontrol, awslambda
Published: 2023-04-29 15:51:31

If you're reading this, perhaps it's not too late. Chances are, however, that you've experienced the dread of receiving an unexpectedly large cloud bill. Alternatively, you may be new to AWS, and this article can help you avoid making the same mistake. In our industry, it's all too easy to fall prey to common mistakes, such as leaving an EC2 instance running for too long, resulting in costly charges that can quickly accumulate. That's why I've written this article, to assist you in avoiding these financial headaches and taking advantage of a more efficient and cost-effective infrastructure. 

Have you ever seen the meme of two men talking? One is dressed nicely and asks the second, who looks like a homeless person, **"How did you end up homeless? Gambling or drugs?"** The second man responds, **"I left an EC2 instance on."** Unfortunately, for those of us in the tech industry, we know all too well the not-so-funny reality behind this joke. One of the biggest culprits is accidentally leaving an EC2 instance up and running, resulting in sky-high bills that can quickly drain a budget. 

![money burn](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3gfygk9am2u5pssvwmkq.jpeg)

Don't worry, I've got your back. In this article, you will discover a solution that can help you avoid this financial nightmare. We will explore the benefits of a fully serverless infrastructure using AWS Lambda and AWS Event Bridge. Implementing this powerful combination not only offers fascinating possibilities but also has the potential to save you and your company thousands of dollars in unnecessary charges. 

![money save](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/bdjveg6dpywst2h75gkc.jpeg)

Before we dive into the details, if you're unfamiliar with AWS Instances or EC2, I recommend checking out my previous article where I explained what EC2 is and how to deploy them using Terraform. You will need the instance ID's to complete this article. [Here's the link to the article](https://dev.to/aws-builders/how-to-create-a-fleet-of-aws-ec2s-with-terraform-595l) return when you're ready to continue. 

Now that you're back, this article assumes you have some basic knowledge of EC2, AWS Lambda, and Event Bridge. Let's get to the fun part, let me describe what this deployment will look like. We will be using Terraform to manage our infrastructure as code. Terraform is an open-source tool that allows you to define your infrastructure in code, making it easier to maintain, version, and share. By using Terraform, we can easily create and manage our AWS resources, including our EC2 instance, Event Bridge, and Lambda functions. 

Our architecture will consist of two Lambda functions - one to start the EC2 instance and another to stop it. These functions will be triggered by two Event Bridge rules on a cron schedule, allowing us to automate the starting and stopping of our EC2 instance at a specific time every day. 

**Infrastructure diagram:**

![Diagram](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lgxjmhiu2u5ucnjs5toi.png)

**Lambda code previous:**

```
data "template_file" "ec2_start_large" {
  count = length(local.source_files)

  template = file(element(local.source_files, count.index))
}

data "archive_file" "ec2_start_large_events" {
  type        = "zip"
  output_path = "start.zip"

  source {
    content  = data.template_file.ec2_start_large.0.rendered
    filename = basename(local.source_files[0])
  }


}

resource "aws_lambda_function" "ec2_start_large_lambda" {
  description = "EC2 large EC2"
  function_name    = "start-ec2-large"
  handler          = "start.handler"
  filename         = "${data.archive_file.ec2_start_large_events.output_path}"
  source_code_hash = "${data.archive_file.ec2_start_large_events.output_base64sha256}"
  role             =  aws_iam_role.lambda_role.arn
  memory_size      = 128
  runtime          = "python3.9"
  timeout          = 3
  publish  = true
  depends_on = [
    aws_iam_role_policy_attachment.role_policy_login_attch
]

  tracing_config {
    mode = "PassThrough"
  }

   tags = {
    Project = "large_ec2"
  }
}

```


**EventBridge code previous:**

```
resource "aws_cloudwatch_event_rule" "start_event_rule" {
    name = "start-large-ec2"
    schedule_expression = "cron(0 12 * * ? *)"

    tags = {
    Project = "large_ec2"
  }
}

```

Using Lambda functions, we can execute code without having to worry about provisioning or managing servers, further reducing our costs. Additionally, leveraging EventBridge will allow us to easily manage our events and automate our workflows, improving our efficiency and reducing the risk of human error.  

I think it's time for a break. Let's stretch our legs or grab a coffee. In the next section, we will cover our project and provide a detailed GitHub repository that includes a step-by-step guide on how to complete and master this serverless infrastructure. In the meantime, if you know someone who could benefit from this article, please share it, or leave a comment below with your thoughts. 

**_See you soon and remember to terminate your EC2 instances if you are no longer using them_😉!**

## Conclusion

Congratulations! 

You have reached the conclusion of this blog on achieving AWS cost optimization with Terraform, AWS Lambda, and Event Bridge. By leveraging the power of infrastructure as code, serverless functions, and event-driven architectures, you are well equipped to optimize costs without compromising performance or functionality.

But the journey doesn't end here. I'm excited to announce that I have created the final part of this blog, a comprehensive GitHub repository that encapsulates all the necessary steps and resources to complete this mini project effortlessly. This repository serves as a practical guide, providing you with code samples, configuration files, and detailed instructions.

With this repository at your fingertips, you'll have everything you need to dive deeper into AWS cost optimization. It's time to put your newfound knowledge into action, automate common tasks, and unlock the full potential of your AWS infrastructure.

Whether you're a seasoned developer or just starting your DevOps journey, this repository is designed to be friendly and accessible. The step-by-step instructions and intuitive examples will empower you to make informed decisions and achieve tangible cost savings.

Remember, cost optimization is an ongoing process. Keep exploring, experimenting, and fine-tuning your resources. And as you embark on this exciting adventure, don't hesitate to reach out for assistance or share your experiences with the vibrant community of AWS enthusiasts.

[GitHub Repository Here] (https://github.com/ValAug/serverless-AWS-cost-optimization)