Kole  Haag

Kole Haag

1603213200

Using Terraform to Create an EC2 Instance With Cloudwatch Alarm Metrics

Hey guys! I wanted to do a quick tutorial on how I created an EC2 module for Terraform. If you want to see the repository it is located in check it out here. This module will do a few things:

  1. Create an EC2 Instance
  2. Automatically look up the latest Windows Server 2019 AMI for the EC2 instance.
  3. Create and attach a additional drive.
  4. Create a Cloudwatch Alarm Metric to monitor CPU.

The folder structure looks like this:

Image for post

First things first… I created the main.tf file which contains all of my configuration except for the variables and outputs. The main.tf has a few parts to it.

AWS Instance Code

The first section is the instance resource code

#AWS Instance

resource "aws_instance" "example" {
     ami = data.aws_ami.windows.id
     instance_type = "t2.micro"
     availability_zone = var.availability_zone
}

You will notice a few things here.

  1. The instance type is set in the module to t2.micro
  2. availability_zone is set using a variable
  3. ami is set using data

We will get the the availability zone piece in just a bit, first we are going to tackle the data used for the ami argument.

Data for AMI Using a Filter

The next bit of code for the filter looks like this

#AMI Filter for Windows Server 2019 Base

data "aws_ami" "windows" {
     most_recent = true
     filter {
       name   = "name"
       values = ["Windows_Server-2019-English-Full-Base-*"]
  }
     filter {
       name   = "virtualization-type"
       values = ["hvm"]
  }
     owners = ["801119661308"] ## Canonical
}

The argument most_recent is set to true. This means that it will grab the most recent AMI that fits the criteria that we specify in our filter.

Next you will notice that in the name we set the value to *Windows_Server-2019-English-Full-Base- **with the star at the end. This lets Terraform know we don’t care about what text comes after that point and it was done because the standard format puts the date there. If we set the date the ami was created and set the most_recent argument to true it would not do us any good.

After that we set the virtualization-type to hvm. I am not going to go into a lot of detail here. Just know this is a good idea and do some additional research on hvm vs pv.

Last we set **owners **to 801119661308.

Now I am sure you are asking… how the heck do I actually get this information? Well you are going to have to run a quick command with the AWS cli.

First, login to AWS and get the ami you want to grab the information for. Here is an example:

Image for post

If you click on launch instance you can do a search.

#aws-ec2 #hashicorp-terraform #aws-cloudwatch #terraform-modules #terraform

Using Terraform to Create an EC2 Instance With Cloudwatch Alarm Metrics