TExcelTAD
Home › DevOps Capstone: Ship a Production Service › Cloud Track: EKS, RDS & ElastiCache

Cloud Track: EKS, RDS & ElastiCache

The cloud track runs the same chart, GitOps repository and dashboards on AWS, with the data tier as managed services instead of in-cluster ones. It is optional and costs money: an EKS control plane, worker nodes, a NAT gateway, a load balancer, an RDS instance and an ElastiCache node all bill by the hour while they exist (see Tracks, Repositories & Costs; check current pricing for your region). Plan to create it, work through a lesson, and destroy it in the same sitting.

The Terraform course built every piece by hand (VPC, NAT and routes, RDS, EKS). Here you compose them, using the community modules for the parts with the most moving pieces and your own code for the part that is specific to linkly.

The layout

text
linkly-infra/cloud/
├── network-cluster/   VPC (terraform-aws-modules/vpc) + EKS (terraform-aws-modules/eks)
├── data/              RDS PostgreSQL + ElastiCache + their security group   ← tested below
└── platform/          the same add-ons as the local platform root, on EKS

Three roots with separate state, applied in that order. The data tier gets its own root because its lifecycle differs: you may rebuild the cluster several times while the database stays.

Network and cluster (sample)

The community modules need the registry, so this part is a sample. Pin the module versions you have tested and read each module's upgrade guide before a major bump:

hcl
# cloud/network-cluster/main.tf
module "vpc" {
  source  = "terraform-aws-modules/vpc/aws"
  version = "~> 6.0"

  name               = "linkly"
  cidr               = "10.40.0.0/16"
  azs                = ["eu-west-1a", "eu-west-1b"]
  private_subnets    = ["10.40.0.0/19", "10.40.32.0/19"]
  public_subnets     = ["10.40.64.0/24", "10.40.65.0/24"]
  enable_nat_gateway = true
  single_nat_gateway = true            # one NAT for a practice VPC: cheaper, not zone-redundant

  public_subnet_tags  = { "kubernetes.io/role/elb" = 1 }
  private_subnet_tags = { "kubernetes.io/role/internal-elb" = 1 }
  tags                = { project = "linkly" }
}

module "eks" {
  source  = "terraform-aws-modules/eks/aws"
  version = "~> 21.0"

  name                   = "linkly"
  kubernetes_version     = "1.36"
  vpc_id                 = module.vpc.vpc_id
  subnet_ids             = module.vpc.private_subnets
  endpoint_public_access = true          # practice only: restrict with public_access_cidrs

  eks_managed_node_groups = {
    default = {
      instance_types = ["t3.large"]
      min_size       = 2
      max_size       = 3
      desired_size   = 2
    }
  }
  tags = { project = "linkly" }
}

output "node_security_group_id" { value = module.eks.node_security_group_id }
output "private_subnet_ids" { value = module.vpc.private_subnets }
output "vpc_id" { value = module.vpc.vpc_id }

The subnet tags tell the AWS Load Balancer Controller where to place load balancers. The Kubernetes version must be one EKS currently supports; check the EKS version calendar rather than copying a number.

The data tier, tested offline

This root is the one specific to linkly, so it gets tests. It takes the VPC, subnets and node security group as inputs (from the root above, through terraform_remote_state or variables in CI) and creates PostgreSQL 16 on RDS and a Valkey (Redis-compatible) replication group on ElastiCache, with staging cheap and disposable and production protected. The session validates it against the real AWS provider schema and runs five tofu test runs with a mocked AWS provider, so nothing is created and no credentials are needed:

bash · try it yourself
mkdir -p linkly-infra/cloud/data/tests && cd linkly-infra/cloud/data
cat > main.tf <<'X'
terraform {
  required_version = ">= 1.10"
  required_providers {
    aws = { source = "hashicorp/aws", version = "~> 6.0" }
  }
}

variable "environment" {
  type = string
  validation {
    condition     = contains(["staging", "production"], var.environment)
    error_message = "environment must be staging or production."
  }
}

variable "vpc_id" { type = string }
variable "private_subnet_ids" { type = list(string) }
variable "node_security_group_id" {
  description = "The EKS nodes' security group: the only source allowed to reach the data tier."
  type        = string
}

locals {
  name    = "linkly-${var.environment}"
  is_prod = var.environment == "production"
  tags    = { project = "linkly", environment = var.environment }
}

resource "aws_security_group" "data" {
  name        = "${local.name}-data"
  description = "linkly PostgreSQL and Redis, reachable from the EKS nodes only"
  vpc_id      = var.vpc_id
  tags        = local.tags
}

resource "aws_vpc_security_group_ingress_rule" "data" {
  for_each                     = { postgres = 5432, redis = 6379 }
  security_group_id            = aws_security_group.data.id
  referenced_security_group_id = var.node_security_group_id
  ip_protocol                  = "tcp"
  from_port                    = each.value
  to_port                      = each.value
  description                  = each.key
}

resource "aws_db_subnet_group" "this" {
  name       = local.name
  subnet_ids = var.private_subnet_ids
  tags       = local.tags
}

resource "aws_db_instance" "this" {
  identifier                  = local.name
  engine                      = "postgres"
  engine_version              = "16"
  instance_class              = local.is_prod ? "db.t4g.medium" : "db.t4g.micro"
  allocated_storage           = 20
  max_allocated_storage       = local.is_prod ? 100 : 20
  storage_type                = "gp3"
  storage_encrypted           = true
  db_name                     = "linkly"
  username                    = "linkly"
  manage_master_user_password = true
  db_subnet_group_name        = aws_db_subnet_group.this.name
  vpc_security_group_ids      = [aws_security_group.data.id]
  publicly_accessible         = false
  multi_az                    = local.is_prod
  backup_retention_period     = local.is_prod ? 7 : 1
  deletion_protection         = local.is_prod
  skip_final_snapshot         = !local.is_prod
  final_snapshot_identifier   = local.is_prod ? "${local.name}-final" : null
  tags                        = local.tags
}

resource "aws_elasticache_subnet_group" "this" {
  name       = local.name
  subnet_ids = var.private_subnet_ids
  tags       = local.tags
}

resource "aws_elasticache_replication_group" "this" {
  replication_group_id       = local.name
  description                = "linkly cache (${var.environment})"
  engine                     = "valkey"
  engine_version             = "8.0"
  node_type                  = "cache.t4g.micro"
  num_cache_clusters         = local.is_prod ? 2 : 1
  automatic_failover_enabled = local.is_prod
  multi_az_enabled           = local.is_prod
  subnet_group_name          = aws_elasticache_subnet_group.this.name
  security_group_ids         = [aws_security_group.data.id]
  at_rest_encryption_enabled = true
  transit_encryption_enabled = true
  tags                       = local.tags
}

output "db_host" { value = aws_db_instance.this.address }
output "db_secret_arn" { value = aws_db_instance.this.master_user_secret[0].secret_arn }
output "redis_url" { value = "rediss://${aws_elasticache_replication_group.this.primary_endpoint_address}:6379" }
X
cat > tests/data.tftest.hcl <<'X'
mock_provider "aws" {
  mock_resource "aws_db_instance" {
    defaults = {
      address            = "linkly-staging.abc123.eu-west-1.rds.amazonaws.com"
      master_user_secret = [{ secret_arn = "arn:aws:secretsmanager:eu-west-1:111122223333:secret:rds-db-staging", kms_key_id = "", secret_status = "active" }]
    }
  }
  mock_resource "aws_elasticache_replication_group" {
    defaults = { primary_endpoint_address = "master.linkly-staging.abc123.euw1.cache.amazonaws.com" }
  }
}

variables {
  vpc_id                 = "vpc-0abc"
  private_subnet_ids     = ["subnet-0aaa", "subnet-0bbb"]
  node_security_group_id = "sg-0nodes"
}

run "staging_is_small_and_disposable" {
  command = plan
  variables { environment = "staging" }
  assert {
    condition     = !aws_db_instance.this.multi_az && !aws_db_instance.this.deletion_protection && aws_db_instance.this.skip_final_snapshot
    error_message = "staging should be single-AZ and deletable"
  }
  assert {
    condition     = aws_elasticache_replication_group.this.num_cache_clusters == 1
    error_message = "staging needs one cache node"
  }
}

run "production_is_protected" {
  command = plan
  variables { environment = "production" }
  assert {
    condition     = aws_db_instance.this.multi_az && aws_db_instance.this.deletion_protection && !aws_db_instance.this.skip_final_snapshot
    error_message = "production must be multi-AZ, deletion-protected and keep a final snapshot"
  }
  assert {
    condition     = aws_elasticache_replication_group.this.automatic_failover_enabled
    error_message = "production cache must fail over"
  }
}

run "nothing_is_public_or_plaintext" {
  command = plan
  variables { environment = "production" }
  assert {
    condition     = !aws_db_instance.this.publicly_accessible && aws_db_instance.this.storage_encrypted
    error_message = "the database must be private and encrypted"
  }
  assert {
    condition     = alltrue([for r in aws_vpc_security_group_ingress_rule.data : r.referenced_security_group_id == "sg-0nodes" && r.cidr_ipv4 == null])
    error_message = "only the node security group may reach the data tier"
  }
}

run "outputs_for_the_app" {
  command = apply
  variables { environment = "staging" }
  assert {
    condition     = output.redis_url == "rediss://master.linkly-staging.abc123.euw1.cache.amazonaws.com:6379"
    error_message = "linkly needs a rediss:// (TLS) URL"
  }
}

run "rejects_unknown_environments" {
  command = plan
  variables { environment = "prod" }
  expect_failures = [var.environment]
}
X
tofu fmt -check -recursive && echo "fmt: ok"
tofu init -backend=false 2>&1 | grep -E 'Installed|initialized' | sort
tofu validate
tofu test
fmt: ok
- Installed hashicorp/aws v6.70.0 (unauthenticated)
OpenTofu has been successfully initialized!
Success! The configuration is valid.
tests/data.tftest.hcl... pass
  run "staging_is_small_and_disposable"... pass
  run "production_is_protected"... pass
  run "nothing_is_public_or_plaintext"... pass
  run "outputs_for_the_app"... pass
  run "rejects_unknown_environments"... pass

Success! 5 passed, 0 failed.

What the tests pin down:

Run Guards against
staging_is_small_and_disposable a staging database that is multi-AZ (twice the price) or can't be destroyed at the end of the day
production_is_protected production losing Multi-AZ, deletion protection, its final snapshot or cache failover in a refactor
nothing_is_public_or_plaintext a public endpoint, unencrypted storage, or a CIDR rule sneaking into the security group: only the EKS nodes' security group may connect
outputs_for_the_app the cache URL losing its rediss:// scheme: with transit_encryption_enabled, ElastiCache accepts only TLS, which linkly's newRedis handles because it accepts rediss:// URLs
rejects_unknown_environments environment = "prod" silently getting staging settings

outputs_for_the_app uses command = apply: with a mocked provider, "apply" fills computed attributes (the endpoint address) from the mock_resource defaults, so outputs can be tested too. manage_master_user_password = true means RDS generates the password and stores it in Secrets Manager; it never appears in code, variables or state (RDS in Code).

Getting the password into the pod

The chart reads DATABASE_URL from a Secret named linkly-db. On the local track, CloudNativePG creates that Secret. On AWS, the External Secrets Operator (installed by the platform root) copies it from Secrets Manager and builds the URL with a template. These objects belong in the GitOps repository; the session validates them against the operator's schemas:

bash · try it yourself
cat > external-secrets.yaml <<'X'
apiVersion: external-secrets.io/v1
kind: ClusterSecretStore
metadata:
  name: aws-secrets-manager
spec:
  provider:
    aws:
      service: SecretsManager
      region: eu-west-1      # credentials: EKS Pod Identity on the operator's service account
---
apiVersion: external-secrets.io/v1
kind: ExternalSecret
metadata:
  name: linkly-db
  namespace: linkly-production
spec:
  refreshInterval: 1h
  secretStoreRef: {kind: ClusterSecretStore, name: aws-secrets-manager}
  target:
    name: linkly-db
    template:
      data:
        url: "postgres://{{ .username }}:{{ .password | urlquery }}@linkly-production.abc123.eu-west-1.rds.amazonaws.com:5432/linkly?sslmode=require"
  data:
    - secretKey: username
      remoteRef: {key: "rds!db-0123abcd", property: username}
    - secretKey: password
      remoteRef: {key: "rds!db-0123abcd", property: password}
X
kubeconform -strict -summary -n 1 external-secrets.yaml
yq 'select(.kind == "ExternalSecret") | .spec.target.template.data.url' external-secrets.yaml
Summary: 2 resources found in 1 file - Valid: 2, Invalid: 0, Errors: 0, Skipped: 0
postgres://{{ .username }}:{{ .password | urlquery }}@linkly-production.abc123.eu-west-1.rds.amazonaws.com:5432/linkly?sslmode=require

Three details:

  • urlquery escapes the generated password, which may contain characters such as % or # that would break a URL.
  • sslmode=require encrypts the connection. verify-full also checks the server certificate, but the RDS certificate authority is not in the public bundle that distroless ships; to verify, mount the RDS CA bundle and add sslrootcert=. Decide deliberately rather than discovering it in production.
  • refreshInterval: 1h picks up a rotated password, but linkly reads DATABASE_URL only at startup: after a rotation, restart the pods (a tool like Reloader can do it on Secret changes).

The same on Google Cloud

Piece AWS (this lesson) Google Cloud
Network VPC module, NAT gateway VPC + Cloud NAT
Cluster EKS + managed node group GKE (Autopilot or Standard)
PostgreSQL RDS for PostgreSQL Cloud SQL for PostgreSQL
Redis ElastiCache (Valkey/Redis) Memorystore
Secrets to pods External Secrets + Secrets Manager External Secrets + Secret Manager
Pod identity EKS Pod Identity Workload Identity Federation for GKE

The chart, GitOps repository and alerts don't change. Azure & Google Cloud for AWS Users maps the rest.

Apply and tear down (sample)

bash
$ tofu -chdir=cloud/network-cluster apply       # roughly 15 minutes, mostly EKS
$ aws eks update-kubeconfig --name linkly --region eu-west-1
$ tofu -chdir=cloud/data apply -var environment=staging -var-file=../from-cluster.tfvars
...
Apply complete! Resources: 7 added, 0 changed, 0 destroyed.
$ tofu -chdir=cloud/platform apply

Teardown, in reverse order and before you stop for the day:

bash
kubectl delete gateway --all -A                       # releases the load balancer
tofu -chdir=cloud/platform destroy
tofu -chdir=cloud/data destroy -var environment=staging -var-file=../from-cluster.tfvars
tofu -chdir=cloud/network-cluster destroy

Production's deletion_protection makes the data destroy fail on purpose; that is the guard working. For a practice "production", switch it off in a reviewed change first.

Test yourself

Why is the data tier its own OpenTofu root?

  1. RDS needs its own provider
  2. Its lifecycle differs: the cluster can be rebuilt while the database stays, and a mistake in one root can't destroy the other
  3. OpenTofu limits roots to 20 resources
  4. It is required by the EKS module

What does command = apply give the outputs_for_the_app test run with a mocked provider?

  1. It creates real resources
  2. Computed attributes are filled from the mock defaults, so outputs built from them can be asserted
  3. It skips validation
  4. Nothing; plan and apply are identical with mocks

With transit_encryption_enabled = true on ElastiCache, what must linkly use?

  1. A plain host:port address
  2. A rediss:// URL, so go-redis connects with TLS
  3. A VPN
  4. Port 443