Infrastructure as Code: Terraform
Infrastructure as Code enables reproducible infrastructure. This article covers Terraform fundamentals.
Introduction
Infrastructure as Code provides:
- Reproducible infrastructure
- Version control
- Automation
- Consistency
- Scalability
Terraform Basics
Terraform Configuration
# โ
Good: Terraform configuration
terraform {
required_version = ">= 1.0"
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 4.0"
}
}
}
provider "aws" {
region = "us-east-1"
}
# โ
Good: Create EC2 instance
resource "aws_instance" "app" {
ami = "ami-0c55b159cbfafe1f0"
instance_type = "t2.micro"
tags = {
Name = "app-server"
}
}
# โ
Good: Create security group
resource "aws_security_group" "app" {
name = "app-sg"
ingress {
from_port = 80
to_port = 80
protocol = "tcp"
cidr_blocks = ["0.0.0.0/0"]
}
egress {
from_port = 0
to_port = 0
protocol = "-1"
cidr_blocks = ["0.0.0.0/0"]
}
}
# โ
Good: Output values
output "instance_ip" {
value = aws_instance.app.public_ip
}
Commands
Terraform Commands
# โ
Good: Initialize Terraform
terraform init
# โ
Good: Validate configuration
terraform validate
# โ
Good: Plan changes
terraform plan
# โ
Good: Apply changes
terraform apply
# โ
Good: Destroy infrastructure
terraform destroy
# โ
Good: Show state
terraform show
# โ
Good: Format code
terraform fmt
Best Practices
-
Use variables:
# โ Good: Use variables variable "instance_type" { type = string default = "t2.micro" } resource "aws_instance" "app" { instance_type = var.instance_type } # โ Bad: Hardcoded values resource "aws_instance" "app" { instance_type = "t2.micro" } -
Use modules:
# โ Good: Use modules module "vpc" { source = "./modules/vpc" cidr = "10.0.0.0/16" } # โ Bad: Inline configuration resource "aws_vpc" "main" { cidr_block = "10.0.0.0/16" } -
Use state files:
# โ Good: Remote state terraform { backend "s3" { bucket = "terraform-state" key = "prod/terraform.tfstate" region = "us-east-1" } } # โ Bad: Local state # Default local state
Summary
Infrastructure as Code is essential. Key takeaways:
- Define infrastructure
- Use variables
- Create modules
- Use remote state
- Version control
- Automate deployment
- Manage resources
- Follow best practices
Related Resources
- Terraform Documentation
- AWS Provider
- Terraform Modules
- Terraform Best Practices
- Infrastructure as Code
Next Steps
- Learn about CI/CD
- Explore Monitoring
- Study Cloud Deployment
- Practice Terraform
- Automate infrastructure
Comments