Terraform Basics for AWS
Manage infrastructure as code with Terraform.
Installation & Setup
# Install Terraform
brew install terraform
# Configure AWS credentials
export AWS_ACCESS_KEY_ID="your-key"
export AWS_SECRET_ACCESS_KEY="your-secret"
Basic Configuration
# main.tf
terraform {
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 5.0"
}
}
}
provider "aws" {
region = "us-east-1"
}
# Create VPC
resource "aws_vpc" "main" {
cidr_block = "10.0.0.0/16"
tags = {
Name = "main-vpc"
}
}
# Create EC2 instance
resource "aws_instance" "web" {
ami = "ami-0c55b159cbfafe1f0"
instance_type = "t3.micro"
tags = {
Name = "web-server"
}
}
Variables and Outputs
# variables.tf
variable "environment" {
description = "Deployment environment"
type = string
default = "dev"
}
variable "instance_type" {
type = map(string)
default = {
dev = "t3.micro"
prod = "t3.large"
}
}
# outputs.tf
output "instance_ip" {
value = aws_instance.web.public_ip
}
Terraform Commands
# Initialize project
terraform init
# Preview changes
terraform plan
# Apply changes
terraform apply
# Destroy infrastructure
terraform destroy
State Management
# Use remote state with S3
terraform {
backend "s3" {
bucket = "my-terraform-state"
key = "prod/terraform.tfstate"
region = "us-east-1"
}
}
Terraform enables reproducible, version-controlled infrastructure deployments.
Comments (0)
Leave a Comment
No comments yet. Be the first to share your thoughts!