For Dummies: What is Terraform? How to use it with AWS?

Anh Dung - Oct 29 - - Dev Community

I. Introduction

1. What is Terraform?

Image description
Source: HashiCorp Developer

Terraform is a powerful tool developed by HashiCorp for managing infrastructure as code (IaC). With Terraform, instead of manually configuring infrastructure, you write code to define how to build and manage infrastructure resources. This makes it easy to reuse, scale, and manage changes.

2. What is AWS?

Amazon Web Services (AWS) is a popular cloud platform offering over 200 services, from virtual servers and storage to databases, AI, and data analytics. AWS enables businesses to build and scale infrastructure flexibly, quickly, and efficiently.

3. Why combine Terraform and AWS?

Combining Terraform with AWS leverages the strengths of both: Terraform automates infrastructure management on AWS, allowing users to deploy, change, and scale without manual intervention. Terraform also reduces human error risk, keeps infrastructure synchronized, and provides easy rollback options.

II. Key Components and Concepts in Terraform AWS

1. Providers

Providers are central in Terraform, enabling it to interact with third-party services. The AWS Provider helps Terraform connect to and manage resources on AWS, like EC2, S3, VPC, etc. Configuring the AWS Provider is straightforward—just provide your AWS account credentials, such as Access Key and Secret Key.

provider "aws" {
  region = "us-west-1"
}
Enter fullscreen mode Exit fullscreen mode

2. Resources

Resources are the actual objects you create and manage on AWS, like an EC2 instance, S3 bucket, or VPC. Resources are the most basic building blocks in a Terraform configuration file.

Example of creating an EC2 instance:

resource "aws_instance" "example" {
  ami           = "ami-0c55b159cbfafe1f0"
  instance_type = "t2.micro"
}
Enter fullscreen mode Exit fullscreen mode

3. Modules

Modules are reusable sets of configuration files that help manage complex configurations and reduce code duplication. By using modules, you can organize Terraform code clearly and make it easier to maintain.

Example of using a module:

module "vpc" {
  source = "terraform-aws-modules/vpc/aws"
  version = "3.0.0"
  ...
}
Enter fullscreen mode Exit fullscreen mode

4. State

Terraform State stores information about the resources it manages. This is an essential component that allows Terraform to track the current state of infrastructure and compare it with the configuration file to apply necessary changes.

Image description

When you run terraform apply, Terraform creates or updates the state file to track the current status of the infrastructure.

Example: When you create an EC2 instance with Terraform, the details of this instance are saved in the state file terraform.tfstate.

provider "aws" {
  region = "us-west-2"
}

resource "aws_instance" "example" {
  ami           = "ami-0c55b159cbfafe1f0"
  instance_type = "t2.micro"
}

Enter fullscreen mode Exit fullscreen mode

After running terraform apply, a terraform.tfstate file is created, storing the state of the EC2 instance, such as its IP address, instance ID, etc. Terraform relies on the state file to determine which resources need to be created or updated.

State File (terraform.tfstate)

{
  "resources": [
    {
      "type": "aws_instance",
      "name": "example",
      "instances": [
        {
          "attributes": {
            "ami": "ami-0c55b159cbfafe1f0",
            "instance_type": "t2.micro",
            "private_ip": "10.0.0.1",
            "public_ip": "3.101.23.14",
            "id": "i-1234567890abcdef"
          }
        }
      ]
    }
  ]
}

Enter fullscreen mode Exit fullscreen mode

5. Variables

Variables make your configuration more flexible by defining changeable values for different environments or resources.

File variables.tf:

variable "instance_type" {
  description = "Instance type for EC2 instance"
  default     = "t2.micro"
}

variable "aws_region" {
  description = "AWS Region"
  default     = "us-west-2"
}
Enter fullscreen mode Exit fullscreen mode

File main.tf

provider "aws" {
  region = var.aws_region
}

resource "aws_instance" "example" {
  ami           = "ami-0c55b159cbfafe1f0"
  instance_type = var.instance_type
}
Enter fullscreen mode Exit fullscreen mode

If no value is provided, Terraform will use the default values in the variables.tf file

terraform apply -var="instance_type=t2.medium" -var="aws_region=us-east-1"
Enter fullscreen mode Exit fullscreen mode

6. Outputs

Outputs are values you can retrieve after Terraform completes deployment, such as the IP address of an EC2 instance or the name of an S3 bucket.

File main.tf:

provider "aws" {
  region = "us-west-2"
}

resource "aws_instance" "example" {
  ami           = "ami-0c55b159cbfafe1f0"
  instance_type = "t2.micro"
}

output "instance_public_ip" {
  description = "The public IP address of the EC2 instance"
  value       = aws_instance.example.public_ip
}
Enter fullscreen mode Exit fullscreen mode

After running terraform apply, you will see output like this:

Apply complete! Resources: 1 added, 0 changed, 0 destroyed.

Outputs:

instance_public_ip = "3.101.23.14"
Enter fullscreen mode Exit fullscreen mode

This output makes it easy to access necessary information without manually searching through the state file or the AWS Console.

III. How Terraform Works with AWS

1. Workflow with Terraform

  • Write Configuration Files: First, write Terraform configuration files in HCL (HashiCorp Configuration Language) to describe the infrastructure you want to deploy.
  • Run terraform init: Initialize the Terraform environment and download the necessary providers.
  • Run terraform plan: Create a plan outlining the changes to be made.
  • Run terraform apply: Execute the plan, deploying or modifying the infrastructure according to the configuration.
  • Update Infrastructure: If changes are needed, just update the configuration file and rerun terraform apply.

2. Example of Deploying Infrastructure on AWS with Terraform

provider "aws" {
  region = "us-west-1"
}

resource "aws_instance" "example" {
  ami           = "ami-0c55b159cbfafe1f0"
  instance_type = "t2.micro"
}
Enter fullscreen mode Exit fullscreen mode

IV. Benefits of Using Terraform with AWS

  • Fully Automated Infrastructure Deployment: Terraform enables complete automation of infrastructure management and deployment on AWS, saving time and reducing the risk of manual errors.
  • Multi-Region and Multi-Account Management: Terraform makes it easy to manage infrastructure resources across multiple AWS regions and accounts.
  • Scalability: With Terraform, you can easily scale infrastructure without the complexity of managing a large setup.
  • Easy Rollback: Terraform tracks and manages infrastructure changes, allowing you to revert to a previous state if needed.

Terraform is a powerful and flexible infrastructure management tool, especially valuable when working with AWS. It helps automate, manage, and optimize cloud infrastructure deployment efficiently, reducing errors and saving time. As the trend for Infrastructure as Code (IaC) continues to grow, Terraform will play a key role in managing complex infrastructure on AWS and other cloud platforms.

. . .