Terraform Complete Guide — Infrastructure as Code
Advertisement
Terraform Complete Guide — Infrastructure as Code
Terraform enables infrastructure provisioning through code, managing cloud resources declaratively.
Introduction
Terraform uses HCL to define infrastructure, enabling version-controlled, repeatable deployments.
Basic Configuration
terraform {
required_version = ">= 1.0"
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 5.0"
}
}
}
provider "aws" {
region = var.aws_region
}
resource "aws_instance" "web" {
ami = "ami-0c55b159cbfafe1f0"
instance_type = var.instance_type
tags = {
Name = "web-server"
}
}
variable "aws_region" {
default = "us-east-1"
}
variable "instance_type" {
default = "t3.micro"
}
output "instance_ip" {
value = aws_instance.web.public_ip
}
State Management
# Initialize
terraform init
# Plan
terraform plan -out=tfplan
# Apply
terraform apply tfplan
# Show state
terraform show
# Remote state
terraform init -backend-config="bucket=my-terraform-state"
Modules
module "vpc" {
source = "./modules/vpc"
vpc_cidr = "10.0.0.0/16"
environment = "production"
}
module "eks" {
source = "terraform-aws-modules/eks/aws"
version = "19.0.0"
cluster_name = "my-cluster"
cluster_version = "1.27"
vpc_id = module.vpc.vpc_id
subnet_ids = module.vpc.private_subnets
}
FAQ
Q: What is Terraform state? A: State file tracking real infrastructure. Critical for tracking resources.
Q: Should I commit tfstate to Git? A: No. Use remote backend (S3, Terraform Cloud) for shared state.
Advertisement