Terraform Basics
๐ฅ Vibe Prompt
"Write Terraform config: AWS EC2 t3.micro with Nginx, Security Group opening port 80."
provider "aws" {
region = "ap-northeast-1"
}
resource "aws_security_group" "web_sg" {
ingress {
from_port = 80; to_port = 80; protocol = "tcp"; cidr_blocks = ["0.0.0.0/0"]
}
}
resource "aws_instance" "web" {
ami = "ami-0d527b8c"; instance_type = "t3.micro"
vpc_security_group_ids = [aws_security_group.web_sg.id]
user_data = <<-EOF
#!/bin/bash
apt update && apt install -y nginx
systemctl start nginx
EOF
}
output "public_ip" { value = aws_instance.web.public_ip }
Key Commands
terraform init # Initialize
terraform plan # Preview
terraform apply # Apply
terraform destroy # Destroy
terraform fmt # Format
Chapter Summary
- Understand core concepts and principles
- Master implementation methods and techniques
- Familiar with common issues and solutions
- Able to apply in real projects
Further Reading
- Official documentation and API references
- Open source examples on GitHub
- Technical books and online courses
- Community discussions and tech blogs
Implementation Example
Basic Example
# This section provides a complete implementation example
Steps
- Setup: Configure development environment
- Data: Prepare required data
- Implementation: Build core functionality
- Testing: Verify correctness
- Optimization: Improve performance
Common Errors
| Error Type | Cause | Solution | |------------|-------|----------| | Compilation | Syntax | Check code syntax | | Runtime | Environment | Verify dependencies installed | | Logic | Algorithm | Step-by-step debugging | | Performance | Efficiency | Use profilers |
Code Example
import sys
def main():
print("Hello, World!")
if __name__ == "__main__":
main()
References
- Official documentation
- API reference
- Open source examples
- Community discussions
Core Terraform Commands
| Command | Purpose | When to Run |
|---------|---------|-------------|
| terraform init | Initialize working directory, download providers | First, after adding providers |
| terraform plan | Preview changes without applying | Before every apply |
| terraform apply | Create or update infrastructure | After reviewing plan |
| terraform destroy | Remove all managed resources | Tear down environment |
| terraform fmt | Format code to canonical style | Before commit |
| terraform validate | Check configuration validity | During development |
| terraform output | View output values | After apply |
Typical Workflow
# 1. Write configuration (main.tf)
# 2. Initialize
export AWS_ACCESS_KEY_ID="your-key"
export AWS_SECRET_ACCESS_KEY="your-secret"
terraform init
# 3. See what will be created
terraform plan -out=tfplan
# 4. Apply the plan
terraform apply tfplan
# 5. Verify outputs
terraform output
# 6. Clean up when done
terraform destroy
Resource Types Reference
AWS Resources
resource "aws_instance" "web" {
ami = "ami-0c55b159cbfafe1f0"
instance_type = "t2.micro"
tags = {
Name = "WebServer"
}
}
resource "aws_s3_bucket" "data" {
bucket = "my-app-data-bucket"
tags = {
Environment = "Production"
}
}
resource "aws_db_instance" "database" {
allocated_storage = 20
engine = "postgres"
engine_version = "15"
instance_class = "db.t3.micro"
db_name = "myapp"
username = "admin"
password = var.db_password
}
Variables and Outputs
Input Variables
# variables.tf
variable "region" {
description = "AWS region"
type = string
default = "us-east-1"
}
variable "instance_type" {
description = "EC2 instance type"
type = string
default = "t2.micro"
}
variable "tags" {
description = "Resource tags"
type = map(string)
default = {
Environment = "Development"
Project = "MyApp"
}
}
# Usage
resource "aws_instance" "web" {
ami = "ami-abc123"
instance_type = var.instance_type
tags = var.tags
}
Output Values
# outputs.tf
output "instance_ip" {
description = "Public IP of web instance"
value = aws_instance.web.public_ip
}
output "database_endpoint" {
description = "Database connection endpoint"
value = aws_db_instance.database.address
sensitive = true
}
# Display after apply
# terraform output instance_ip
# 54.123.45.67
Providers Configuration
# providers.tf
terraform {
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 5.0"
}
random = {
source = "hashicorp/random"
version = "~> 3.5"
}
}
required_version = ">= 1.5"
}
provider "aws" {
region = var.region
# Credentials from environment variables
}
provider "random" {}
resource "random_id" "bucket_suffix" {
byte_length = 8
}
Data Sources
Data sources fetch information from existing infrastructure.
# Get the current AWS account ID
data "aws_caller_identity" "current" {}
# Get available availability zones
data "aws_availability_zones" "available" {
state = "available"
}
# Usage
output "account_id" {
value = data.aws_caller_identity.current.account_id
}
output "azs" {
value = data.aws_availability_zones.available.names
}
Summary
Terraform uses HCL to define infrastructure as code. Resources, variables, outputs, providers, and data sources are the building blocks of any Terraform project.
Key takeaways:
- HCL syntax: resource type "name" { configuration } |
- Core commands: init โ plan โ apply โ destroy |
- Variables make configurations reusable across environments |
- Outputs expose useful information after apply |
- Providers connect Terraform to cloud platforms (AWS, GCP, Azure) |
- Data sources read existing infrastructure state |
terraform fmtensures consistent code formatting |- Always review
terraform planbefore applying |
What's Next: Terraform State
The next chapter covers Terraform state management and remote backends.