AWS Builder Center
Deploying Moodle 5.2.1 on AWS with Terraform and Ansible

Deploying Moodle 5.2.1 on AWS with Terraform and Ansible

Building a secure, cost-optimized, and fully automated Learning Management System on AWS using Terraform, Ansible, Aurora Serverless v2, and AWS Secrets Manager

Cloud DevOps Engineer @ The Cloud Advisory

Table of Contents




Introduction

Moodle is the world's most widely adopted open-source Learning Management System (LMS), powering more than 300 million users across 245 countries. But while Moodle itself is free, deploying it reliably in the cloud is a different story. It demands a robust web server, a modern PHP runtime, a scalable database, secure secret management, and a well-planned network topology.
This article walks through how I designed and built DMI-LMS, a complete Moodle 5.2.1 deployment on AWS using Infrastructure as Code (IaC) with Terraform and Ansible. The entire platform — from VPC and database to the application itself — is provisioned automatically from a single terraform apply command.
Whether you are a DevOps engineer, a platform architect, or a developer who wants to move from "click-ops" to real IaC, this guide shares the architecture, the code patterns, and the hard-earned lessons from building this environment end to end.
📸 SCREENSHOT: 
Final deployed Moodle dashboard




The Challenge

The requirements for this project were specific and demanding:
Requirement
Implication
Run Moodle 5.2.1 (the latest stable branch)
Requires PHP 8.3+ and a modern MySQL-compatible database (Aurora MySQL 8.4)
Fully Infrastructure as Code
Every resource must be reproducible from version-controlled code
Zero hardcoded credentials
All secrets managed by AWS Secrets Manager, retrieved at runtime
Cost-efficient development
A DEV environment that stays small, but can scale when needed
Secure by default
Least-privilege IAM, private database subnet, IMDSv2 enforced
Self-provisioning
The EC2 instance must install and configure Moodle itself — no manual server setup
Reproducible
A new engineer should be able to deploy the whole stack in under 30 minutes
The interesting constraint was the tension between cost (a small, single-AZ dev environment) and production-readiness (managed services, encryption, and automation). The solution: a modular Terraform architecture with deliberate, documented trade-offs.



Architecture Overview

DMI-LMS runs in the eu-north-1 (Stockholm) region and is composed of six isolated Terraform modules connected by a clean dependency graph:
📸 SCREENSHOT: Architecture diagram (rendered Mermaid)



The Module Dependency Graph

Each module has a deliberate dependency ordering so Terraform can plan and parallelize effectively:

  1. networking — VPC, subnets, route tables, IGW, security groups, S3 endpoint (no dependencies)
  1. secrets — Creates the admin and S3-keys secrets before the DB depends on them (no dependencies)
  1. database — Aurora Serverless v2, depends on networking for subnets and security groups
  1. storage — S3 bucket for Moodle course content (no dependencies)
  1. iam — Role/policy wired to real ARNs from database, secrets, and storage
  1. compute — EC2 + Elastic IP; depends on networking, database, iam, and secrets
  1. monitoring — CloudWatch log group and alarms; depends on compute
This modularity means you can swap, extend, or reuse any component in another environment (staging, production) without touching the rest of the stack.



Key Design Decisions

Every architectural choice was made deliberately. These were the five decisions that mattered most:

1. Modular Terraform Architecture

Each component lives in its own module under modules/ with its own main.tf, variables.tf, outputs.tf, and versions.tf. The environment (envs/dev/) composes them and supplies real values. This is what makes the infrastructure testable, reviewable, and reusable across environments.

2. Single-AZ Development Environment

High-availability features — multi-AZ, an Application Load Balancer, and auto-scaling — were intentionally omitted. This is a development environment, and the cost and complexity are simply not justified. The trade-off is documented and clearly flagged in the codebase so it cannot be silently forgotten in production.

3. ARM64 Graviton2 Instances

The compute runs on a t4g.small (Graviton2) instance. AWS Graviton processors deliver roughly 20% better price-performance than comparable x86 instances, which is a meaningful saving for a workload that is mostly idle in development. The compute module automatically resolves the latest Ubuntu 22.04 ARM64 AMI from Canonical.

4. Serverless Database

Aurora Serverless v2 with an 0.5–2.0 ACU scaling range. The database scales down to near zero when the dev environment is idle and scales up automatically when traffic increases — giving us managed MySQL 8.4 compatibility for Moodle 5.x with almost zero idle cost. Credentials are auto-generated and managed by Aurora (no manual password rotation).

5. Secrets Manager Everywhere

No password is ever written in code, tfvars, or user data. Database credentials are generated by Aurora's manage_master_user_password, and application credentials are generated with the random_password provider. Everything is fetched at runtime by the EC2 instance using its scoped IAM role.



The Terraform Modules

Networking Module

The networking module builds a complete, self-contained VPC:
  • VPC 10.0.0.0/16 with DNS support and hostnames enabled
  • Public subnet 10.0.1.0/24 in eu-north-1a with auto-assign public IP
  • Private subnet 10.0.2.0/24 in eu-north-1b (required for the Aurora subnet group)
  • Internet Gateway with a public route table (0.0.0.0/0 → IGW)
  • S3 Gateway VPC Endpoint attached to both route tables — a free way to keep S3 traffic inside the AWS network
  • Two security groups:
  • EC2 SG: SSH (22) from your IP (auto-detected!), HTTP (80) from 0.0.0.0/0
  • DB SG: MySQL (3306) from the EC2 security group only
One neat detail: the environment auto-detects your current public IP using a http data source (checkip.amazonaws.com) and locks down SSH to exactly that address — no need to update the CIDR manually every time your IP changes.

Database Module

The database module provisions a fully managed, serverless Aurora cluster:
  • Engine: Aurora MySQL 8.4 (aurora-mysql), compatible with MySQL 8.4.7
  • Scaling: Serverless v2 between 0.5 and 2.0 ACUs
  • Encryption: storage_encrypted = true
  • Backups: 7-day retention, automated backups 03:00–04:00 UTC
  • Logs: error, slowquery, and general exported to CloudWatch
  • Credentials: manage_master_user_password = true — Aurora creates and rotates its own master password
  • Custom parameter group tuned for Moodle:
  • require_secure_transport = OFF (Moodle defaults to non-SSL connections)
  • innodb_default_row_format = DYNAMIC so utf8mb4 VARCHAR(255) indexes fit within the 3072-byte limit
The database lives in the private subnet and is only reachable from the EC2 security group — it has no public exposure at all.

Storage Module

Moodle's course content (files, uploads, backups) is stored in a dedicated S3 bucket:
  • Private: all public access blocked
  • Encrypted: AES256 server-side encryption
  • Versioned: content protection and rollback
  • CORS: configured for Moodle's direct browser uploads
  • Lifecycle: transitions to STANDARD_IA at 30 days and GLACIER_IR at 90 days, with expiration at 365 days — automatic cost control for a growing content store

IAM Module

The IAM module follows the principle of least privilege:
  • A dedicated EC2 role with an assume-role policy for ec2.amazonaws.com
  • A scoped policy granting only:
  • GetSecretValue / DescribeSecret on the specific DB, admin, and S3 secrets (never *)
  • CloudWatch Logs create/write on the specific log group
  • SSM parameter reads scoped to the project prefix
  • DescribeInstances (needed for IMDSv2 metadata lookup)
  • Conditional S3 bucket access (only when a bucket ARN is provided)

Secrets Module

Two application secrets are created here:
  1. Admin secret — username admin, a 24-character auto-generated password (with guaranteed character classes), and the admin email
  1. S3 keys secret — the IAM access key/secret key for the Moodle S3 repository plugin
Both use recovery_window_in_days = 0 so terraform destroy works cleanly in development.

Compute Module

The heart of the stack:
  • Latest Ubuntu 22.04 ARM64 AMI (resolved dynamically, owner Canonical)
  • t4g.small instance with 20 GB encrypted gp3 root volume
  • Elastic IP associated for a stable public address
  • IMDSv2 required (http_tokens = "required") — blocks SSRF-style metadata theft
  • A templatefile()-rendered user-data script that receives every value it needs (DB endpoint, secret ARNs, S3 bucket, Moodle branch) directly from Terraform
  • A lifecycle rule that ignores user_data and ami drift so that AMI updates don't cause surprise instance replacement

Monitoring Module

  • CloudWatch Log Group /aws/ec2/dmi-lms-dev with 30-day retention
  • CPU alarm — average CPU > 80% over two 5-minute periods
  • Status check alarm — any EC2 status check failure
  • Both alarms optionally fan out to an SNS topic for notifications



Security First: Secrets and Least Privilege

Security was not an afterthought — it is baked into the architecture:
  1. No hardcoded credentials. Secrets Manager holds every secret; the codebase contains zero real passwords. Credentials in terraform.tfvars are marked sensitive and the example file ships with placeholders only.
  1. Runtime retrieval. The EC2 instance never stores credentials. During bootstrap, its IAM role fetches them from Secrets Manager on demand and writes them straight into Moodle's config.php (which is created no_log and mode 640, owned by www-data).
  1. Auto-generated, auto-rotated DB password. Aurora's manage_master_user_password handles generation and rotation for the database master credentials with zero manual effort.
  1. Network isolation. The database sits in a private subnet reachable only from the EC2 security group. The EC2 instance itself only exposes SSH (locked to your IP) and HTTP.
  1. Encryption everywhere. Encrypted EBS root volume, encrypted Aurora storage, server-side encrypted S3, encrypted secrets — every layer of persistence is encrypted at rest.
  1. IMDSv2 is enforced on the instance to prevent token theft via web vulnerabilities.



Zero-Touch Bootstrapping with Ansible

The most interesting part of this project is the self-provisioning EC2 instance. When Terraform launches the instance, a user-data script takes over and completes the entire software installation — automatically. Here is how it works:

Phase 1 — System Update

apt update / apt upgrade, then installs base tooling: git, curl, jq, unzip, Python 3, and pip.

Phase 2 — Install Ansible

Installs Ansible via pip with a robust fallback chain, because cloud-init's environment doesn't always set HOME. The script verifies ansible --version after install and retries through multiple installation strategies.

Phase 3 — Public IP via IMDSv2

Uses IMDSv2 (token-based instance metadata) to fetch the Elastic IP assigned to the instance, with a 30-attempt polling loop that waits for the EIP association to propagate. This IP later becomes Moodle's $CFG->wwwroot.

Phase 4 — Pre-flight: PHP + Composer

Runs a minimal Ansible playbook that installs the full PHP 8.3 toolchain from the ondrej/php PPA (with retries for transient network issues), the AWS CLI v2, and Composer (with checksum verification of the installer). A self-healing fallback re-installs Composer manually if the playbook fails, then hard-fails only if Composer is still missing.

Phase 5 — The Main Playbook

A generated Ansible playbook with six roles completes the install:
  1. system — base packages, PHP 8.3, AWS CLI, Composer
  1. apache — enables rewrite/headers, creates Moodle directories, writes a VirtualHost pointing at dmi-lms/public, tunes php.ini (memory 256M, upload 50M, OPcache on), and restarts Apache
  1. moodle_database — waits for the Aurora cluster to be reachable (mysqladmin ping with retries), then pulls DB credentials from Secrets Manager
  1. moodle_install — idempotent: skips cloning if version.php already exists; otherwise cleans up partial clones, clones MOODLE_502_STABLE from GitHub, fixes ownership, and runs composer install
  1. moodle_config — writes config.php with the Aurora endpoint, credentials from Secrets Manager, auroramysql DB driver, and the correct wwwroot
  1. moodle_cron — enables cron and installs Moodle's every-minute scheduled-task job
  1. moodle_s3 — patches Moodle's legacy S3 repository plugin to use the modern AWS SDK v3 S3Client (Moodle 5.x requires this), seeds the S3 keys into the database from Secrets Manager
The whole bootstrap is logged to /var/log/user-data.log so every failure is diagnosable.

Why Ansible inside user-data?

This is a deliberate architecture choice. Terraform owns the AWS infrastructure; Ansible owns the software configuration. By having the EC2 instance generate and run its own playbook, we get:
  • Idempotency — re-running the playbook never breaks anything
  • Self-healing — the creates: guards and retry loops recover from transient failures
  • Reusability — the same roles also exist as a standalone Ansible project (ansible/roles/) for post-deployment management



Deploying the Infrastructure

Deployment is a linear, well-documented process:

1. Prerequisites

  • AWS CLI v2 configured (aws configure, aws sts get-caller-identity)
  • Terraform ≥ 1.5
  • An EC2 key pair in eu-north-1
aws ec2 create-key-pair \
  --key-name dmi-lms-dev-key \
  --region eu-north-1 \
  --query 'KeyMaterial' \
  --output text > ~/.ssh/dmi-lms-dev-key.pem
chmod 400 ~/.ssh/dmi-lms-dev-key.pem

2. Configure Variables

cd envs/dev
cp terraform.tfvars.example terraform.tfvars
The tfvars file controls everything — instance type, DB capacity, Moodle branch, monitoring thresholds, and the S3 keys for the repository plugin. Validation blocks in variables.tf catch typos early (e.g., invalid regions, out-of-range capacities, malformed emails).

3. Initialize, Validate, Plan, Apply

terraform init
terraform validate
terraform plan -var-file="terraform.tfvars"
terraform apply -var-file="terraform.tfvars"
terraform apply provisions all ~33 resources in the correct dependency order. Aurora takes 5–8 minutes, the EC2 bootstrap takes another 5–7.
📸 SCREENSHOT: terraform plan output showing the resource list

📸 SCREENSHOT: terraform apply completing successfully


4. Capture Outputs

terraform output
Key outputs include moodle_url, ssh_command, db_endpoint, and s3_bucket_name — everything you need to connect.

5. Verify the Bootstrap

ssh -i ~/.ssh/dmi-lms-dev-key.pem ubuntu@<EC2_IP>
sudo tail -100 /var/log/user-data.log
You should see [5/5] Running main Ansible playbook... followed by DMI-LMS Bootstrap completed successfully.

6. Complete Moodle Setup in the Browser

Open http://<EC2_IP>/ and walk through the Moodle installer — language, directory confirmation, the native MySQL driver, the Aurora endpoint, and the database credentials from Secrets Manager.
📸 SCREENSHOT: Moodle installation wizard — database settings page

📸 SCREENSHOT: Moodle environment checks page (all green)


7. Verify the Stack

curl -I http://<EC2_IP>/                    # Expect HTTP 200/302
sudo systemctl status apache2               # Apache running
php -v                                      # PHP 8.3
sudo crontab -l -u www-data                 # Moodle cron present



Cost Optimization

Cost was a first-class requirement. Here is how this architecture keeps the monthly bill down:
Decision
Savings / Rationale
t4g.small Graviton2
~20% cheaper than equivalent x86; generous dev capacity
Aurora Serverless v2 (0.5–2 ACU)
Scales to near-zero when idle; only pay for usage
Single AZ + no NAT Gateway
No NAT = ~$32/month avoided; no cross-AZ data charges
S3 Gateway VPC Endpoint
S3 traffic stays inside AWS — no internet data charges
S3 lifecycle policies
Auto-transitions old content to STANDARD_IA → GLACIER_IR, then expires
Single small EC2
One instance serves web + PHP + app; no ALB or autoscaling overhead
CloudWatch 30-day log retention
Logs automatically expire
The whole development environment can run for well under the cost of a single on-demand large instance, and it is trivially destroyable with terraform destroy when not in use.



S3 Setup and Accessing Data into Moodle:

We saved Data in S3 which we can access in Moodle : 

Content we have added: 

We can pick the file which we want to add on Dashboard:


Monitoring and Observability

No production-worthy deployment is complete without visibility:
  • CloudWatch Log Group collects application and system logs with a 30-day retention window
  • High-CPU alarm triggers when average CPU exceeds 80% for two consecutive 5-minute windows
  • Status-check alarm catches instance and system check failures immediately
  • Both alarms can push to SNS (email/SMS) for proactive alerting
  • Aurora exports error, slowquery, and general logs to CloudWatch for database troubleshooting



What I Learned

Building this taught me more than any textbook exercise. Some of the hardest-won lessons:

1. Module dependency ordering matters

The subtle bug in this stack was that the EC2 instance profile depends on ARNs produced by the database, secrets, and storage modules. Getting the depends_on graph right in envs/dev/main.tf was essential to avoid "resource not found" failures during apply.

2. templatefile() variable escaping is treacherous

Inside a user-data script that itself generates an Ansible playbook (which itself writes PHP), you have three levels of templating. Terraform's $${} escaping vs. bash variables vs. Ansible's {{ }} took real discipline to get right:
  • $${HOME} → bash variable (Terraform passes through)
  • {{ moodle.db_host }} → Ansible variable (untouched by Terraform)
  • ${DB_SECRET_ARN} → Terraform substitution (injected at apply time)

3. IMDSv2 is non-negotiable

Enforcing token-based instance metadata (http_tokens = "required") is a simple, free defense against the SSRF attacks that have historically compromised EC2 instances.

4. Idempotency pays for itself

Every Ansible task is written with guards (creates:, when:, stat checks) so that re-running the bootstrap — a routine necessity after transient failures — is always safe. The "check if version.php exists before cloning Moodle" guard alone saved me hours of reinstall pain.

5. ARM64 is not a compromise

Graviton2 ran the entire stack (Ubuntu, Apache, PHP 8.3, Moodle, AWS CLI, Composer) without a single x86-only dependency. The AWS CLI installer even has a dedicated linux-aarch64 build. ARM64 for a PHP/MySQL workload is a pure win.

6. Aurora Serverless v2 is genuinely zero-ops

The manage_master_user_password flag means I never once handled a database password — Aurora generates, stores, and rotates it automatically. The Moodle config just reads it from Secrets Manager at bootstrap.



Roadmap to Production The DEV environment is intentionally lean. Promoting this stack to staging or production means activating the features that were deliberately omitted:

  • [ ] Multi-AZ Aurora for high availability and failover
  • [ ] Application Load Balancer + Auto Scaling Group for horizontal scaling and zero-downtime deploys
  • [ ] HTTPS via ACM + CloudFront (or an ALB with a TLS listener) to terminate SSL and cache content at the edge
  • [ ] WAF to protect the application from web attacks
  • [ ] Private subnets with a NAT Gateway for internet egress from private resources
  • [ ] EFS for shared dataroot storage across multiple instances
  • [ ] ElastiCache (Redis) for Moodle session and cache scaling
  • [ ] S3 backend + DynamoDB locking for Terraform state (already scaffolded in envs/dev/backend.tf and bootstrap/)
  • [ ] Hardening + backup automation — the repo already includes Ansible hardening and monitoring roles ready to activate



Conclusion

DMI-LMS proves that a serious, production-minded LMS deployment on AWS does not require a big budget or days of click-ops. With Terraform owning the infrastructure, Ansible owning the software, Aurora Serverless v2 handling the database, and Secrets Manager protecting every credential, the entire platform deploys from a single command — reproducibly, securely, and cheaply.
The repository is structured so any team can reuse it:
├── modules/            # Reusable, environment-agnostic building blocks
│   ├── networking/     # VPC, subnets, IGW, SG, S3 endpoint
│   ├── secrets/        # Admin + S3 key secrets
│   ├── database/       # Aurora Serverless v2
│   ├── storage/        # S3 content bucket
│   ├── iam/            # Least-privilege role & policy
│   ├── compute/        # EC2 + EIP + user-data bootstrap
│   └── monitoring/     # CloudWatch logs & alarms
├── envs/
│   └── dev/            # Dev environment composition + tfvars
├── ansible/            # Standalone Ansible roles for post-deploy management
└── bootstrap/          # Optional S3 backend provisioning
If you are planning to host Moodle (or any PHP/MySQL workload) on AWS, I hope this blueprint saves you the trial and error it cost me. Start with a modular Terraform design, lean on managed services for the hard parts, enforce IMDSv2 and least-privilege IAM from day one, and let Ansible do the boring part of installing software.
Deploy fast, secure everything, and let the cloud do the heavy lifting.


The complete infrastructure code is available in this repository. Feel free to clone it, adapt the module naming to your project, and make it yours.
Questions or feedback? Drop a response below — I'd love to hear how your LMS deployment goes.



Appendix: Full Resource Inventory

#
Resource
AWS Service
Terraform Module
1
VPC (10.0.0.0/16)
VPC
networking
2
Public Subnet (10.0.1.0/24)
VPC
networking
3
Private Subnet (10.0.2.0/24)
VPC
networking
4
Internet Gateway
VPC
networking
5
Public Route Table
VPC
networking
6
Private Route Table
VPC
networking
7
S3 Gateway Endpoint
VPC
networking
8
EC2 Security Group
VPC
networking
9
DB Security Group
VPC
networking
10
EC2 Instance (t4g.small)
EC2
compute
11
Elastic IP
EC2
compute
12
EBS Volume (gp3, 20 GB)
EC2
compute
13
Aurora Cluster (8.4)
RDS
database
14
Aurora Serverless Instance
RDS
database
15
DB Cluster Parameter Group
RDS
database
16
DB Subnet Group
RDS
database
17
S3 Bucket (versioned, encrypted)
S3
storage
18
IAM Role
IAM
iam
19
IAM Policy
IAM
iam
20
IAM Instance Profile
IAM
iam
21
Admin Secret
Secrets Manager
secrets
22
S3 Keys Secret
Secrets Manager
secrets
23
CloudWatch Log Group
CloudWatch
monitoring
24
CPU Alarm
CloudWatch
monitoring
25
Status Check Alarm
CloudWatch
monitoring



Appendix: Useful Commands

# Deploy
terraform apply -var-file="terraform.tfvars"
# Get outputs
terraform output moodle_url
terraform output ssh_command
# Check bootstrap (from EC2)
sudo tail -f /var/log/user-data.log
# Get admin credentials
aws secretsmanager get-secret-value \
  --secret-id dmi-lms-dev-admin-secret \
  --region eu-north-1 \
  --query 'SecretString' --output text
# Re-run bootstrap after user-data changes
terraform taint module.compute.aws_instance.main
terraform apply -var-file="terraform.tfvars"
# Destroy everything
terraform destroy -var-file="terraform.tfvars"
After Completion of Project we need to destroy the resources.

Any opinions in this article are those of the individual author and may not reflect the opinions of AWS.
Enjoyed reading this content? Let the author know!

Your likes, comments, shares, and saves help creators reach more builders.

Loading recommendations

Loading article