惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

博客园 - 三生石上(FineUI控件)
博客园 - 叶小钗
博客园 - 聂微东
博客园 - 司徒正美
Hugging Face - Blog
Hugging Face - Blog
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
Google DeepMind News
Google DeepMind News
Recent Announcements
Recent Announcements
IT之家
IT之家
J
Java Code Geeks
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
I
InfoQ
爱范儿
爱范儿
Vercel News
Vercel News
Apple Machine Learning Research
Apple Machine Learning Research
阮一峰的网络日志
阮一峰的网络日志
博客园 - Franky
U
Unit 42
酷 壳 – CoolShell
酷 壳 – CoolShell
腾讯CDC
F
Fortinet All Blogs
V
Visual Studio Blog
人人都是产品经理
人人都是产品经理

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant
Build the infrastructure and understand Terraform
Do Ngoc Tuan · 2026-05-14 · via DEV Community

Senerio

In the previous section, we know how to set up Terraform on Ubuntu24.04. Now, in this section we will learn how to use the Terraform to Initialize and manage the infrastructure. Not by using AWS console, but use the CLI instead.

By the end of this article, you'll:
✅ Understand the Terraform workflow
✅ Write .tf file
✅ Create an actual S3 bucket and EC2 on AWS
✅ Understand what a state file
✅ Clean up resources properly

Quick Theory: The Terraform Workflow

Before we dive in, there are 4 commands that we need to know form the core Terraform workflow. You'll use these commands in every project, whether you're creating a simple S3 bucket or a complex multi-tier application with many services on AWS.

terraform init      #Initialize the providers
terraform plan      #See what resources will change
terraform apply     #Build the real insfrastructure
terraform destroy   #Clean up the resources after using

Enter fullscreen mode Exit fullscreen mode

📝 Understanding Terraform Files

Terraform uses files extension .tf written in HCL (HashiCorp Configuration Language). Don't worry - it's much simpler than it sounds!

Basic Structure:

# This is a comment

block_type "label" "name" {
  argument = "value"
  another_argument = 1234
}

Enter fullscreen mode Exit fullscreen mode

Three main block types we'll use when edit the configuration:

terraform - Configuration settings
provider - Which cloud (AWS, Azure, GCP)
resource - What to create (S3, EC2, RDS etc...)
Ok now you see it simlifier than before right. Let's see them in action!

🛠️ Hands-On: Create Your First S3 Bucket

Step 1: Create Your Project Directory

# Create a directory for Terraform project
mkdir -p ~/terraform-project
cd ~/terraform-project

Enter fullscreen mode Exit fullscreen mode

Create mns3.tf

nano mns3.tf # or use your favorite editor vim, vscode, etc...

Step 2: Write Your First Terraform Code

terraform {
  required_version = ">= 1.0"
  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 6.0"
    }
  }
}

provider "aws" {
  region = "ap-southeast-1" #Choose the region that closest your country
}

# Create two S3 buckets
resource "aws_s3_bucket" "logs" {
  bucket = "my-app-logs-shoeshop-2026"

  tags = {
    Name        = "Application Logs"
    Environment = "Development"
    Purpose     = "Logging"
  }
}

resource "aws_s3_bucket" "backups" {
  bucket = "my-app-backups-shoeshop-2026"

  tags = {
    Name        = "Application Backups"
    Environment = "Development"
    Purpose     = "Backup Storage"
  }
}

# Outputs
output "logs_bucket_id" {
  value = aws_s3_bucket.logs.id
}

output "backups_bucket_id" {
  value = aws_s3_bucket.backups.id
}

Enter fullscreen mode Exit fullscreen mode

⚠️ Important: Change the bucket name = "my-app-logs-shoeshop-2026" and "my-app-backups-shoeshop-2026" to differnt name because S3 bucket names must be globally unique across ALL AWS accounts!

Save the file

🚀 The 4 Commands in Action

Now comes the exciting part! Let's run our 4 magic commands.

Command 1: terraform init

This downloads the AWS provider plugin.

terraform init

Enter fullscreen mode Exit fullscreen mode

You'll see:

What just happened?

  • Terraform downloaded the AWS provider plugin
  • Created a .terraform/ directory (hidden folder)
  • Created .terraform.lock.hcl file (locks provider versions) Pro Tip: You only need to run init once per project, or when you add new providers.

Command 2: terraform plan

This show you what Terraform will create (you can preview the change before apply it).

terraform plan

Enter fullscreen mode Exit fullscreen mode

You'll see:


Understanding the output:

  • means "will be created" ~ means "will be modified" (you'll see this later)
  • means "will be destroyed" (known after apply) means AWS will generate this value This is your safety check! Always review the plan before applying.

Command 3: terraform apply

This actually creates the resources on AWS.

terraform apply

Enter fullscreen mode Exit fullscreen mode

Type yes and press Enter.

You'll see:


🎉 Congratulations! You just created your first AWS resource with code!

Verify in AWS Console

Let's confirm it's really there:

Go to AWS S3 Console
You should see two bucket: my-app
Click on it and check the Tags tab - you'll see all the tags you defined!
This is the "enjoy!" moment - you created AWS infrastructure without clicking through the console!

🗂️ Understanding the State File

After running terraform apply, you'll notice a new file: terraform.tfstate

ls -al

Enter fullscreen mode Exit fullscreen mode

You'll see:

.terraform/
.terraform.lock.hcl
main.tf
terraform.tfstate

Enter fullscreen mode Exit fullscreen mode

What is the State File?

The state file is Terraform's memory. It stores:

  • What resources Terraform created
  • Current configuration of those resources
  • Metadata and dependencies Let's peek inside:
cat terraform.tfstate

Enter fullscreen mode Exit fullscreen mode

You'll see JSON with details about your S3 bucket - its name, ARN, region, tags, etc.

Why Does State Matter?

When you run terraform plan or terraform apply again, Terraform:

  • Reads the state file to know what exists
  • Compares it with your .tf files
  • Calculates what needs to change Without state, Terraform wouldn't know what it created!

⚠️ Important State Rules:

Never edit state files manually
Never delete state files (you'll lose track of resources)
Never commit state files to Git (they contain sensitive data)

🧪 Let's Make a Change

Now let's see Terraform's power - making changes to existing infrastructure.

Edit mns3.tf file and add a new tag:

terraform {
  required_version = ">= 1.0"
  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 6.0"
    }
  }
}

provider "aws" {
  region = "ap-southeast-1"
}

# Create two S3 buckets
resource "aws_s3_bucket" "logs" {
  bucket = "my-app-logs-shoeshop-2026"

  tags = {
    Name        = "Application Logs"
    Environment = "Development"
    Purpose     = "Logging"
    LastUpdated = "Today" # <- Add this new tag
  }
}

resource "aws_s3_bucket" "backups" {
  bucket = "my-app-backups-shoeshop-2026"

  tags = {
    Name        = "Application Backups"
    Environment = "Development"
    Purpose     = "Backup Storage"
    LastUpdated = "Today"  # <- Add this new tag
  }
}

# Outputs
output "logs_bucket_id" {
  value = aws_s3_bucket.logs.id
}

output "backups_bucket_id" {
  value = aws_s3_bucket.backups.id
}

Enter fullscreen mode Exit fullscreen mode

Run plan again:
terraform plan
You'll see:

# aws_s3_bucket.backups will be updated in-place
  ~ resource "aws_s3_bucket" "backups" {
        id                          = "my-app-backups-shoeshop-2026"
      ~ tags                        = {
            "Environment" = "Development"
          + "LastUpdated" = "Today"
            "Name"        = "Application Backups"
            "Purpose"     = "Backup Storage"
        }
      ~ tags_all                    = {
          + "LastUpdated" = "Today"
            # (3 unchanged elements hidden)
        }
        # (14 unchanged attributes hidden)

        # (3 unchanged blocks hidden)
    }

  # aws_s3_bucket.logs will be updated in-place
  ~ resource "aws_s3_bucket" "logs" {
        id                          = "my-app-logs-shoeshop-2026"
      ~ tags                        = {
            "Environment" = "Development"
          + "LastUpdated" = "Today"
            "Name"        = "Application Logs"
            "Purpose"     = "Logging"
        }
      ~ tags_all                    = {
          + "LastUpdated" = "Today"
            # (3 unchanged elements hidden)
        }
        # (14 unchanged attributes hidden)

        # (3 unchanged blocks hidden)
    }

Plan: 0 to add, 2 to change, 0 to destroy.

Enter fullscreen mode Exit fullscreen mode


Notice the ~ symbol - it means "modify existing resource"!
Apply the change:
terraform apply
Type yes when prompted.


Check AWS Console - your bucket now has the new tag!


This is Infrastructure as Code magic - you changed infrastructure by editing a text file!

🧹 Command 4: terraform destroy

Always clean up resources you're not using (to avoid unexpected charges).

terraform destroy

Terraform will show what it will delete:

# aws_s3_bucket.logs will be destroyed
  - resource "aws_s3_bucket" "logs" {
      - bucket                      = "my-app-logs-shoeshop-2026" -> null
          - "Environment" = "Development"
          - "LastUpdated" = "Today"
          - "Name"        = "Application Logs"
          - "Purpose"     = "Logging"
        } -> null
          .....
        }
    }

Plan: 0 to add, 0 to change, 2 to destroy.

Enter fullscreen mode Exit fullscreen mode

Type yesto confirm.


Verify in AWS Console - your bucket is gone!

🎓 What You Just Learned

Let's recap what you accomplished:

✅ The Terraform Workflow:
init - Initialize project
plan - Preview changes
apply - Create resources
destroy - Clean up
✅ HCL Basics:
terraform block (configuration)
provider block (cloud provider)
resource block (what to create)
output block (display information)
✅ State Management:

  1. State file tracks resources
  2. Never edit state manually
  3. State enables change detection
    ✅ Real Infrastructure:

  4. Created actual AWS S3 bucket

  5. Modified existing resource

  6. Destroyed resources cleanly