What is Terraform?
You declare infrastructure (servers, networks, databases, and more) as code in .tf files, then create, update, or destroy real cloud resources with a single terraform apply. AWS, GCP, Azure, Kubernetes, and more are all supported.
Installation
Bash
# Ubuntu/Debian
wget -O- https://apt.releases.hashicorp.com/gpg | gpg --dearmor \
| sudo tee /usr/share/keyrings/hashicorp-archive-keyring.gpg
echo "deb [signed-by=/usr/share/keyrings/hashicorp-archive-keyring.gpg] \
https://apt.releases.hashicorp.com $(lsb_release -cs) main" \
| sudo tee /etc/apt/sources.list.d/hashicorp.list
sudo apt update && sudo apt install terraform
terraform versionBasic Structure
CODE
my-infra/
├── main.tf # resource definitions
├── variables.tf # input variables
├── outputs.tf # output values
├── providers.tf # provider configuration
└── terraform.tfvars # variable values (exclude from git)AWS EC2 Example
providers.tf
HCL
terraform {
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 5.0"
}
}
}
provider "aws" {
region = var.region
}main.tf
HCL
data "aws_ami" "ubuntu" {
most_recent = true
owners = ["099720109477"]
filter {
name = "name"
values = ["ubuntu/images/hvm-ssd/ubuntu-*-22.04-amd64-server-*"]
}
}
resource "aws_instance" "web" {
ami = data.aws_ami.ubuntu.id
instance_type = var.instance_type
tags = {
Name = "web-server"
Environment = "production"
}
}outputs.tf
HCL
output "instance_public_ip" {
value = aws_instance.web.public_ip
}Workflow
Bash
# Initialize (download providers)
terraform init
# Review the execution plan (what will actually be created/changed/destroyed)
terraform plan
# Apply
terraform apply
# Apply a specific resource only
terraform apply -target=aws_instance.web
# Destroy everything
terraform destroy
# Inspect current state
terraform show
terraform state listRemote State Management (Team Collaboration)
HCL
# backend.tf
terraform {
backend "s3" {
bucket = "my-terraform-state"
key = "prod/terraform.tfstate"
region = "ap-northeast-2"
encrypt = true
dynamodb_table = "terraform-lock"
}
}Always manage the state file (terraform.tfstate) in a remote backend (S3 + DynamoDB locking). Never commit it to git.
Editorial note
AI tools may assist drafting. Check the evidence in each guide for whether commands were run and which environment was used. Confirm the current docs for your version before applying instructions, and email us about errors. email us
Topic-related official docs (auto-linked · not per-claim sources)Terraform documentation ↗AWS documentation ↗
Questions & answers
Ask a question about this guide. We'll review and reply.