A production-style DevOps automation project, runnable entirely on your own machine.
Infrastructure as Code, Linux hardening, containerised deployment, observability, automated backups, a Python operations toolkit and a CI pipeline, all in one repository.
- Overview
- Features
- Tech Stack
- Architecture
- Repository Structure
- Prerequisites
- Quick Start
- Step-by-Step Build Guide
- Component Reference
- Testing and Quality Gates
- Continuous Integration
- Security Considerations
- Operations Runbook
- Troubleshooting and Lessons Learned
- Cleanup
- Roadmap
- License
Small teams often run services by hand: clicking through consoles, SSH-ing into servers, editing config files and hoping nothing drifts. That leads to inconsistent environments, slow recovery, missing backups and no visibility into failures.
OpsForge replaces that manual process with repeatable, version-controlled automation. It automates the lifecycle of a small web service:
- describing infrastructure as code,
- hardening a Linux server,
- packaging and deploying a containerised application behind a reverse proxy,
- monitoring it with metrics, dashboards and alerts,
- backing it up and proving the backups are restorable,
- verifying every change automatically in CI.
Everything runs locally. No cloud account and no cost. Terraform uses the Docker provider, so the same Infrastructure as Code workflow (init, plan, apply, destroy) applies to local containers and networks.
| Area | What you get |
|---|---|
| Application | Flask API with /, /health, /api/info and Prometheus /metrics, served by Gunicorn |
| Containers | Multi-stage Dockerfile, non-root user, built-in health check, pinned image versions |
| Reverse proxy | Nginx with rate limiting (429), security headers, hidden version, internal-only /metrics |
| Observability | Prometheus, Node Exporter, Grafana with an auto-provisioned 9-panel dashboard, 4 alert rules |
| Linux automation | Idempotent Bash scripts for bootstrap, hardening (SSH, UFW, fail2ban, auto-updates, sysctl) and deploy |
| Safety by design | Dry-run is the default, explicit --apply, SSH lock-out protection, config validation with rollback |
| Backup and recovery | Timestamped archives, SHA-256 checksums, retention, safe restore, daily systemd timer |
| Python toolkit | opsforge CLI: health checks, backup verification, Markdown status reports (30 pytest tests) |
| Infrastructure as Code | Terraform (Docker provider): network, app and Nginx containers, validated inputs, idempotent |
| CI | GitHub Actions: ShellCheck, flake8, pytest, Terraform validate, Docker build and real smoke test |
| Layer | Technology | Version | Purpose |
|---|---|---|---|
| Infrastructure as Code | Terraform with kreuzwerker/docker provider |
>= 1.5, provider ~> 3.0 |
Network and containers for an isolated environment |
| Scripting | Bash | 5.x | Bootstrap, hardening, deploy, backup, restore |
| Automation | Python | 3.12 (Docker/CI), 3.x locally | Ops CLI, tests, Flask app |
| Operating system | Linux (Debian/Ubuntu) | Ubuntu 24.04 tested | systemd, UFW, fail2ban, unattended-upgrades, sysctl |
| Containers | Docker Engine and Compose v2 | any recent | Packaging and orchestration |
| Web application | Flask and Gunicorn | 3.1.0 / 23.0.0 | Demo service |
| Reverse proxy | Nginx | 1.27-alpine | Edge protection |
| Metrics | Prometheus, Node Exporter | v2.55.1, v1.8.2 | Collection and alert rules |
| Dashboards | Grafana | 11.4.0 | Visualisation |
| Quality | ShellCheck, flake8, pytest, promtool, actionlint | latest stable | Linting and validation |
| CI | GitHub Actions | Automated quality gates |
flowchart LR
user["User / Browser"]
op["Operator"]
subgraph host["Linux host"]
subgraph net["Docker network: opsforge-net"]
nginx["Nginx 1.27<br/>rate limit, security headers<br/>blocks /metrics"]
app["Flask app<br/>Gunicorn :5000<br/>/health /api/info /metrics"]
prom["Prometheus<br/>scrape every 15s<br/>7 day retention"]
node["Node Exporter<br/>host metrics"]
graf["Grafana<br/>provisioned dashboard"]
end
subgraph vol["Docker volumes"]
pdata[("prometheus-data")]
gdata[("grafana-data")]
end
timer["systemd timer<br/>daily 02:30"]
backup["backup.sh"]
arch[("backups/<br/>tar.gz + sha256")]
end
user -->|"HTTP :8080"| nginx
nginx -->|"proxy_pass"| app
prom -->|"scrape /metrics"| app
prom -->|"scrape :9100"| node
graf -->|"PromQL queries"| prom
prom --- pdata
graf --- gdata
op -->|"127.0.0.1:3000"| graf
op -->|"127.0.0.1:9090"| prom
timer --> backup
backup -->|"config + Grafana volume"| arch
gdata -.-> backup
Key design points:
- Only Nginx is published to the network (port 8080). The app has no published port.
- Prometheus and Grafana are bound to
127.0.0.1and are not reachable from other machines. - Prometheus scrapes the app directly on the internal network, which is why Nginx can safely return
403for/metrics.
flowchart TD
dev["Developer commit"] --> push["git push to main / pull request"]
push --> ci{"GitHub Actions CI"}
ci --> sc["ShellCheck<br/>all scripts"]
ci --> py["flake8 + pytest<br/>30 tests"]
ci --> tf["terraform fmt<br/>init, validate"]
ci --> dk["Docker job"]
dk --> dk1["compose config"]
dk1 --> dk2["promtool check config + rules"]
dk2 --> dk3["Grafana JSON validation"]
dk3 --> dk4["Build image"]
dk4 --> dk5["Start app + Nginx"]
dk5 --> dk6["Smoke test:<br/>health, headers, /metrics = 403"]
sc --> gate{"All jobs green?"}
py --> gate
tf --> gate
dk6 --> gate
gate -->|"yes"| ok["Change is safe to merge"]
gate -->|"no"| fix["Fix and push again"]
fix --> push
sequenceDiagram
autonumber
participant T as systemd timer
participant B as backup.sh
participant D as Docker
participant A as backups/
participant V as opsforge verify-backup
participant R as restore.sh
T->>B: trigger daily at 02:30
B->>B: stage config files
B->>D: tar Grafana volume (read-only mount)
D-->>B: grafana-data.tar.gz
B->>A: write archive + SHA-256 checksum
B->>A: prune, keep newest N
V->>A: verify checksum, structure, safe paths, freshness
Note over R,A: Disaster recovery
R->>A: verify checksum + reject unsafe paths
R->>R: extract to a separate directory
R->>D: optional: restore volume (asks to confirm)
flowchart TD
img_app["data.docker_image.app<br/>local image opsforge-app:dev"]
img_nginx["docker_image.nginx<br/>keep_locally = true"]
net["docker_network.main<br/>opsforge-dev-net"]
app["docker_container.app<br/>caps dropped, no-new-privileges"]
nginx["docker_container.nginx<br/>published on :8081"]
img_app --> app
net --> app
net --> nginx
img_nginx --> nginx
app --> nginx
opsforge/
├── .github/workflows/ci.yml # CI pipeline (4 jobs)
├── app/
│ ├── app.py # Flask service with Prometheus metrics
│ ├── Dockerfile # Multi-stage, non-root, health check
│ ├── requirements.txt
│ └── .dockerignore
├── nginx/
│ └── default.conf # Reverse proxy, rate limit, security headers
├── monitoring/
│ ├── prometheus/
│ │ ├── prometheus.yml # Scrape configuration
│ │ └── alert_rules.yml # 4 alert rules
│ └── grafana/
│ ├── provisioning/ # Data source + dashboard provider
│ └── dashboards/opsforge.json
├── scripts/
│ ├── lib/common.sh # Logging, dry-run helpers
│ ├── bootstrap.sh # Packages, Docker, deploy user
│ ├── harden.sh # SSH, UFW, fail2ban, updates, sysctl
│ ├── deploy.sh # up / down / status / logs
│ ├── backup.sh # Archive + checksum + retention
│ ├── restore.sh # Verify + safe extract
│ └── install-timer.sh # Install systemd units
├── systemd/
│ ├── opsforge-backup.service
│ └── opsforge-backup.timer
├── terraform/
│ ├── versions.tf variables.tf main.tf outputs.tf
│ ├── example.tfvars
│ └── .terraform.lock.hcl # Provider version lock
├── tools/
│ ├── opsforge/ # Python CLI package
│ │ ├── cli.py health.py backup.py report.py
│ └── tests/ # 30 pytest tests
├── compose.yaml # Full local stack
├── .env.example # Configuration template
├── pytest.ini .flake8 .shellcheckrc .gitignore
├── LICENSE
└── README.md
| Tool | Check command | Notes |
|---|---|---|
| Git | git --version |
|
| Docker Engine and Compose v2 | docker --version and docker compose version |
Your user must be able to run docker |
| Terraform | terraform --version |
>= 1.5 |
Python 3 with venv |
python3 --version |
sudo apt install python3-venv if needed |
| curl | curl --version |
Used in smoke tests |
Free ports: 8080 (Nginx), 8081 (Terraform environment), 3000 (Grafana), 9090 (Prometheus). They can be changed through .env.
# 1. Clone
git clone https://github.com/sonujha78/opsforge.git
cd opsforge
# 2. (Optional) configure
cp .env.example .env
# 3. Deploy the whole stack and wait until it is healthy
bash scripts/deploy.sh up
# 4. Try it
curl -s localhost:8080/health
curl -s localhost:8080/api/infoOpen the tools in your browser:
| Service | URL | Notes |
|---|---|---|
| Application (via Nginx) | http://localhost:8080 | |
| Grafana | http://localhost:3000 | Login admin / admin (change it, see Security) |
| Prometheus | http://localhost:9090 | Alerts at /alerts |
In Grafana: Dashboards → OpsForge → OpsForge Overview.
Stop everything:
bash scripts/deploy.sh downThe project was built in small, tested steps. Each step is one commit, so the Git history reads as a tutorial. Follow these steps to rebuild the project from scratch.
Create the repository (public, MIT licence), clone it, and add the folder layout and a .gitignore that excludes Terraform state, Python caches, secrets and local runtime data.
mkdir -p terraform scripts app monitoring tools systemd docs .github/workflows- Endpoints:
/,/health,/api/info,/metrics. - Metrics: request counter and latency histogram, labelled by method, endpoint and status.
- Dockerfile: multi-stage build, runs as UID 1001,
HEALTHCHECK, Gunicorn with one worker and four threads (one process keeps Prometheus counters consistent).
docker build -t opsforge-app:dev ./app- Nginx proxies to the app and is the only published service.
- Rate limit: 10 requests/second per IP with a burst of 20, returns
429when exceeded. - Headers:
X-Content-Type-Options,X-Frame-Options: DENY,Referrer-Policy,Permissions-Policy; Nginx version hidden. /metricsreturns403at the edge.
Verification: 200 and 429 responses appear when sending 60 quick requests.
- Prometheus scrapes the app, itself and Node Exporter every 15 seconds.
- Grafana is provisioned from files: data source and dashboard are loaded automatically.
- Alert rules:
AppDown,HighErrorRate,HighCpuUsage,LowDiskSpace.
- All scripts use
set -euo pipefail, structured logging and a sharedlib/common.sh. - Dry-run is the default. Nothing changes until
--applyis passed. harden.shrefuses to disable SSH password login when noauthorized_keysexists, validatessshd -tand reverts on failure.- Verified by running
--applyinside a disposable Ubuntu 24.04 container, including a second run to prove idempotency.
backup.sharchives configuration and the Grafana volume, writes a SHA-256 checksum, keeps the newestKEEPbackups.restore.shverifies the checksum, rejects archives with absolute or..paths, extracts to a separate directory and never overwrites the live project.install-timer.shrenders and installs a daily timer.
A standard-library-only CLI with unit tests that use a local throwaway HTTP server and generated archives (see Section 9.5).
python3 -m venv .venv && source .venv/bin/activate
pip install -r tools/requirements-dev.txt
flake8 tools && pytest -vAn isolated dev environment with its own network and containers (see Section 9.6).
cd terraform
terraform init
terraform plan -var-file=example.tfvars -out=tfplan
terraform apply tfplanA four-job GitHub Actions workflow that lints, tests, validates and smoke-tests every push and pull request.
This README, with architecture diagrams, a full reference and a runbook.
| Endpoint | Method | Description |
|---|---|---|
/ |
GET | Welcome message and version |
/health |
GET | Status and uptime in seconds |
/api/info |
GET | Service name, version, environment, hostname |
/metrics |
GET | Prometheus metrics (blocked at Nginx, reachable on the internal network) |
Custom metrics:
opsforge_http_requests_total{method, endpoint, status}opsforge_http_request_duration_seconds{endpoint}(histogram)
| Setting | Value |
|---|---|
| Listen port (container) | 80, published as ${NGINX_PORT:-8080} |
| Rate limit | 10 r/s per IP, burst 20, status 429 |
| Upstream | app:5000 |
/metrics |
403 |
| Timeouts | connect 5s, read 30s |
Alert rules
| Alert | Condition | For | Severity |
|---|---|---|---|
AppDown |
up{job="opsforge-app"} == 0 |
1m | critical |
HighErrorRate |
5xx ratio above 5% | 2m | warning |
HighCpuUsage |
CPU above 80% | 5m | warning |
LowDiskSpace |
Less than 15% free on / |
5m | critical |
Grafana dashboard panels: App Status, Total Requests, CPU Usage, Memory Usage, Request Rate by Endpoint, p95 Latency by Endpoint, CPU %, Memory %, Disk % (root).
All state-changing scripts default to dry-run.
| Script | Usage | Purpose |
|---|---|---|
bootstrap.sh |
bootstrap.sh [--apply] |
Base packages, Docker, deploy user. Env: DEPLOY_USER, SKIP_DOCKER |
harden.sh |
harden.sh [--apply] [--only ssh,firewall,...] |
Tasks: ssh, firewall, fail2ban, updates, sysctl. Env: SSH_PORT |
deploy.sh |
deploy.sh {up|down|status|logs} |
Validate, build, start, wait for health, smoke test |
backup.sh |
backup.sh |
Env: BACKUP_DIR, KEEP (default 7), GRAFANA_VOLUME |
restore.sh |
restore.sh <archive> [--target DIR] [--restore-volume] [--yes] |
Verify and extract |
install-timer.sh |
install-timer.sh [--apply] |
Install the systemd service and timer |
What harden.sh configures:
| Task | Result |
|---|---|
ssh |
Root login off, password login off, key-only, max 3 auth tries, drop-in file 00-opsforge.conf |
firewall |
UFW default deny incoming, SSH rate-limited, 80 and 443 open |
fail2ban |
1h ban after 5 failures in 10 minutes |
updates |
Automatic security updates |
sysctl |
Reverse-path filtering, SYN cookies, no source routing or redirects, ASLR |
Warning:
harden.sh --applyandbootstrap.sh --applymodify SSH and the firewall. Run them on a server or disposable VM/container, never casually on your daily laptop. Test them safely like this:docker run --rm -v "$PWD/scripts:/opt/scripts:ro" -e SKIP_DOCKER=1 ubuntu:24.04 \ bash -c 'bash /opt/scripts/bootstrap.sh --apply'
python3 -m tools.opsforge health # exit code 0 if all UP, 1 otherwise
python3 -m tools.opsforge health --json
python3 -m tools.opsforge verify-backup --backup-dir backups --max-age-hours 26
python3 -m tools.opsforge report --output status.md| Command | Checks |
|---|---|
health |
App via Nginx, Prometheus and Grafana endpoints; custom ones via --url NAME=URL |
verify-backup |
SHA-256 checksum, readable archive, no unsafe paths, required files, freshness |
report |
Markdown report with overall status HEALTHY or DEGRADED |
Because health and verify-backup return meaningful exit codes, they plug straight into cron, systemd or any monitoring system.
Creates an isolated environment next to the Compose stack (different names, port 8081), so both can run at the same time.
| Resource | Purpose |
|---|---|
data.docker_image.app |
Reads the local opsforge-app:dev image |
docker_image.nginx |
Pulls Nginx; keep_locally = true so shared images are never deleted |
docker_network.main |
opsforge-<env>-net |
docker_container.app |
App with all capabilities dropped and no-new-privileges |
docker_container.nginx |
Proxy using the same nginx/default.conf |
| Variable | Default | Validation |
|---|---|---|
environment |
dev |
2-16 chars, lowercase letters, digits, hyphens |
nginx_port |
8081 |
1024-65535 |
app_image |
opsforge-app:dev |
|
nginx_image |
nginx:1.27-alpine |
|
app_version |
1.0.0 |
cd terraform
terraform fmt -check -recursive
terraform init && terraform validate
terraform plan -var-file=example.tfvars -out=tfplan # 4 to add
terraform apply tfplan
terraform destroy -var-file=example.tfvars| Variable | Default | Description |
|---|---|---|
APP_VERSION |
1.0.0 |
Version reported by the app |
APP_ENV |
local |
Environment name |
NGINX_PORT |
8080 |
Host port for Nginx |
PROMETHEUS_PORT |
9090 |
Host port (localhost only) |
GRAFANA_PORT |
3000 |
Host port (localhost only) |
GRAFANA_ADMIN_PASSWORD |
admin |
Change this |
| Gate | Command | Result |
|---|---|---|
| Shell lint | shellcheck -x scripts/*.sh scripts/lib/common.sh |
clean |
| Python lint | flake8 tools |
clean |
| Unit tests | pytest -v |
30 passed |
| Terraform | terraform fmt -check, validate |
clean |
| Prometheus | promtool check config (includes alert rules) |
valid |
| Compose | docker compose config -q |
valid |
| Workflow syntax | actionlint |
clean |
Test coverage by area:
| Test module | What it proves |
|---|---|
test_health.py |
Healthy, 500, custom expected status, connection refused, non-HTTP scheme rejected |
test_backup.py |
Good archive, missing or tampered checksum, invalid tar, missing files, unsafe paths, stale backup, volume requirement, latest selection |
test_report.py |
Healthy and degraded reports, missing backup |
test_cli.py |
Argument parsing, exit codes, JSON output, report file |
Scenario tests that were run by hand:
- Rate limiting under load: 26 requests
200, 34 requests429. /metricsreturns403at the edge; port 5000 is not reachable from outside.- Hardening applied inside a disposable container, then run again (idempotent).
- Lock-out protection refused to apply SSH hardening without keys.
- Backup retention with
KEEP=2left exactly two archives. - A tampered archive was rejected by
restore.shand byverify-backup. - Grafana volume restored into a temporary test volume.
- Stopping Grafana turned the health check red (exit code 1) and the report
DEGRADED. - Terraform: second
planshows no changes; an invalid port is rejected;destroyleaves nothing behind.
Workflow: .github/workflows/ci.yml. It runs on pushes to main, pull requests and manual dispatch, with read-only permissions and automatic cancellation of superseded runs.
| Job | Steps |
|---|---|
| ShellCheck | Lints every script |
| Python | flake8, then pytest on Python 3.12 with pip caching |
| Terraform | fmt -check, init -backend=false, validate |
| Docker | Validate compose file, promtool check, Grafana JSON check, build image, start app and Nginx, wait for healthy, smoke test, print logs on failure, always clean up |
Implemented:
- Non-root application container, minimal base image, multi-stage build.
- Only Nginx is exposed; Prometheus and Grafana are bound to
127.0.0.1. - Nginx rate limiting, security headers, hidden version, blocked
/metrics. - Terraform containers drop all Linux capabilities and set
no-new-privileges. - Hardening script: key-only SSH, no root login, firewall, fail2ban, auto-updates, kernel network settings.
- Pinned image and dependency versions; Terraform provider lock file committed.
- Backups are created with
0600permissions in a0700folder, verified with checksums, and restores reject path traversal. - Secrets (
.env,*.pem,*.key, state files) are git-ignored.
Things to know:
- Change the default Grafana password before using this anywhere other than your own machine: set
GRAFANA_ADMIN_PASSWORDin.env. - Ports published by Docker bypass UFW rules. Publish only what you intend to expose.
- Backups may contain
.env. Treat thebackups/folder as sensitive. - This is a demonstration project. Review and adapt it before relying on it in production.
| Task | Command |
|---|---|
| Start the stack | bash scripts/deploy.sh up |
| Stop the stack (keeps data) | bash scripts/deploy.sh down |
| Status | bash scripts/deploy.sh status |
| Follow logs | bash scripts/deploy.sh logs |
| Health check | python3 -m tools.opsforge health |
| Create a backup | bash scripts/backup.sh |
| Verify the latest backup | python3 -m tools.opsforge verify-backup |
| Restore to a folder | bash scripts/restore.sh backups/<archive>.tar.gz |
| Restore Grafana data | bash scripts/deploy.sh down && bash scripts/restore.sh backups/<archive>.tar.gz --restore-volume |
| Schedule daily backups (on a server) | sudo bash scripts/install-timer.sh --apply |
| Check the timer | systemctl list-timers opsforge-backup.timer |
| Test an alert | docker compose stop app, wait about 2 minutes, open http://localhost:9090/alerts |
Disaster recovery outline:
- Clone the repository on the new machine.
- Restore the archive:
bash scripts/restore.sh <archive>. - Copy needed files from
restore/<archive>/config/(for example.env). - Restore the Grafana volume with
--restore-volume. - Run
bash scripts/deploy.sh upand confirm withpython3 -m tools.opsforge health.
| Problem | Cause | Fix |
|---|---|---|
Nginx container stays unhealthy although it serves traffic |
In Alpine, localhost resolves to IPv6 ::1 first, but the config only listens on IPv4 |
The health check uses 127.0.0.1 instead of localhost |
ShellCheck reports SC1091 "Not following" |
It resolved source paths from the working directory |
.shellcheckrc with source-path=SCRIPTDIR and external-sources=true |
ShellCheck SC2015 on A && B || C |
Not a true if-then-else | Split into two separate checks |
pip install refused on Ubuntu |
System Python is externally managed | Use a virtual environment (python3 -m venv .venv) |
| Port already in use | Another service uses 8080, 3000 or 9090 | Change NGINX_PORT, GRAFANA_PORT or PROMETHEUS_PORT in .env |
terraform plan cannot read opsforge-app:dev |
The image has not been built | docker build -t opsforge-app:dev ./app |
Everything returns 429 in a test loop |
Rate limit is working | Add a short sleep between requests |
Lessons that shaped the design:
- A
health: startingstatus is not proof of health. Always verify the final status, and let the deploy script do it. - Make dangerous automation safe by default: dry-run first, explicit
--apply, lock-out protection, validation with rollback. - Test destructive scripts in disposable containers, not on your own machine.
- A backup is only real once you have restored it. This project verifies checksums, structure and restores.
- Use
keep_locallyfor shared images so thatterraform destroycannot damage other projects.
Remove everything this project created, and nothing else.
cd ~/opsforge
# Compose stack, its network and its named volumes
docker compose down -v --remove-orphans
# Terraform environment (if it was applied)
(cd terraform && terraform destroy -auto-approve -var-file=example.tfvars)
# Project image
docker rmi opsforge-app:devTo also delete the local copy of the repository: cd ~ && rm -rf ~/opsforge.
- Alertmanager with Slack or email notifications.
- Loki and Promtail for centralised logs.
- A CD job that publishes the image to GHCR on release tags.
- Terraform remote state and an AWS target module.
- Trivy image scanning and
tflintin CI. - Ansible as an alternative to the Bash bootstrap.
- Encrypted off-host backups.
Released under the MIT License.
Built by @sonujha78. If this project helped you, consider giving it a star.