How to Install Terraform on AWS EC2

Image of a computer screen with multi-colored lines of code.
Get started using Terraform on AWS today!

Terraform is a very popular infrastructure as a code (IaaC) platform. This IaaC makes it easy for you to provision resources through writing a development framework for your code. This includes protocols for databases, virtual machines, and then executing the apply command. In addition, Terraform is a declarative language solution that helps guide your development work using a high-level coding aproach. In other words, you tell it what you want, and it will populate the rest of the code. This saves you a ton of time and extra coding. 

In this tutorial, you’ll start using Terraform by creating an AWS virtual machine EC2 instance. You’ll learn how to install it, connect it to AWS, provision some infrastructure, and finally, destroy it. 

Now let’s jump in and find out what you need to start using Terraform.

Get Azure DevOps News

AWS Prerequisites

Before starting this tutorial, make sure you have the following for AWS:  

  1. AWS Account 
  2. An EC2 Instance
  3. Root access for the AWS servers under your account
  4. An ‘access_key’ and the ‘secret_key’ for your AWS IAM User 

Now that you have all the prerequisites out of the way, let’s install Terraform!

Installing Terraform 

Depending on your machine image you’ll need to download a binary image that suits your OS from the Terraform Downloads site. For the sake of this tutorial let’s assume we’re using a Linux/Mac OS. Before downloading it, you’ll want to make a directory for it on your EC2 instance. CD where you want to go and then:

mkdir terraform

cd terraform

Then install terraform to your newly created directory. Once you download it and unzip it, look for the Terraform binary file, then move it to: user/local/bin. Then check the version to see if it’s working. Use the commands below: 

mv terraform /user/local/bin/

terraform -v

Congratulations! You’ve successfully installed Terraform on your EC2 instance! Now, let’s write some code and create the files you’re going to need to get started.

Creating Terraform Configuration Files 

Use an editor of your choice; I prefer VS Code with the HashiCorp Terraform extension installed. That way, if I make a mistake or a syntax error, the extension will underline it for me. Trust me, this saves countless hours of head scratching wondering what the heck is wrong. 

You’ll want to create three configuration files for Terraform: 

  1. variables.tf
  2. terraform.tfvars
  3. main.tf

Let’s start with the main.tf first. 

Image of a tall building's infrastructure being erected
Start building an infrastructure framework with Terraform!

Main.tf

You’ll want to copy and paste this code block. This is your main file that you’ll use to write infrastructure code. Keep in mind some things you might want to change depending on your configuration, such as port numbers, cidr_blocks, etc. You’ll want to double check your EC2 instance info in the AWS console before applying any changes. 

provider “aws” {

      region     = “${var.region}”

      access_key = “${var.access_key}”

      secret_key = “${var.secret_key}”

}

resource “aws_vpc” “vpc” {

     cidr_block = “10.0.0.0/16”

}

resource “aws_internet_gateway” “gateway” {

     vpc_id = “${aws_vpc.vpc.id}”

}

resource “aws_route” “route” {

     route_table_id         = “${aws_vpc.vpc.main_route_table_id}”

     destination_cidr_block = “0.0.0.0/0”

     gateway_id             = “${aws_internet_gateway.gateway.id}”

}

data “aws_availability_zones” “available” {}

resource “aws_subnet” “main” {

    count                   = “${length(data.aws_availability_zones.available.names)}”

    vpc_id                  = “${aws_vpc.vpc.id}”

    cidr_block              = “10.0.${count.index}.0/24”

    map_public_ip_on_launch = true

    availability_zone       = “${element(data.aws_availability_zones.available.names, count.index)}”

}

resource “aws_security_group” “default” {

     name        = “http-https-allow”

     description = “Allow incoming HTTP and HTTPS”

     vpc_id      = “${aws_vpc.vpc.id}”

     ingress {

         from_port = 80

         to_port = 80

         protocol = “tcp”

         cidr_blocks = [“0.0.0.0/0”]

    }

     ingress {

         from_port = 443

         to_port = 443

         protocol = “tcp”

         cidr_blocks = [“0.0.0.0/0”]

    }

}

Variables.tf

In the variables.tf file you’ll set up your variables names and the description of that variable. The variables don’t have values presented here. You’ll add the actual data values in the terraform.tfvars. See the next section for the tfvars.

variable “access_key” {

     description = “Access key to AWS console”

}

variable “secret_key” {

     description = “Secret key to AWS console”

}

variable “region” {

     description = “Region of AWS VPC”

}

Terraform.tfvars

Here you’ll add in your values from the EC2 instance as shown below. Notice also how the names match with the names in the variables.tf file. 

region = “<your region>”

access_key = “<your access key>”

secret_key = “<your secret key>”

Now that you have written out your configuration files, you’re going to run some commands in the CLI to get terraform to create a virtual personal cloud (VPC). The VPC is based on the infrastructure code you wrote in the main.tf file. 

Running Terraform Commands Using the CLI

You have created your configuration files and now you’re ready to put Terraform to work for you. The first command that you need to run is terraform init. Running this command will initialize Terraform, then download and install all the packages for the providers that you’re using in your file. In this case, your provider is AWS. 

Once you get the green text stating that “Terraform has successfully been initialized,” you can move on to the next command terraform plan. The terraform plan will run the code that you have written and check it all for errors. Once it runs this check and ensures it can do it, the CLI will let you know that your code is good and then you can move to the third command terraform apply. Running this will execute the code and provision a VPC in AWS as written. Go and check the console on AWS to see that your new VPC has been spun up.

Congratulations, you have created your VPC via terraform. Now, for the final trick, one more command that you can run to tear everything down. However, you need to be careful with this command as it will remove everything from your EC2 instance terraform destroy. When you run the command, it will prompt you if you want to continue, say yes. Check your console and see that the VPC has been terminated. 

Final Words

In this brief tutorial you’ve learned how to:

  •  Install terraform on an AWS EC2 instance the primary configuration files
  • Populate them with code 
  • Execute the code with the Terraform CLI commands 

Now, you’ll be able to do more experimentation on your own and get to know Terraform better. Have more questions about Terraform? Check out the FAQ and Resource sections below! 

Get The Latest Windows Server News

FAQ

What is infrastructure as a code (IaaC)?

Infrastructure as a code (IaaC) helps you to deploy software faster on multiple servers in the cloud. It uses code in a modular format to reduce the inconsistencies of software versioning on servers. In addition, increases productivity and lowers development costs. 

What is AWS?

Amazon Web Services (AWS) is an advanced cloud computing service from Amazon. It offers pretty much everything any IT professional would need for enterprise cloud based solutions. To this end, AWS can store data, create VMs, mange security, and create a complete business solution.

What is the Terraform State?

If your team consists of multiple engineers working in Terraform, then think of the state as a software development repository. It also controls access and who can do what. You’ll need to use the terraform apply command to propagate changes.

How many providers does Terraform work with?

More than 100 providers. You can often connect it to anything because of Terraform’s dynamic API. This is only true if the other software you want to use also has an API. 

What is the HCL language?

HashiCorp Configuration Language (HCL) is a programming language by HashiCorp’s. HCL enables you to write code in all of their offerings, including Terraform. The language is visually similar to JSON but has additional support for data structures built in.

Resources  

TechGenix: Terraform 101: a Beginner’s Guide for ARM Template Lovers 

Learn more about using Terraform in this guide here.

TechGenix: What is Infrastructure-as-code and why you should use it 

Learn more about the concept of IaaC here.

Learn about what the future of Cloud computing has in store for your organization here

TechGenix: AWS EKS Anywhere: Amazon’s bid for Hybrid Cloud Supremacy  

Explore AWS EKS hybrid cloud solutions and see what you can do with it here.

TechGenix: AWS Serverless Strategy has Containers Front and Center 

Learn more about AWS serverless options and what they can do for you here

About The Author

Leave a Comment

Your email address will not be published. Required fields are marked *

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

Scroll to Top