Infrastructure as Code with Terraform
Learn to manage cloud infrastructure efficiently with Terraform best practices.
Introduction
Infrastructure as Code (IaC) allows you to provision and manage infrastructure using configuration files rather than a graphical user interface. Terraform is the industry standard for IaC, supporting all major cloud providers.
Basic Concepts
- Providers: Plugins that interact with cloud APIs (e.g., AWS, Azure).
- Resources: The infrastructure components (e.g., EC2 instances, S3 buckets).
- State: Terraform keeps track of the real-world resources in a state file.
Your First Configuration
Create a main.tf file to provision an AWS EC2 instance.
terraform {
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 4.16"
}
}
required_version = ">= 1.2.0"
}
provider "aws" {
region = "us-west-2"
}
resource "aws_instance" "app_server" {
ami = "ami-830c94e3"
instance_type = "t2.micro"
tags = {
Name = "ExampleAppServerInstance"
}
}
Workflow
terraform init: Initialize the directory and download providers.terraform plan: Preview the changes.terraform apply: Execute the changes.
Modules
Modules allow you to group resources together and reuse them.
module "vpc" {
source = "terraform-aws-modules/vpc/aws"
name = "my-vpc"
cidr = "10.0.0.0/16"
azs = ["us-west-2a", "us-west-2b", "us-west-2c"]
private_subnets = ["10.0.1.0/24", "10.0.2.0/24", "10.0.3.0/24"]
public_subnets = ["10.0.101.0/24", "10.0.102.0/24", "10.0.103.0/24"]
enable_nat_gateway = true
enable_vpn_gateway = true
tags = {
Terraform = "true"
Environment = "dev"
}
}
Conclusion
Terraform enables you to version control your infrastructure, making it reproducible, testable, and collaborative.