Sample Terraform Project
Directory structure
terraform-project/
|-- aws/
| |-- main.tf
| |-- variables.tf
| |-- outputs.tf
|-- azure/
| |-- main.tf
| |-- variables.tf
| |-- outputs.tf
|-- modules/
| |-- networking/
| | |-- main.tf
| | |-- variables.tf
| | |-- outputs.tf
| |-- computing/
| | |-- main.tf
| | |-- variables.tf
| | |-- outputs.tf
| |-- databases/
| | |-- main.tf
| | |-- variables.tf
| | |-- outputs.tf
| |-- storage/
| | |-- main.tf
| | |-- variables.tf
| | |-- outputs.tf
| |-- security/
| |-- main.tf
| |-- variables.tf
| |-- outputs.tf
|-- main.tf
|-- variables.tf
|-- outputs.tf
Main.tf
module "networking" {
source = "../modules/networking"
region = "us-east-1"
}
module "computing" {
source = "../modules/computing"
vpc_id = module.networking.vpc_id
subnet_ids = module.networking.subnet_ids
}
module "databases" {
source = "../modules/databases"
vpc_id = module.networking.vpc_id
}
module "storage" {
source = "../modules/storage"
}
module "security" {
source = "../modules/security"
vpc_id = module.networking.vpc_id
}
modules/networking/main.tf:
variable "region" {}
resource "aws_vpc" "main" {
cidr_block = "10.0.0.0/16"
region = var.region
# ... other VPC configurations
}
resource "aws_subnet" "main" {
count = 3
vpc_id = aws_vpc.main.id
cidr_block = "10.0.${count.index + 1}.0/24"
availability_zone = "us-east-1a" # Modify based on your needs
map_public_ip_on_launch = true
# ... other subnet configurations
}
output "vpc_id" {
value = aws_vpc.main.id
}
output "subnet_ids" {
value = aws_subnet.main[*].id
}
modules/computing/main.tf:
variable "vpc_id" {}
variable "subnet_ids" {}
resource "aws_instance" "app_instances" {
count = 3
instance_type = "t2.micro"
ami = "ami-xxxxxxxxxxxxxx"
vpc_security_group_ids = [module.security.app_sg_id]
subnet_id = element(var.subnet_ids, count.index)
# ... other instance configurations
}
modules/databases/main.tf:
resource "aws_db_instance" "main" {
# ... database configurations
}
modules/storage/main.tf:
# Storage configurations (e.g., S3 buckets)
modules/security/main.tf:
resource "aws_security_group" "app_sg" {
vpc_id = var.vpc_id
# ... other security group configurations
}
output "app_sg_id" {
value = aws_security_group.app_sg.id
}
Usage:
-
Create the necessary directories and files as per the structure above.
-
Run the following commands in the terminal:
cd terraform-project/aws
terraform init
terraform apply
cd terraform-project/azure
terraform init
terraform apply
-
Follow the prompts to confirm the changes.
-
Once the deployment is complete, you'll have infrastructure deployed in both AWS and Azure, organized into modules for networking, computing, databases, storage, and security.