Refactor Terraform stacks into instance layout

This commit is contained in:
cloudneutral 2025-12-09 21:56:44 +08:00
parent acef116967
commit 28817ef7fb
38 changed files with 176 additions and 27 deletions

View File

@ -1,19 +0,0 @@
output "vpc_id" {
value = module.dev_vpc.vpc_id
description = "VPC ID for dev environment"
}
output "public_subnet_ids" {
value = module.dev_vpc.public_subnet_ids
description = "Public Subnets for dev"
}
output "private_subnet_ids" {
value = module.dev_vpc.private_subnet_ids
description = "Private Subnets for dev"
}
output "nat_gateway_id" {
value = module.dev_vpc.nat_gateway_id
description = "NAT Gateway for dev"
}

View File

@ -1,4 +1,4 @@
# envs/dev-ec2/Makefile
# instance/ec2/Makefile
render:
python ../../render_provider_backend.py

View File

@ -5,7 +5,7 @@ locals {
}
data "aws_iam_policy_document" "dev_assume" {
data "aws_iam_policy_document" "assume" {
statement {
actions = ["sts:AssumeRole"]
@ -16,11 +16,11 @@ data "aws_iam_policy_document" "dev_assume" {
}
}
module "dev_role" {
module "role" {
source = "../../modules/iam"
name = "dev-app-role"
assume_role_policy = data.aws_iam_policy_document.dev_assume.json
name = "app-role"
assume_role_policy = data.aws_iam_policy_document.assume.json
tags = local.account.tags
}

View File

@ -1,9 +1,9 @@
output "iam_role_arn" {
description = "IAM role ARN created for Terraform deployment"
value = module.dev_role.arn
value = module.role.arn
}
output "iam_role_name" {
description = "IAM role name"
value = module.dev_role.name
value = module.role.name
}

View File

@ -8,7 +8,7 @@ locals {
)
}
module "dev_vpc" {
module "vpc" {
source = "../../modules/vpc"
vpc_cidr = local.vpc_conf.vpc_cidr

View File

@ -0,0 +1,19 @@
output "vpc_id" {
value = module.vpc.vpc_id
description = "VPC ID for this instance"
}
output "public_subnet_ids" {
value = module.vpc.public_subnet_ids
description = "Public Subnet IDs"
}
output "private_subnet_ids" {
value = module.vpc.private_subnet_ids
description = "Private Subnet IDs"
}
output "nat_gateway_id" {
value = module.vpc.nat_gateway_id
description = "NAT Gateway ID"
}

View File

@ -0,0 +1,26 @@
#!/usr/bin/env bash
set -euo pipefail
# Normalize relative paths inside Terraform stacks after moving envs/* to instance/*.
# The script uses BSD sed on macOS or gsed if available.
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
ROOT_DIR="$(cd "${SCRIPT_DIR}/.." && pwd)"
cd "${ROOT_DIR}"
SED_CMD="$(command -v gsed || command -v sed)"
FILES=$(find instance -type f \( -name "main.tf" -o -name "outputs.tf" -o -name "Makefile" \))
for FILE in ${FILES}; do
echo "Rewriting paths in ${FILE}"
# Point any lingering envs/dev-* references to the new instance layout
${SED_CMD} -i'' -e 's|envs/dev-[a-zA-Z0-9_-]*/|instance/|g' "${FILE}"
# Ensure YAML lookups target the config folder two levels up
${SED_CMD} -i'' -e 's|file("${path.root}/../../config/|file("${path.root}/../../config/|g' "${FILE}"
# Keep module sources anchored on the shared modules directory
${SED_CMD} -i'' -e 's|source = "../../modules/|source = "../../modules/|g' "${FILE}"
done
echo "Path normalization complete. Review git diff for any updates."

View File

@ -0,0 +1,37 @@
#!/usr/bin/env bash
set -euo pipefail
# Move environment-specific stacks from envs/ into instance/ with environment-less names.
# Run from any directory; the script will change into the aws-cloud root automatically.
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
ROOT_DIR="$(cd "${SCRIPT_DIR}/.." && pwd)"
cd "${ROOT_DIR}"
declare -A RENAMES=(
["envs/dev-vpc"]="instance/vpc"
["envs/dev-rds"]="instance/rds"
["envs/dev-redis"]="instance/redis"
["envs/dev-kafka"]="instance/kafka"
["envs/dev-nlb"]="instance/nlb"
["envs/dev-alb"]="instance/alb"
["envs/dev-object"]="instance/s3"
["envs/dev-role"]="instance/role"
["envs/dev-ec2"]="instance/ec2"
["envs/dev-landingzone"]="instance/landingzone"
)
mkdir -p instance
for FROM in "${!RENAMES[@]}"; do
TO="${RENAMES[${FROM}]}"
if [[ -d "${FROM}" ]]; then
echo "Moving ${FROM} -> ${TO}"
git mv "${FROM}" "${TO}"
else
echo "Skipping ${FROM}; not found" >&2
fi
done
# Show the resulting structure for quick confirmation
printf "\nCurrent instance layout:\n"
find instance -maxdepth 2 -type d | sed 's/^/ /'

View File

@ -0,0 +1,86 @@
#!/usr/bin/env bash
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
ROOT_DIR="$(cd "${SCRIPT_DIR}/.." && pwd)"
cd "${ROOT_DIR}"
RUN_TERRAFORM=false
if [[ ${1:-} == "--terraform-validate" ]]; then
RUN_TERRAFORM=true
fi
status=0
if [[ -d envs ]]; then
ORPHANS=$(find envs -maxdepth 1 -type d -name 'dev-*' ! -path 'envs')
if [[ -n "${ORPHANS}" ]]; then
echo "[FAIL] Orphan environment directories detected under envs/:"
echo "${ORPHANS}" | sed 's/^/ - /'
status=1
else
echo "[OK] No orphaned envs/dev-* directories remain."
fi
else
echo "[WARN] envs/ directory not found; skipping orphan check."
fi
python <<'PY'
import pathlib
import re
import sys
root = pathlib.Path(__file__).resolve().parents[1]
instance_dir = root / "instance"
issues = []
file_pattern = re.compile(r'file\("\$\{path\.root\}/([^"}]+)"\)')
source_pattern = re.compile(r'source\s*=\s*"([\.\./][^"]+)"')
rel_hint_pattern = re.compile(r'(\.\./\.\./[^"\s]+)')
for tf in instance_dir.rglob("*.tf"):
text = tf.read_text()
for match in file_pattern.finditer(text):
rel = match.group(1)
target = (tf.parent / rel).resolve()
if not target.exists():
issues.append(f"{tf}: missing YAML target -> {target}")
for match in source_pattern.finditer(text):
rel = match.group(1)
target = (tf.parent / rel).resolve()
if not target.exists():
issues.append(f"{tf}: module source not found -> {target}")
for match in rel_hint_pattern.finditer(text):
rel = match.group(1)
target = (tf.parent / rel).resolve()
if not target.exists():
issues.append(f"{tf}: relative path hint not found -> {target}")
if issues:
print("[FAIL] Broken paths detected:")
for issue in issues:
print(f" - {issue}")
sys.exit(1)
else:
print("[OK] Terraform files reference existing relative paths.")
PY
if [[ ${RUN_TERRAFORM} == true ]]; then
if command -v terraform >/dev/null 2>&1; then
for DIR in instance/*; do
if [[ -d ${DIR} ]]; then
echo "Running terraform validate in ${DIR}" \
&& (cd "${DIR}" && terraform validate) || status=1
fi
done
else
echo "[WARN] terraform binary not found; skipping validate step."
fi
else
echo "[INFO] Terraform validate skipped (enable with --terraform-validate)."
fi
exit ${status}