Hands-on Infrastructure as Code: AWS Deployment with Terraform

I've been building a DevOps automation project on my GitHub page to showcase how Terraform, Ansible and Docker can be used together to quickly deploy, and automate the configuration of assets using Infrastructure as Code (IaC).
Set up local environment variables
For this project, I'm building on AWS. In order to use Terraform, I need to set up environment variables to store my AWS Access Key IDand then my AWS Secret Access Key. It's super important not to share these, or store them in a script that later gets pushed to GitHub.
$ export AWS_ACCESS_KEY_ID=<your_aws_key>
$ export AWS_SECRET_ACCESS_KEY=<your_secret_key>
Main configuration file
Once the local variables are set, two files will be required to create an EC2 instance on AWS through IaC. First, the main.tf
file.
terraform {
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 4.16"
}
}
required_version = ">= 1.2.0"
}
provider "aws" {
region = var.aws_region
}
resource "aws_instance" "app_server" {
ami = var.ami_id
instance_type = var.instance_type
tags = {
Name = "DevOpsDemoInstance"
}
}
Next, it's time to define a variables.tf
file that will store the variables used by main.tf
during execution. For simple deployments, like this one, it would be enough to declare the variables in the main.tf
file. However, for more complex projects, or when better organisation is needed, or the configuration will be reused, it's best practice to use a variables.tf
file. For that reason, that's the approach used here since this is a learning exercise.
Variables file
variable "aws_region" {
description = "AWS region"
type = string
default = "ap-southeast-2"
}
variable "instance_type" {
description = "EC2 instance type"
type = string
default = "t2.micro"
}
variable "ami_id" {
description = "The AMI ID for the EC2 instance"
type = string
default = "ami-0b0a3a2350a9877be"
}
Finally, the next thing is to initialise the directory using terraform init
, and then create the infrastructure using terraform apply
and reviewing what will be built. Once satisfied, select yes
and your AWS infrastructure will be provisioned. Once the proof-of-concept is finished, remember to use terraform destroy
to tear down your infrastructure.
Subscribe to my newsletter
Read articles from Bernie Camejo directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
