AWS Terraform Basic Guide: EC2 & RDS

This guide provides a fundamental introduction to using Terraform for provisioning Amazon EC2 instances and Amazon RDS databases. It covers the basic setup, directory structure, and essential Terraform configurations to get you started with Infrastructure as Code on AWS.

1. Prerequisites

Before you begin, ensure you have the following:

2. Directory & File Structure

It's good practice to organize your Terraform configurations into a clear directory structure. For this basic guide, we'll use a simple layout:

aws-terraform-basics/
│
├── main.tf           # Defines the main AWS resources (VPC, EC2, RDS, Security Group)
├── variables.tf      # Declares input variables for your configurations
├── outputs.tf        # Defines output values that can be easily retrieved after deployment
├── provider.tf       # Configures the AWS provider
└── .terraform/       # (Automatically created by `terraform init`) Stores provider plugins and modules

3. provider.tf

This file configures the AWS provider, telling Terraform which cloud provider to interact with and in which region.

provider "aws" {
  region = var.aws_region # Uses the 'aws_region' variable defined in variables.tf
}

4. variables.tf

This file declares the input variables that allow you to parameterize your Terraform configurations, making them more flexible and reusable.

variable "aws_region" {
  description = "The AWS region where resources will be deployed."
  type        = string
  default     = "ap-southeast-2" # Default region set to Sydney
}

variable "instance_type" {
  description = "The EC2 instance type."
  type        = string
  default     = "t3.micro" # Default instance type
}

variable "db_username" {
  description = "The master username for the RDS database."
  type        = string
  default     = "admin"
}

variable "db_password" {
  description = "The master password for the RDS admin user."
  type        = string
  sensitive   = true # Marks the variable as sensitive to prevent it from being shown in logs/outputs
}

5. main.tf

This is the core configuration file where you define your AWS resources.

VPC & Networking (for demo purposes, simplified)