diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml new file mode 100644 index 0000000..cc9c9ab --- /dev/null +++ b/.pre-commit-config.yaml @@ -0,0 +1,11 @@ +repos: + - repo: https://github.com/gitleaks/gitleaks + rev: v8.30.0 + hooks: + - id: gitleaks + + - repo: https://github.com/antonbabenko/pre-commit-terraform + rev: v1.109.5 + hooks: + - id: terraform_fmt + exclude: terraform\.tfvars$ diff --git a/README.md b/README.md index 221c8d9..e23da57 100644 --- a/README.md +++ b/README.md @@ -1,37 +1,112 @@ # kaapi-infra -Infrastructure as Code for Kaapi, written in Terraform. This repo is the single source of truth for everything Kaapi runs on AWS: networking (VPC, subnets, Elastic IPs), compute (ECS services behind an ALB), the RDS database, container images (ECR), configuration and secrets (SSM Parameter Store, Secrets Manager, KMS), scheduling (EventBridge), monitoring (CloudWatch) and access control (IAM). +Infrastructure as Code for Kaapi, written in Terraform. This repo is the single source of truth for what Kaapi runs on AWS: networking (VPC, subnets, route tables, Internet Gateway), compute (ECS), container images (ECR), configuration and secrets (Secrets Manager), monitoring (CloudWatch alarms, SNS alerts) and, as modules are filled in, RDS, ALB, KMS, SSM, EventBridge and IAM. -Each environment (`staging`, `prod`, and any added later) is built from the same shared modules but has its own values, its own AWS profile and account guard, and its own remote state in S3. A change applied to one environment can never affect another. +Each environment (`staging`, `prod`, and any added later) is built from the same shared modules but has its own values, its own AWS account guard and its own remote state in S3. A change applied to one environment can never affect another. -> Make infra changes here and apply them with Terraform. Do not edit these resources by hand in the AWS console: Terraform will undo or conflict with manual changes on the next apply. +> Make infra changes here and apply them through GitHub Actions. Do not edit Terraform-managed resources by hand in the AWS console: Terraform will undo or conflict with manual changes on the next apply. + +## Contents + +- [Repository structure](#repository-structure) +- [Pre-commit hooks](#pre-commit-hooks) +- [CI/CD (GitHub Actions)](#cicd-github-actions) +- [Security notes](#security-notes) ## Repository structure ![kaapi-infra folder structure: bootstrap creates the state buckets, environments wire the shared modules, and each environment keeps its state in its own S3 bucket](docs/images/folder-structure-diagram.png) -| Folder | Purpose | -|---|---| -| `bootstrap/` | One-time setup per AWS account: the S3 bucket that holds Terraform state | -| `environments/` | One folder per environment (`staging`, `prod`) that wires the modules together with that environment's values | -| `modules/` | Reusable building blocks (VPC, ECS, ECR, RDS, CloudWatch, SNS, ...) shared by all environments | -| `docs/` | Diagrams and other documentation | +``` +kaapi-infra/ +├── .github/ +│ ├── actions/terraform-plan/ # Shared init + plan step (used by PR plans and deploys) +│ │ └── redact.sh # Hides AWS IDs in plan/apply output +│ ├── workflows/ # pr-checks, pr-plan, deploy-staging, deploy-prod, plan-and-apply +│ └── CODEOWNERS +├── bootstrap/ # One-time setup per AWS account: the Terraform state bucket +├── environments/ +│ ├── staging/ # Wires the modules together with staging's values +│ └── prod/ +├── modules/ # Reusable building blocks shared by all environments +│ ├── vpc/ # VPC (root) + submodules: +│ │ ├── subnet/ # subnets of one tier (public or private) +│ │ ├── route-table/ # a route table, its routes and subnet associations +│ │ └── internet-gateway/ # the Internet Gateway +│ ├── ecs-cluster/ ecs-task-definition/ ecs-service/ +│ ├── ecr/ cloudwatch/ sns/ +│ └── rds/ alb/ iam/ kms/ ssm/ secrets-manager/ eventbridge/ elastic-ip/ ec2/ # placeholders +├── docs/ # Diagrams +├── Makefile # Local init / plan helpers +├── .env.example # Local AWS profile, region and state bucket (copy to .env.) +└── .pre-commit-config.yaml +``` + +Each environment folder contains: + +| File | Purpose | +| ---------------------------------------------------------------------- | ----------------------------------------------------------------------- | +| `main.tf` | Which modules the environment uses and how they are wired together | +| `variables.tf` | Every input, with type, default and validation | +| `constants.tfvars` | Committed, non-sensitive values (names, sizes, CIDRs, ECS config) | +| `terraform.tfvars.example` | Template for the local, never-committed `terraform.tfvars` | +| `backend.tf`, `providers.tf`, `locals.tf`, `outputs.tf`, `versions.tf` | State backend, AWS provider and default tags, naming, outputs, versions | + +Resource names follow `--`, e.g. `kaapi-staging-vpc-main`, `kaapi-staging-cluster`. Every resource is tagged `Product`, `Environment` and `ManagedBy = terraform`. + +## Pre-commit hooks + +`.pre-commit.yaml` runs these checks on every `git commit`: + +| Hook | What it does | +| -------------------- | ----------------------------------------------------------------- | +| `gitleaks` | Blocks the commit if it finds secrets (keys, tokens, passwords) | +| `terraform_fmt` | Formats changed `.tf` / `.tfvars` files (`terraform fmt`) | +| `terraform_validate` | Runs `terraform validate` in folders with changed Terraform files | -## Deploying (GitHub Actions) +One-time setup: -Changes reach AWS only through GitHub Actions, and only after approval. Nobody needs AWS credentials to contribute. +```bash +brew install pre-commit # or: pip install pre-commit, uv tool install pre-commit +pre-commit install --config pre-commit.yaml # adds the git hook to this clone +``` -| Step | Workflow | Who acts | -|---|---|---| -| Pull request | `pr-checks`: `terraform fmt -check` and `validate` for every environment (no AWS access) | Author, reviewers | -| Merge to `main` | `deploy-staging` starts and waits at **staging-plan** | — | -| Approve **staging-plan** | Plan is created and shown in the run summary | Staging approvers | -| Approve **staging-apply** | That exact saved plan is applied | Staging approvers, after reading the plan | -| Push a version tag (`v1.2.3`) on a `main` commit | `deploy-prod` starts and waits at **prod-plan** | Release manager | -| Approve **prod-plan**, then **prod-apply** | Same plan → review → apply flow for prod | Prod approvers | +Run all hooks on every file (e.g. after updating the config): +```bash +pre-commit run --all-files --config pre-commit.yaml +``` + +If `terraform_fmt` reformats a file, the commit stops: review the change, `git add` it, and commit again. `pr-checks` runs `terraform fmt -check` in CI too, so unformatted code fails there as well. + +## CI/CD (GitHub Actions) + +Changes reach AWS only through GitHub Actions, and only after approval. + +| Step | Workflow | What happens | Who acts | +| ------------------------------------------------ | ---------------- | ------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------- | +| Open or update a PR | `pr-checks` | `terraform fmt -check`, no `REPLACE_ME` left, `terraform validate` (no AWS access) | Author | +| Open or update a PR that touches Terraform | `pr-plan` | After approval of **staging-pr-plan**, plans staging with a read-only role and comments the list of changed resources on the PR | Staging approvers | +| Merge to `main` | `deploy-staging` | Waits at **staging-plan** | — | +| Approve **staging-plan** | `plan-and-apply` | Creates the plan; the full plan is in the **Plan** step log | Staging approvers | +| Approve **staging-apply** | `plan-and-apply` | Applies that exact saved plan | Staging approvers, after reading the plan | +| Push a version tag (`v1.2.3`) on a `main` commit | `deploy-prod` | Same plan → review → apply flow with **prod-plan** and **prod-apply** | Release manager, prod approvers | + +- PR plans never apply anything and skip PRs from forks. - Several merges while staging waits for plan approval: each new run cancels the waiting one, so a single approval plans and applies everything merged so far. - An apply is never cancelled midway. If state changed after a plan was made, Terraform refuses that plan; re-run the workflow to plan again. -- If a plan has no changes, the apply step is skipped. +- If a plan has no changes, the apply job is skipped. - Only tags like `v1.2.3` deploy prod, and only when the tag points to a commit on `main`. Tags such as `v1.2.3-rc1` are ignored. - Staging can also be re-run from **Actions → deploy-staging → Run workflow**. +- `pr-checks` currently validates `staging` only; `prod` will be added back once its environment is set up. + +## Security notes + +The repository is public, so its Actions logs are too. + +- **No plan output in public summaries:** the job summary and artifacts never contain plan output. The PR comment lists only resource addresses and actions. +- **IDs are redacted:** plan and apply logs go through `.github/actions/terraform-plan/redact.sh`, which hides AWS resource IDs, account IDs, UUIDs and email hashes. +- **Sensitive values stay hidden:** sensitive Terraform values show as `(sensitive value)`, and GitHub masks secrets as `***`. +- **App secret values never touch Terraform:** they stay in Secrets Manager, and Terraform only references their ARNs. +- **AWS roles:** the PR plan role is read-only and scoped to what `terraform plan` needs. The deploy role can only be assumed by the `staging-plan` / `staging-apply` (and prod) environments. +- **No secrets in commits:** `gitleaks` checks every commit locally. diff --git a/environments/prod/constants.tfvars b/environments/prod/constants.tfvars index bb9fdfa..4016bf3 100644 --- a/environments/prod/constants.tfvars +++ b/environments/prod/constants.tfvars @@ -1,5 +1,6 @@ -project = "kaapi" +product = "kaapi" environment = "production" +managed_by = "Terraform" # ECS ecs_container_insights = "enabled" # enabled | enhanced | disabled (enabled/enhanced add CloudWatch cost) diff --git a/environments/prod/locals.tf b/environments/prod/locals.tf index 6d9afa0..ba73391 100644 --- a/environments/prod/locals.tf +++ b/environments/prod/locals.tf @@ -1,9 +1,9 @@ locals { - name_prefix = "${var.project}-${var.environment}" + name_prefix = "${var.product}-${var.environment}" common_tags = { Product = "Kaapi" Environment = var.environment - ManagedBy = "terraform" + ManagedBy = var.managed_by } } diff --git a/environments/prod/variables.tf b/environments/prod/variables.tf index 2a6832c..a5f26a1 100644 --- a/environments/prod/variables.tf +++ b/environments/prod/variables.tf @@ -1,5 +1,5 @@ -variable "project" { - description = "Project name, the first part of every resource name (--...)" +variable "product" { + description = "Product name, the first part of every resource name (--...)" type = string } @@ -8,6 +8,12 @@ variable "environment" { type = string } +variable "managed_by" { + description = "Tag value for ManagedBy; e.g. Terraform etc." + type = string + default = "Terraform" +} + variable "aws_region" { description = "AWS region to deploy into" type = string diff --git a/environments/staging/constants.tfvars b/environments/staging/constants.tfvars index 41d6048..6fb094b 100644 --- a/environments/staging/constants.tfvars +++ b/environments/staging/constants.tfvars @@ -1,5 +1,6 @@ -project = "kaapi" +product = "kaapi" environment = "staging" +managed_by = "Terraform" # ECS ecs_container_insights = "disabled" # enabled | enhanced | disabled (enabled/enhanced add CloudWatch cost) @@ -48,7 +49,6 @@ ecs_task_definitions = { DOCKER_IMAGE_FRONTEND = "frontend" ENVIRONMENT = "staging" MEMORY_THRESHOLD_PERCENT = "75.0" - OTEL_ENABLED = "true" PROJECT_NAME = "Kaapi" RESOURCE_CHECK_INTERVAL = "5" RESOURCE_MONITORING_ENABLED = "True" @@ -91,8 +91,7 @@ ecs_task_definitions = { "FIRST_SUPERUSER_PASSWORD", "FRONTEND_HOST", "GCP_PROJECT_ID", - # TODO: comment for now, so we are moving the GCP_SA_KEY to the secrets manager so secret manager not store the json key so maybe we need to parse this in code level and then use it.. so will enable this after discussion with team. - # "GCP_SA_KEY", + "GCP_SA_KEY", "GCP_VERTEX_API_KEY", "GCP_VERTEX_LOCATION", "GCS_AUDIO_BUCKET", diff --git a/environments/staging/locals.tf b/environments/staging/locals.tf index 6d9afa0..ba73391 100644 --- a/environments/staging/locals.tf +++ b/environments/staging/locals.tf @@ -1,9 +1,9 @@ locals { - name_prefix = "${var.project}-${var.environment}" + name_prefix = "${var.product}-${var.environment}" common_tags = { Product = "Kaapi" Environment = var.environment - ManagedBy = "terraform" + ManagedBy = var.managed_by } } diff --git a/environments/staging/variables.tf b/environments/staging/variables.tf index 89fe400..ef9aff7 100644 --- a/environments/staging/variables.tf +++ b/environments/staging/variables.tf @@ -1,5 +1,5 @@ -variable "project" { - description = "Project name, the first part of every resource name (--...)" +variable "product" { + description = "Product name, the first part of every resource name (--...)" type = string } @@ -8,6 +8,12 @@ variable "environment" { type = string } +variable "managed_by" { + description = "Tag value for ManagedBy; e.g. Terraform etc." + type = string + default = "Terraform" +} + variable "aws_region" { description = "AWS region to deploy into" type = string