A
cd ..
DevOps

Terraform Infrastructure as Code

Manage cloud infrastructure with Terraform commands.

2025-10-08
terraform, iac, cloud

Initialize Terraform

terraform init

Validate configuration

terraform validate

Format code

terraform fmt

Format and check

terraform fmt -check

Plan changes

terraform plan

Apply changes

terraform apply

Apply without confirmation

terraform apply -auto-approve

Destroy infrastructure

terraform destroy

Destroy without confirmation

terraform destroy -auto-approve

Show current state

terraform show

List resources

terraform state list

Show specific resource

terraform state show aws_instance.example

Refresh state

terraform refresh

Output values

terraform output

Specific output

terraform output instance_ip

Import existing resource

terraform import aws_instance.example i-1234567890abcdef0

Taint resource (force recreate)

terraform taint aws_instance.example

Untaint resource

terraform untaint aws_instance.example

Target specific resource

terraform apply -target=aws_instance.example

Use variable file

terraform apply -var-file="prod.tfvars"

Set variable from CLI

terraform apply -var="instance_type=t2.micro"

Generate dependency graph

terraform graph | dot -Tsvg > graph.svg

Select workspace

terraform workspace select prod

List workspaces

terraform workspace list

Create workspace

terraform workspace new staging

Delete workspace

terraform workspace delete staging

Show workspace

terraform workspace show

Lock state

terraform force-unlock LOCK_ID

Get providers

terraform providers

Basic example

# main.tf
terraform {
  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 4.0"
    }
  }
}

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

resource "aws_instance" "web" {
  ami           = "ami-0c55b159cbfafe1f0"
  instance_type = "t2.micro"
  
  tags = {
    Name = "WebServer"
  }
}

output "instance_ip" {
  value = aws_instance.web.public_ip
}

Variables file

# variables.tf
variable "region" {
  description = "AWS region"
  default     = "us-east-1"
}

variable "instance_type" {
  description = "EC2 instance type"
  default     = "t2.micro"
}

Remote backend (S3)

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

Debug mode

TF_LOG=DEBUG terraform apply

Was this useful?

Share with your team

Browse More