Skip to content
>_higan
This post has a translation:Read in Tiếng Việt

Terraform #00 — Setup & Free Practice Environment

Install Terraform with tfenv, understand the Terraform vs OpenTofu split, and set up a safe, free practice environment using LocalStack.

Goal: Get Terraform installed, understand how providers work, and set up a safe, free practice environment using LocalStack (a local AWS emulator).


0.1. What is Terraform? (30 seconds)

Terraform is HashiCorp's Infrastructure as Code (IaC) tool. You describe your infrastructure (servers, networks, databases...) in text files, and Terraform:

  1. Compares what you want with what currently exists (plan).
  2. Calls the provider's API (AWS/Azure/GCP...) to create, update, or delete resources (apply).
  3. Remembers what it created in a state file.
   .tf files (desired state)  ──►  terraform plan  ──►  terraform apply  ──►  Cloud API
                                          ▲                                        │
                                          └──────────  state file  ◄───────────────┘
                                                   (what was actually created)

Why IaC? Reproducibility, Git-reviewable changes, rollback, and no more "who clicked what in the console" mysteries.


0.2. Terraform vs OpenTofu

In 2023, HashiCorp changed Terraform's license from MPL to BSL (Business Source License). The community responded by forking it into OpenTofu (under the Linux Foundation). The syntax is about 99% identical.

TerraformOpenTofu
LicenseBSL 1.1MPL 2.0 (open source)
CLIterraformtofu
HCL syntax~99% identical~99% identical

This series uses terraform. Everything applies to tofu — just swap the command name. In practice, knowing both is a plus.


0.3. Installing Terraform

In real projects, different codebases often need different Terraform versions. tfenv makes switching painless.

# macOS
brew install tfenv
 
# Linux
git clone https://github.com/tfutils/tfenv.git ~/.tfenv
echo 'export PATH="$HOME/.tfenv/bin:$PATH"' >> ~/.bashrc
source ~/.bashrc
 
# Install and use a specific version
tfenv install 1.9.0
tfenv use 1.9.0
tfenv list

Drop a .terraform-version file containing 1.9.0 in your project directory and tfenv will pick it up automatically.

Option 2: Direct install

# macOS
brew tap hashicorp/tap
brew install hashicorp/tap/terraform
 
# Linux (Debian/Ubuntu)
wget -O- https://apt.releases.hashicorp.com/gpg | sudo gpg --dearmor -o /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
 
# Windows
choco install terraform

Verify

terraform version
# Terraform v1.9.x

0.4. Supporting tools (worth having)

ToolWhat it doesInstall
terraform fmtFormat code (built-in)built-in
tflintLinter, catches bugs and anti-patternsbrew install tflint
terraform-docsAuto-generates module documentationbrew install terraform-docs
checkov / tfsecSecurity scanningpip install checkov
infracostCost estimation from plan outputbrew install infracost
pre-commitRun fmt/lint before every commitpip install pre-commit

You don't need all of these right now. Module 08 covers them. Just know they exist.


0.5. Editor setup

Install the HashiCorp Terraform extension for VS Code — it gives you syntax highlighting, autocomplete, and format-on-save. Enable it:

// settings.json
{
  "editor.formatOnSave": true,
  "[terraform]": { "editor.defaultFormatter": "hashicorp.terraform" }
}

0.6. Practice environment: two options

LocalStack runs a local AWS API emulator on your machine. No account needed, no cost, no risk of accidentally spinning up expensive resources.

# Install LocalStack
pip install localstack
# Or with Docker
docker run --rm -d -p 4566:4566 --name localstack localstack/localstack
 
# Start it
localstack start -d
localstack status services

Provider config pointing to LocalStack (you'll use this in later modules):

provider "aws" {
  region                      = "us-east-1"
  access_key                  = "test"
  secret_key                  = "test"
  skip_credentials_validation = true
  skip_metadata_api_check     = true
  skip_requested_account_id   = true
 
  endpoints {
    s3       = "http://localhost:4566"
    ec2      = "http://localhost:4566"
    dynamodb = "http://localhost:4566"
    iam      = "http://localhost:4566"
  }
}

LocalStack covers most of S3, EC2, DynamoDB, IAM, Lambda, SQS, SNS (roughly 90% of labs). Some advanced services need the Pro tier.

Option B — Real AWS account (Free Tier)

If you want the real thing:

  1. Create an AWS account and set up billing alerts straight away.
  2. Create an IAM user, get Access Key + Secret Key. Don't use the root account for anything.
  3. Install AWS CLI and configure it:
aws configure
# AWS Access Key ID: ...
# AWS Secret Access Key: ...
# Default region name: us-east-1

⚠️ Golden rule for real AWS: Always run terraform destroy after each lab. Set a billing alert at a low threshold ($5 is fine) so nothing sneaks up on you.


0.7. Credentials — the right way

Never hardcode access keys in .tf files.

Use environment variables:

export AWS_ACCESS_KEY_ID="AKIA..."
export AWS_SECRET_ACCESS_KEY="..."
export AWS_REGION="us-east-1"

Or an AWS profile:

export AWS_PROFILE="my-learning-profile"

Always have a .gitignore:

# Terraform .gitignore
*.tfstate
*.tfstate.*
.terraform/
.terraform.lock.hcl   # usually SHOULD be committed — see Module 01
*.tfvars              # if it contains secrets
crash.log
override.tf

0.8. Hands-on: "Hello, Terraform"

A tiny starter lab to confirm your environment works. Create a directory:

mkdir -p ~/tf-hello && cd ~/tf-hello

main.tf:

terraform {
  required_version = ">= 1.5.0"
}
 
# A local resource — no cloud needed, just creates a file on disk
resource "local_file" "hello" {
  filename = "${path.module}/hello.txt"
  content  = "Hello, Terraform! Your environment is ready.\n"
}
 
output "message" {
  value = "Created: ${local_file.hello.filename}"
}

Run it:

terraform init      # downloads the 'local' provider
terraform plan      # preview: shows 1 resource to create
terraform apply     # type 'yes' to confirm
cat hello.txt       # verify the file was created
terraform destroy   # clean up

Module 00 completion criteria:

  • terraform version runs without errors.
  • Completed the "Hello, Terraform" lab — saw hello.txt get created and destroyed.
  • Have a working environment (LocalStack or AWS) ready for Module 01.
  • Understand why credentials should never be hardcoded.

Key commands

terraform version          # check version
terraform init             # initialize, download providers
terraform plan             # preview changes
terraform apply            # apply changes
terraform destroy          # destroy all managed resources
terraform fmt              # format code

➡️ Next: Module 01 — Fundamentals

Share: