DEV Community

Cover image for Exploring Terraform -From Basics to Advanced Concepts - Week Fifteen
Shubham Murti
Shubham Murti

Posted on • Updated on

Exploring Terraform -From Basics to Advanced Concepts - Week Fifteen

Hello Community! 🌟

In this week's deep dive, we explored Terraform, an Infrastructure as Code (IaC) tool that allows you to build, change, and version infrastructure safely and efficiently. Terraform is a powerful tool for managing and provisioning cloud resources, and in this blog, we'll cover its essential concepts, how it compares with other tools like Ansible, and provide a step-by-step guide to getting started with Terraform on AWS and GitHub.

We will focus on creating and managing AWS resources using Terraform. We'll cover setting up an EC2 instance, generating and assigning SSH keys, creating security groups, and managing Terraform workspaces.


What is Terraform?

Terraform is an open-source IaC tool developed by HashiCorp that allows users to define and provision infrastructure using a high-level configuration language. Terraform supports multiple cloud providers, making it a versatile tool for managing infrastructure across various platforms.

Image description


Why Use Terraform?

Terraform is widely used because it offers several key advantages:

  • Provider Agnostic: Supports multiple cloud providers (AWS, Azure, Google Cloud) and platforms like GitHub.
  • Declarative Language: You define the desired state of your infrastructure, and Terraform figures out how to achieve it.
  • Automation: Automates provisioning and management with simple commands.
  • Version Control: Tracks changes to infrastructure over time.

Terraform vs. Ansible

  • Infrastructure Creation: Terraform is designed for infrastructure provisioning, while Ansible is better for configuration management.
  • Configuration Management: Ansible excels at software deployment, whereas Terraform focuses on infrastructure.
  • State Management: Terraform uses a state file to track the current state of your infrastructure, ensuring precise changes, while Ansible does not maintain state in the same way.

Getting Started with Terraform on Windows

Installing Terraform

  1. Download Terraform: Visit the official Terraform website and download the appropriate version for Windows.
  2. Add Terraform to System Path: Add the path to the Terraform executable in the system environment variables.
  3. Verify Installation: Open Command Prompt and type terraform -help to confirm that Terraform is installed.
  4. Set Up Text Editor: Use Visual Studio Code (VS Code) with the HashiCorp Terraform extension.

Writing Your First Terraform Configuration

  1. Create a Terraform File: Create a .tf file, for example, first.tf.
output "Hello1" {
  value = "Hello World"
}

Enter fullscreen mode Exit fullscreen mode
  1. Executing Terraform Commands: Run terraform plan to preview changes and ensure the configuration is correct.

Working with Multiple Blocks and Files

Multiple Blocks in a Single File:

output "FirstOutput" {
  value = "First Output of Terraform"
}
output "SecondOutput" {
  value = "Second Output of Terraform"
}```
{% endraw %}


2. Multiple Terraform Files in a Directory: Terraform processes all .tf files in a directory, allowing you to separate configurations.

## Working with Variables

1. **Defining Variables:**
{% raw %}

```hcl
variable "username" {}
output "printname" {
  value = "Hello ${var.username}"
}```
{% endraw %}


2. **Passing Variables from the Command Line:**
{% raw %}

```bash
terraform plan -var "username=Shubham"
Enter fullscreen mode Exit fullscreen mode
  1. Using Multiple Variables:
variable "username" { default = "world" }
variable "age" { default = 25 }

output "printname" {
  value = "Hello ${var.username}, and your age is ${var.age}"
}
Enter fullscreen mode Exit fullscreen mode

Advanced Terraform Features

Lists and Maps:

variable "users" {
  type = list(string)
}
output "printFirst" {
  value = "First user is ${var.users[0]}"
}```
{% endraw %}


**Maps Example:**
{% raw %}


```hcl
variable "userage" {
  type = map
  default = {
    "Shubham" = 25
    "Asif" = 30
  }
}
output "userage" {
  value = "My name is ${var.username} and my age is ${lookup(var.userage, var.username)}"
}
Enter fullscreen mode Exit fullscreen mode

Terraform State and Commands

  • terraform init: Initializes a Terraform working directory.
  • terraform plan: Shows planned actions.
  • terraform apply: Applies changes to reach the desired state.
  • terraform destroy: Destroys managed infrastructure.
  • terraform validate: Validates configuration files.
  • terraform fmt: Formats configuration files.
  • Managing Resources with Terraform

Creating AWS Resources

provider "aws" {
  region = "us-west-2"
  access_key = "<your-access-key>"
  secret_key = "<your-secret-key>"
}

resource "aws_instance" "web" {
  ami = "ami-0e472ba48eb589f49"
  instance_type = "t2.micro"
  tags = {
    Name = "first-tf-instance"
  }
}
Enter fullscreen mode Exit fullscreen mode

Managing GitHub Repositories

provider "github" {
  token = "<your-github-token>"
}

resource "github_repository" "First_repo_to_github" {
  name        = "First_repo_from_github"
  description = "My awesome codebase"
  visibility  = "public"
}
Enter fullscreen mode Exit fullscreen mode

Creating Your First AWS Resource: EC2 Instance

resource "aws_instance" "web" {
  ami           = "ami-0e472ba48eb589f49"
  instance_type = "t2.micro"
  tags = {
    Name = "first-tf-instance"
  }
}
Enter fullscreen mode Exit fullscreen mode

Creating an AWS SSH Key and Reading a File in Terraform

ssh-keygen -t rsa -b 2048 -f ~/.ssh/my-key-pair
hcl
Copy code
resource "aws_key_pair" "deployer" {
  key_name   = "my-key-pair"
  public_key = file("~/.ssh/my-key-pair.pub")
}
Enter fullscreen mode Exit fullscreen mode

Creating a Security Group Using Terraform

resource "aws_security_group" "web_sg" {
  name        = "allow_ssh_http"
  description = "Allow SSH and HTTP traffic"
  vpc_id      = "<your-vpc-id>"

  ingress {
    from_port   = 22
    to_port     = 22
    protocol    = "tcp"
    cidr_blocks = ["0.0.0.0/0"]
  }

  ingress {
    from_port   = 80
    to_port     = 80
    protocol    = "tcp"
    cidr_blocks = ["0.0.0.0/0"]
  }

  egress {
    from_port   = 0
    to_port     = 0
    protocol    = "-1"
    cidr_blocks = ["0.0.0.0/0"]
  }
}
Enter fullscreen mode Exit fullscreen mode

Visualizing Terraform Configuration: Terraform Graph

terraform graph | dot -Tpdf > graph.pdf
Managing Environments with Terraform Workspaces
terraform workspace list: List all workspaces.
terraform workspace new dev: Create a new workspace named 'dev'.
terraform workspace show: Show the current workspace.
terraform workspace select dev: Switch to the 'dev' workspace.
Enter fullscreen mode Exit fullscreen mode

Closure

Terraform is a powerful tool that simplifies the process of managing and provisioning infrastructure. Whether you're setting up cloud resources on AWS or managing repositories on GitHub, Terraform provides a consistent and efficient way to manage infrastructure as code. By mastering the basics and exploring advanced features, you can automate complex environments and improve the reliability of your deployments.

Stay tuned for more updates next week!

Shubham Murti — Aspiring Cloud Security Engineer | Weekly Cloud Learning !!

Let’s connect: Linkdin, Twitter, Github

Top comments (0)