#Terraform
The most popular IaC tool for multi-cloud infrastructure.
#Installation
bash
1# macOS
2brew tap hashicorp/tap
3brew install hashicorp/tap/terraform
4
5# Linux
6wget https://releases.hashicorp.com/terraform/1.6.0/terraform_1.6.0_linux_amd64.zip
7unzip terraform_1.6.0_linux_amd64.zip
8sudo mv terraform /usr/local/bin/#Basic Example
hcl
1# main.tf
2terraform {
3 required_providers {
4 aws = {
5 source = "hashicorp/aws"
6 version = "~> 5.0"
7 }
8 }
9}
10
11provider "aws" {
12 region = "us-east-1"
13}
14
15resource "aws_instance" "web" {
16 ami = "ami-0c55b159cbfafe1f0"
17 instance_type = "t2.micro"
18
19 tags = {
20 Name = "WebServer"
21 }
22}
23
24output "public_ip" {
25 value = aws_instance.web.public_ip
26}#Commands
bash
1# Initialize
2terraform init
3
4# Plan
5terraform plan
6
7# Apply
8terraform apply
9
10# Destroy
11terraform destroy
12
13# Format
14terraform fmt
15
16# Validate
17terraform validate#State Management
hcl
1# Remote state (recommended)
2terraform {
3 backend "s3" {
4 bucket = "my-terraform-state"
5 key = "prod/terraform.tfstate"
6 region = "us-east-1"
7 }
8}#Modules
hcl
1module "vpc" {
2 source = "terraform-aws-modules/vpc/aws"
3 version = "5.0.0"
4
5 name = "my-vpc"
6 cidr = "10.0.0.0/16"
7}[!TIP] Pro Tip: Always use remote state and state locking!