What is Infrastructure as Code (IaC)?

Infrastructure as Code (IaC) is managing infrastructure using code instead of manual configuration. Terraform allows users to define both low-level resources (like virtual machines, networks) and high-level resources (like DNS, SaaS features).

Terraform:

  • Creates infrastructure safely and efficiently.
  • Tracks and versions changes.
  • Allows incremental updates and changes through an execution plan.

Terraform Variables

Variable Types

Terraform supports several variable types:

  • String
  • Number
  • Boolean
  • List
  • Map

Example:

variable "vpcname" {
  type    = string
  default = "myvpc"
}

Lists

Example list variable:

variable "mylist" {
  type    = list(string)
  default = ["Value1", "Value2"]
}

Access elements with var.mylist[0].

Maps

Key-value pairs, accessed by keys:

variable "mymap" {
  type    = map(string)
  default = {
    Key1 = "Value1"
    Key2 = "Value2"
  }
}

Access with var.mymap["Key1"].

Input Variables

Prompt users for input at runtime:

variable "vpc_name" {
  description = "Enter the VPC name"
}

Outputs

Display infrastructure attributes after creation:

output "vpc_id" {
  value = aws_vpc.myvpc.id
}

Local Values

Reusable within modules to avoid repetition:

locals {
  service_name = "forum"
  owner        = "Community Team"
}

Environment Variables

Set externally:

export TF_VAR_vpcname="envvpc"

CLI Variables

Pass variables at runtime:

terraform plan -var="vpcname=cliname"

TFVARS Files

File-based variable management:

vpcname = "tfvarsname"
port    = 22
policy  = {
  test  = 1
  debug = "true"
}

Terraform Commands

Command Purpose
terraform init Initialize configuration & download plugins
terraform validate Check configuration validity
terraform plan Preview changes before apply
terraform apply Apply configuration changes
terraform destroy Remove managed infrastructure

Terraform Modules

Reusable code blocks with input/output variables.

Example usage:

module "dbserver" {
  source = "./db"
  dbname = "mydbserver"
}

Terraform State Management

  • Local Backend: Stores state locally.
  • Remote Backend (S3): Stores state in AWS S3 bucket.

Example remote backend:

terraform {
  backend "s3" {
    bucket = "mybucket"
    key    = "state/terraform.tfstate"
    region = "us-east-1"
  }
}

Terraform Cloud

Features:

  • Remote state storage
  • Collaboration tools
  • VCS integration

Setup:

  • Create an account at Terraform Cloud.
  • Connect VCS repositories.
  • Manage secrets and variables securely.

Debugging Terraform

Enable detailed logs:

export TF_LOG=TRACE
export TF_LOG_PATH=./terraform.log

Happy Terraforming!