Post

Terraform Basics and Getting Started

What is Terraform?

Terraform is an open-source Infrastructure as Code (IaC) tool developed by HashiCorp. It allows you to define and provision infrastructure resources using a declarative configuration language called HashiCorp Configuration Language (HCL). Terraform supports multiple cloud providers, including AWS, Azure, Google Cloud Platform, and many others.

Key Benefits of Terraform

  • Infrastructure as Code: Define your infrastructure in code, making it version-controlled and repeatable.
  • Multi-Cloud Support: Manage resources across multiple cloud providers with a single tool.
  • Declarative Syntax: Describe the desired state of your infrastructure, and Terraform will determine how to achieve it.
  • State Management: Terraform maintains a state file that tracks the current state of your infrastructure.
  • Plan and Apply: Preview changes before applying them to your infrastructure.

Installing Terraform

On macOS

You can install Terraform using Homebrew:

1
brew install terraform

On Linux

Download the appropriate binary for your system from the Terraform downloads page:

1
2
3
4
# Replace VERSION with the latest version from the downloads page
wget https://releases.hashicorp.com/terraform/VERSION/terraform_VERSION_linux_amd64.zip
unzip terraform_VERSION_linux_amd64.zip
sudo mv terraform /usr/local/bin/

Alternatively, you can use the HashiCorp APT repository:

1
2
3
wget -O- https://apt.releases.hashicorp.com/gpg | sudo gpg --dearmor -o /usr/share/keyrings/hashicorp-archive-keyring.gpg
echo "deb [signed-by=/usr/share/keyrings/hashicorp-archive-keyring.gpg] https://apt.releases.hashicorp.com $(lsb_release -cs) main" | sudo tee /etc/apt/sources.list.d/hashicorp.list
sudo apt update && sudo apt install terraform

On Windows

Download the Windows binary from the Terraform downloads page and add it to your system PATH.

Verify Installation

Verify that Terraform is installed correctly:

1
terraform version

Core Terraform Concepts

Providers

Providers are plugins that allow Terraform to interact with cloud platforms, SaaS providers, and other APIs. Each provider adds a set of resource types and data sources.

1
2
3
4
5
6
7
8
9
10
11
12
terraform {
  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 5.0"
    }
  }
}

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

Resources

Resources are the most important element in Terraform. They describe one or more infrastructure objects, such as virtual networks, compute instances, or DNS records.

Note: The AMI ID in these examples is for demonstration purposes. AMI IDs are region-specific and change over time. You can find the latest Amazon Linux 2 AMI ID for your region in the AWS EC2 Console or by using the AWS CLI: aws ec2 describe-images --owners amazon --filters "Name=name,Values=amzn2-ami-hvm-*-x86_64-gp2" --query 'sort_by(Images, &CreationDate)[-1].ImageId'

1
2
3
4
5
6
7
8
resource "aws_instance" "example" {
  ami           = "ami-0abcdef1234567890"  # Replace with current AMI ID for your region
  instance_type = "t2.micro"

  tags = {
    Name = "example-instance"
  }
}

Variables

Variables allow you to parameterize your Terraform configuration:

1
2
3
4
5
6
7
8
9
10
variable "instance_type" {
  description = "The type of EC2 instance to launch"
  type        = string
  default     = "t2.micro"
}

resource "aws_instance" "example" {
  ami           = "ami-0abcdef1234567890"  # Replace with current AMI ID
  instance_type = var.instance_type
}

Outputs

Outputs allow you to export values from your Terraform configuration:

1
2
3
4
output "instance_public_ip" {
  description = "The public IP address of the instance"
  value       = aws_instance.example.public_ip
}

State

Terraform stores the state of your infrastructure in a state file. This file is used to map real-world resources to your configuration, track metadata, and improve performance.

Your First Terraform Project

Let’s create a simple Terraform project that provisions an AWS EC2 instance.

Step 1: Create a Project Directory

1
2
mkdir terraform-demo
cd terraform-demo

Step 2: Create the Configuration File

Create a file named main.tf with the following content:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
terraform {
  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 5.0"
    }
  }
}

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

resource "aws_instance" "web_server" {
  ami           = "ami-0abcdef1234567890"  # Replace with current AMI ID for your region
  instance_type = "t2.micro"

  tags = {
    Name = "my-first-terraform-instance"
  }
}

output "instance_id" {
  description = "The ID of the EC2 instance"
  value       = aws_instance.web_server.id
}

output "instance_public_ip" {
  description = "The public IP of the EC2 instance"
  value       = aws_instance.web_server.public_ip
}

Step 3: Initialize Terraform

Initialize your Terraform working directory:

1
terraform init

This command downloads the required provider plugins and initializes the backend.

Step 4: Preview Changes

Generate an execution plan to see what Terraform will do:

1
terraform plan

Step 5: Apply Changes

Apply the configuration to create the resources:

1
terraform apply

Type yes when prompted to confirm the changes.

Step 6: Verify Resources

After the apply completes, you can see the outputs and verify that the instance was created.

Step 7: Destroy Resources

When you’re done, clean up by destroying the resources:

1
terraform destroy

Best Practices

  1. Use Version Control: Store your Terraform configuration in a version control system like Git.
  2. Use Remote State: Store your state file remotely (e.g., in S3 or Terraform Cloud) for team collaboration.
  3. Use Modules: Organize your code into reusable modules.
  4. Use Variables: Parameterize your configuration for flexibility.
  5. Use Workspaces: Manage multiple environments (dev, staging, prod) with workspaces.
  6. Plan Before Apply: Always run terraform plan before terraform apply.

Additional Resources

Conclusion

Terraform is a powerful tool for managing infrastructure as code. By following this guide, you should now have a basic understanding of Terraform concepts and be able to create your first Terraform project. As you become more comfortable with Terraform, explore more advanced features like modules, remote state, and workspaces to build more complex infrastructure deployments.

Happy provisioning!

This post is licensed under CC BY 4.0 by the author.