From On-Premises Kubernetes to Amazon EKS: A Complete Cloud Migration Guide
A Practical, End-to-End Tutorial for Migrating Containerized Workloads, Persistent Data, Networking and Infrastructure to AWS.
Executive summary
Migrating Kubernetes to the cloud is not copying YAML from one cluster to another. Over the years, an on-premises cluster accumulates decisions tied to the datacenter: StorageClasses bound to Ceph or NFS, hardware load balancers, internal DNS, private registries, certificates issued by a corporate CA and databases running as StatefulSets. Each of those pieces needs an explicit decision: keep, replace or modernize.
This guide walks through a real migration from start to finish using a concrete scenario: ACME Technologies, a company with a kubeadm cluster of 3 control plane nodes and 4 workers running a frontend, a Spring Boot backend, PostgreSQL, Redis, ingress-nginx, Prometheus and Grafana. The target is Amazon EKS inside a multi-account Landing Zone built with Terraform.
The main decisions of the proposed architecture are:
| Decision | Choice for ACME | Reason |
|---|---|---|
| Container platform | Amazon EKS with Managed Node Groups + Karpenter | Managed control plane and efficient node scaling |
| Database | Amazon RDS for PostgreSQL Multi-AZ (replatform) | Removes the burden of running backups, HA and patching for a critical StatefulSet |
| Cache | Amazon ElastiCache (Valkey or Redis OSS) | Redis is used as a cache: it is rebuilt, not migrated |
| Ingress | AWS Load Balancer Controller + ALB | ingress-nginx was retired by the Kubernetes community |
| Manifest migration | Helm/Kustomize in Git + Argo CD, with Velero as a safety net | Reproducibility, auditability and rollback |
| Data migration | PostgreSQL logical replication (or AWS DMS) with a cutover of minutes | Minimal, verifiable downtime |
| Pod identity | EKS Pod Identity | Temporary credentials per ServiceAccount, no access keys |
| Observability | Prometheus → Amazon Managed Service for Prometheus + Grafana, logs in CloudWatch | Keeps dashboards and PromQL while removing operational work |
The expected outcome is a highly available platform across 3 Availability Zones, with auditable GitOps deployments, secrets kept outside the cluster and a predictable monthly cost that can be optimized.
1. Introduction: understanding the migration
1.1 What on-premises infrastructure is
On-premises infrastructure is infrastructure whose hardware the organization itself buys, installs and operates, in its own datacenter or in a colocation facility. The company is responsible for the whole stack: power, cooling, physical network, servers, storage, hypervisors, operating systems and, on top of all that, the platforms and applications.
That gives full control, but also full responsibility. If a disk fails at 3 a.m., the company’s team replaces it. If twice the capacity is needed for Black Friday, someone had to buy the servers months in advance.
1.2 Kubernetes in your own datacenter
Kubernetes is a container orchestrator: it receives a declarative description of the desired state (“I want 4 replicas of this container, exposed on this port, with this volume”) and works continuously to make the actual state match. Its main pieces are:
- Control plane:
kube-apiserver(the API),etcd(the state database),kube-scheduler(decides which node each pod runs on) andkube-controller-manager(the reconciliation loops). - Worker nodes: run
kubelet(the node agent), a container runtime such ascontainerd, andkube-proxy(network rules for Services). - Add-ons: a network plugin (CNI) such as Calico or Flannel, internal DNS (CoreDNS), an Ingress Controller, storage drivers (CSI) and monitoring.
In your own datacenter, the team installs Kubernetes with tools such as kubeadm, Kubespray or RKE2 and is in charge of everything: upgrading the control plane, rotating certificates, backing up etcd, operating the CNI, providing load balancing (there is no native type: LoadBalancer without something like MetalLB) and offering persistent storage with Ceph, NFS, Longhorn or a SAN.
1.3 What migrating containerized workloads to the cloud means
A workload is an application running on Kubernetes: a Deployment, a StatefulSet, a CronJob. Migrating it means it starts running on another cluster (here, on AWS) with its configuration, its identity, its network, its data and its deployment process.
The easy part is the container, which is portable by design. The hard part is everything around it:
- The data. A Ceph PersistentVolume does not “travel”. Its contents have to be copied with a consistent method.
- The network. IPs, DNS, firewalls and load balancers change completely.
- Identity. Static credentials must become IAM roles.
- External dependencies. LDAP, a mainframe or an internal API that stays on-premises.
- The process. Pipelines that deploy today with a
kubeconfigstored in a CI variable.
1.4 Self-managed Kubernetes vs. managed Kubernetes
| Aspect | Self-managed (on-premises kubeadm) | Managed (Amazon EKS) |
|---|---|---|
| Control plane | You install, scale, back up and upgrade it | AWS runs it across several AZs with an SLA |
| etcd | You handle backup, defragmentation and restore | Invisible to you; AWS manages it |
| Upgrades | Manual, node by node | One command or a Terraform change for the control plane; nodes with rolling updates |
| Load balancers | MetalLB, F5, HAProxy | ALB/NLB via the AWS Load Balancer Controller |
| Storage | Ceph, NFS, Longhorn: you operate the storage | Managed EBS, EFS, S3 |
| Identity | Certificates, tokens, LDAP | IAM + Access Entries + Pod Identity |
| Cost | CAPEX (hardware) + people | OPEX: cluster fee + consumed resources |
| Control | Full (kernel, apiserver flags) | Some control plane parameters are not configurable |
1.5 What Amazon EKS is
Amazon Elastic Kubernetes Service (EKS) is upstream, CNCF-certified Kubernetes, with the control plane managed by AWS. The APIs, kubectl, Helm and manifests are the same. What changes is who operates the control plane and how it integrates with the cloud:
- The control plane runs in AWS-owned accounts, replicated across several Availability Zones. You see an API endpoint.
- Nodes are EC2 instances in your VPC (Managed Node Groups, self-managed nodes or Karpenter), Fargate, or EKS Auto Mode, where AWS also manages nodes and critical add-ons.
- Pods get real VPC IP addresses thanks to the Amazon VPC CNI.
- Identity integrates with IAM: users access the cluster through Access Entries and pods get credentials with EKS Pod Identity or IRSA.
1.6 When migrating to EKS makes sense, and when it does not
Migrating makes sense when:
- The hardware is reaching end of life or the datacenter contract is expiring, and renewing means a large CAPEX.
- The team spends more time operating Kubernetes than delivering product.
- Real elasticity (seasonal peaks, new markets) or multi-region presence is needed.
- You want to consume managed services (RDS, ElastiCache, S3) instead of running them inside the cluster.
- There are compliance requirements AWS already covers (ISO 27001, SOC 2, PCI DSS) that are expensive to certify on-premises.
It is better not to migrate, or not yet, when:
- There are regulatory data residency requirements that no AWS Region meets. In that case you can evaluate EKS Anywhere, Outposts or EKS Hybrid Nodes.
- Applications depend on sub-millisecond latency to systems that stay on-premises (a mainframe, industrial machinery).
- The hardware is already paid off, has years of useful life left, and the load is stable and predictable: there may be no cost savings.
- The team has no AWS experience at all and there is no training budget: a migration without judgment creates a surprise bill.
1.7 Benefits, risks, limitations and costs
| Benefits | Risks | Limitations | Costs to watch |
|---|---|---|---|
| Managed, multi-AZ control plane | Downtime or data loss during cutover | Some apiserver flags are not configurable | Per-cluster fee (higher in extended support) |
| Node scaling in minutes | Unexpected bill (NAT, logs, data transfer) | Pod IPs consume VPC addresses | NAT Gateway: per hour and per GB processed |
| Managed services for data | Overly permissive IAM configurations | EBS volumes are bound to one AZ | Cross-AZ and Internet data transfer |
| Built-in security (KMS, GuardDuty, IAM) | Vendor lock-in | Service quotas (ENIs, IPs, LBs) | CloudWatch Logs (ingestion) |
| Reproducible infrastructure as code | Team learning curve | Kubernetes versions have a fixed support cycle | Orphaned volumes and snapshots |
1.8 Migrating containers, migrating a cluster or modernizing
These are three different scopes that are often confused:
- Migrating containers (rehosting workloads). The same images and manifests, with minimal adjustments (StorageClass, Ingress, registry), run on EKS. It is fast, but it inherits the technical debt.
- Migrating the cluster (replatforming the platform). Besides the workloads, platform components are replaced with cloud equivalents: ingress-nginx with ALB, Ceph with EBS/EFS, Secrets with Secrets Manager, the registry with ECR, self-managed Prometheus with Amazon Managed Service for Prometheus.
- Modernizing applications (refactoring). The application changes: the database moves to RDS, a monolith is split, messaging with SQS is adopted, or it is redesigned to scale horizontally.
In practice, a real project combines all three depending on the application. The decision matrix in chapter 5 exists precisely for that.
1.9 The scenario: ACME Technologies
ACME Technologies is a B2B software company with about 200 employees. Its electronic invoicing platform runs on an on-premises Kubernetes cluster installed four years ago with kubeadm on Dell servers in its own datacenter.
- The colocation contract expires in 9 months, and renewing means buying new hardware.
- Month-end peaks (accounting close) quadruple traffic and are currently covered with hardware that sits idle the rest of the month.
- The platform team (3 people) spends 40 % of its time on operational tasks: upgrading Kubernetes, repairing Ceph and renewing certificates.
- An enterprise customer requires multi-zone high availability and evidence of security controls.
Project goal: migrate to Amazon EKS in 12 weeks, with less than 15 minutes of downtime at cutover, zero data loss and a monthly cost comparable to the current TCO.
References
2. Source architecture: on-premises infrastructure
Traffic enters through a firewall and an L4 load balancer (F5/HAProxy) towards ingress-nginx. State lives in StatefulSets backed by Ceph/NFS, images live in Harbor, and deployments run from GitLab runners inside the datacenter.
2.1 Component inventory and their role
| Component | ACME implementation | Role |
|---|---|---|
| Distribution | kubeadm v1.29, 3 control plane nodes with stacked etcd | Cluster installation and lifecycle |
| Control plane | cp-01..03 behind an HAProxy VIP (:6443) | Highly available Kubernetes API |
| Worker nodes | 4 servers (32 vCPU, 128 GiB) | Run the application pods |
| Container runtime | containerd 1.7 | Pulls images and runs containers (CRI) |
| CNI | Calico (IP-in-IP overlay, pods in 192.168.0.0/16) | Pod networking and NetworkPolicies |
| Deployments | frontend (React served by NGINX), backend (Spring Boot) | Stateless applications with replicas |
| StatefulSets | postgresql (14), redis (7) | Applications with stable identity and storage |
| Services | ClusterIP for everything; NodePort for ingress | Internal discovery and load balancing |
| Ingress | ingress-nginx as a DaemonSet; F5 points to NodePort 30443 | HTTP(S) entry point, TLS, host-based routing |
| PV / PVC | 200 GiB PVC (PostgreSQL), 50 GiB (uploads, RWX) | Persistent storage for pods |
| StorageClass | ceph-rbd (RWO, default), nfs-client (RWX) | Dynamic volume provisioning |
| Registry | Harbor 2.x at harbor.acme.local | Stores private images |
| Database | PostgreSQL 14 in a StatefulSet, nightly pg_dump backups | Transactional invoicing data |
| Cache | Redis 7 in a StatefulSet, no critical persistence | Sessions and query cache |
| Configuration | ConfigMaps + Secrets (base64, not encrypted in etcd) | Parameters and credentials |
| Observability | kube-prometheus-stack (Prometheus, Alertmanager, Grafana) | Metrics, alerts and dashboards |
| CI/CD | GitLab CI with on-premises runners and kubectl apply | Build and deployment |
| DNS | Internal BIND (*.acme.local) | Corporate name resolution |
3. Target architecture: AWS
Only 2 of the 3 Availability Zones are drawn for readability. The ALB sends traffic straight to pod IPs (target-type ip). Nodes live only in private subnets, and Internet egress goes through NAT Gateways (one per AZ). ECR, Secrets Manager and S3 are reached through VPC endpoints.
3.1 Components and responsibilities on AWS
- Amazon VPC (
10.20.0.0/16) with 3 subnet types per AZ: public (ALB and NAT Gateways only), private application subnets (nodes and pods, with a large/20because every pod consumes an IP) and private data subnets (RDS and ElastiCache, with no route to the Internet). - Internet Gateway for traffic in and out of the public subnets, and a NAT Gateway per AZ so private nodes can reach the Internet without being reachable.
- Route Tables: public ones with
0.0.0.0/0 → IGW; private application ones with0.0.0.0/0 → NATin the same AZ; data ones with no default route. - Security Groups as a stateful per-resource firewall: the ALB accepts 443 from the Internet, nodes accept traffic from the ALB, and RDS only accepts 5432 from the node SG (or from specific pods).
- Amazon EKS with Managed Node Groups for system add-ons and Karpenter for applications.
- AWS IAM: Access Entries for people and pipelines, EKS Pod Identity for pods.
- Amazon ECR as a private registry with vulnerability scanning.
- Amazon EBS CSI Driver (RWO gp3 volumes) and Amazon EFS CSI Driver (RWX volumes).
- AWS Load Balancer Controller, which creates Application Load Balancers from Ingress resources and Network Load Balancers from
LoadBalancerServices. - Amazon Route 53 for public and private DNS, and ACM for TLS certificates.
- AWS Secrets Manager (credentials with rotation) and SSM Parameter Store (non-sensitive configuration), synced into the cluster with External Secrets Operator.
- Amazon RDS for PostgreSQL Multi-AZ and Amazon ElastiCache.
- Amazon CloudWatch (logs and Container Insights), Amazon Managed Service for Prometheus and Grafana.
- AWS Backup for RDS, EBS and EFS, and Velero for Kubernetes resources.
3.2 What is kept, what is replaced and what is modernized
| On-premises component | AWS target | Decision | Rationale |
|---|---|---|---|
| kubeadm control plane | EKS control plane | Replace | Removes etcd operations and manual upgrades |
| Physical workers | MNG + Karpenter (EC2) | Replace | Elasticity and right-sizing |
| containerd | containerd (AL2023 / Bottlerocket AMIs) | Keep | Same runtime; only who manages it changes |
| Calico (CNI) | Amazon VPC CNI (+ native NetworkPolicies) | Replace | Pods with VPC IPs and integration with SGs and ALB |
| frontend/backend Deployments | Deployments on EKS | Keep | Image, resource and probe adjustments |
| ingress-nginx | AWS Load Balancer Controller + ALB | Modernize | Retired project; managed ALB with ACM and WAF |
| F5 / HAProxy | ALB / NLB | Replace | Created by the controller from manifests |
| Ceph RBD | EBS gp3 via CSI | Replace | Managed block storage with snapshots |
| NFS | Amazon EFS via CSI | Replace | Managed multi-AZ RWX |
| Harbor | Amazon ECR | Replace | No operations, integrated with IAM and Inspector |
| PostgreSQL StatefulSet | Amazon RDS for PostgreSQL | Modernize (replatform) | Managed HA, PITR backups and patching |
| Redis StatefulSet | Amazon ElastiCache | Modernize | Automatic failover and no operations |
| Secrets (base64) | Secrets Manager + External Secrets | Modernize | KMS encryption, rotation and auditing |
| kube-prometheus-stack | Prometheus agent → AMP + Grafana | Modernize (partial) | Keeps PromQL and dashboards; removes storage |
GitLab CI + kubectl apply | CI (GitLab or GitHub Actions) + Argo CD | Modernize | GitOps: the pipeline no longer has cluster access |
| Internal BIND | Route 53 (private zones) + Resolver | Replace / integrate | Hybrid resolution during the transition |
3.3 The hybrid architecture during the migration
During the weeks the migration lasts, both worlds coexist. This intermediate stage is the most delicate one, because both environments must be able to talk privately and data must flow in a single, controlled direction.
Both environments coexist for weeks. Route 53 splits traffic with weighted records. Private connectivity (VPN or Direct Connect) carries data replication, and each data type uses its own mechanism: no single tool migrates everything.
Three principles govern this phase:
- Private connectivity first. No data replication should travel over the Internet. Set up a Site-to-Site VPN (quick to deploy, up to 1.25 Gbps per standard tunnel or 5 Gbps with large-bandwidth tunnels) or Direct Connect (dedicated link, stable latency), with non-overlapping IP ranges.
- A single writer per dataset. While on-premises is the system of record, AWS only reads or replicates. The writer switches exactly once, at cutover.
- Gradual, reversible traffic. Route 53 weighted records let you move 1 %, then 10 %, then 100 %, and go back with a weight change.
References
- Amazon EKS Best Practices Guide
- AWS Site-to-Site VPN · AWS Direct Connect
- AWS Well-Architected Framework
4. Assessment: evaluating the existing infrastructure
The assessment answers three questions: what is there, what depends on what and how hard it is to move. Without it, the migration plan rests on assumptions and problems show up at the worst possible moment: during cutover.
4.1 Discovering nodes and versions
# Server and node versions
kubectl version
kubectl get nodes -o wide
# Capacity and actual allocation per node (requests/limits vs. capacity)
kubectl describe nodes | grep -A 8 "Allocated resources"
# OS, kernel and runtime of each node as a table
kubectl get nodes -o custom-columns=\
NAME:.metadata.name,\
OS:.status.nodeInfo.osImage,\
KERNEL:.status.nodeInfo.kernelVersion,\
RUNTIME:.status.nodeInfo.containerRuntimeVersion,\
KUBELET:.status.nodeInfo.kubeletVersion
-o custom-columns lets you extract any field of the object with JSONPath expressions. It is easier to read than -o yaml when you go through dozens of nodes.
4.2 Namespace and workload inventory
# Namespaces with their labels (useful to identify teams/owners)
kubectl get namespaces --show-labels
# Every workload in the cluster
kubectl get deploy,sts,ds,cronjob,job -A -o wide
# "Forgotten" resources: Services, Ingress, PVCs, ConfigMaps, Secrets per namespace
for ns in $(kubectl get ns -o jsonpath='{.items[*].metadata.name}'); do
echo "== $ns"
kubectl get svc,ing,pvc,cm,secret -n "$ns" --no-headers 2>/dev/null | wc -l
done
A more complete script generates a CSV with what the assessment matrix needs:
#!/usr/bin/env bash
# scripts/inventory-workloads.sh — workload inventory to CSV
# Requires: kubectl with read access to the cluster, and jq.
set -euo pipefail
echo "namespace,kind,name,replicas,images,cpu_requests,mem_requests,pvcs,service_account"
for kind in deployment statefulset daemonset; do
kubectl get "$kind" -A -o json | jq -r --arg kind "$kind" '
.items[] |
[
.metadata.namespace,
$kind,
.metadata.name,
(.spec.replicas // "n/a"),
([.spec.template.spec.containers[].image] | join(" ")),
([.spec.template.spec.containers[].resources.requests.cpu // "none"] | join(" ")),
([.spec.template.spec.containers[].resources.requests.memory // "none"] | join(" ")),
([.spec.template.spec.volumes[]? | select(.persistentVolumeClaim) | .persistentVolumeClaim.claimName] | join(" ")),
(.spec.template.spec.serviceAccountName // "default")
] | @csv'
done
4.3 Actual CPU and memory usage
Declared requests are usually far from actual usage. To size nodes on AWS, use observed usage, not what is declared:
# Point-in-time usage (requires metrics-server)
kubectl top nodes
kubectl top pods -A --sort-by=memory | head -30
For capacity decisions, use 2- to 4-week percentiles from Prometheus:
# CPU p95 per workload (cores) over the last 14 days
quantile_over_time(0.95,
sum by (namespace, pod) (rate(container_cpu_usage_seconds_total{container!=""}[5m]))[14d:5m]
)
# Maximum working set memory per container over 14 days (bytes)
max_over_time(container_memory_working_set_bytes{container!=""}[14d])
4.4 Storage and Persistent Volumes
# StorageClasses, their provisioner and which one is the default
kubectl get storageclass
# Every PV with capacity, access mode, class and bound PVC
kubectl get pv -o custom-columns=\
NAME:.metadata.name,\
CAP:.spec.capacity.storage,\
MODES:.spec.accessModes,\
CLASS:.spec.storageClassName,\
CLAIM_NS:.spec.claimRef.namespace,\
CLAIM:.spec.claimRef.name,\
RECLAIM:.spec.persistentVolumeReclaimPolicy
# local, hostPath or hand-made NFS PVs (they need special handling)
kubectl get pv -o json | jq -r '.items[] |
select(.spec.local or .spec.hostPath or .spec.nfs) |
"\(.metadata.name)\t\(.spec.claimRef.namespace)/\(.spec.claimRef.name)"'
Also measure the actual usage inside each volume, not just the provisioned capacity. For example: kubectl exec -n acme-data postgresql-0 -- df -h /var/lib/postgresql/data.
4.5 Networking and dependencies
# Services by type (NodePort and LoadBalancer need a redesign)
kubectl get svc -A -o custom-columns=NS:.metadata.namespace,NAME:.metadata.name,TYPE:.spec.type,PORTS:.spec.ports[*].port
# Ingress, hosts and class
kubectl get ingress -A -o custom-columns=NS:.metadata.namespace,NAME:.metadata.name,CLASS:.spec.ingressClassName,HOSTS:.spec.rules[*].host
# NetworkPolicies (and Calico-specific policies, which are not portable)
kubectl get networkpolicy -A
kubectl get globalnetworkpolicies.crd.projectcalico.org 2>/dev/null || true
# Pods with hostNetwork, hostPort or privileged (risks and blockers on EKS)
kubectl get pods -A -o json | jq -r '.items[] |
select(.spec.hostNetwork == true
or any(.spec.containers[]; .securityContext.privileged == true)
or any(.spec.containers[].ports[]?; .hostPort != null)) |
"\(.metadata.namespace)/\(.metadata.name)"'
Dependencies between microservices are discovered with three complementary sources:
- Configuration. Look for hostnames and URLs in ConfigMaps and environment variables, for example with
kubectl get cm -A -o yaml | grep -Eo '[a-z0-9.-]+\.(svc|acme\.local)[:0-9]*' | sort -u. - Real traffic. Use Calico flow logs, service mesh metrics if there is one, or
conntrackandtcpdumpon the nodes during a representative window. - Interviews with the owning teams. No tool discovers the monthly cron job that calls a vendor’s FTP server.
External dependencies (LDAP, SMTP, a bank’s SFTP, APIs with IP allowlisting) are critical: if a vendor only accepts the datacenter’s public IP, after the migration traffic will leave through the NAT Gateway’s Elastic IP, and that allowlist must be updated weeks in advance.
4.6 Deprecated APIs, CRDs and operators
Going from Kubernetes 1.29 to 1.37 means crossing several versions. Manifests that use removed APIs will fail when applied at the target.
# Pluto: detects deprecated or removed apiVersions in manifests and Helm releases
pluto detect-all-in-cluster --target-versions k8s=v1.37.0
pluto detect-files -d ./manifests --target-versions k8s=v1.37.0
# kubent (kube-no-trouble): analyzes the live objects in the cluster
kubent --target-version 1.37.0
# Installed CRDs and their stored version
kubectl get crd -o custom-columns=NAME:.metadata.name,GROUP:.spec.group,VERSIONS:.spec.versions[*].name
# Operators (they usually live in *-operator or *-system namespaces)
kubectl get deploy -A | grep -Ei 'operator|controller'
Each CRD represents a component that must be reinstalled at the target before restoring its resources. For each one, decide whether it is kept (cert-manager, external-dns), replaced (Calico, MetalLB or Ceph operator CRDs make no sense on EKS) or removed.
4.7 On-premises-specific configuration
Look for everything that only exists in the datacenter:
nodeSelector,affinityortolerationstargeting physical node names or labels (kubernetes.io/hostname: worker-03).hostPathorlocalvolumes.- MetalLB, F5 (CIS) or ingress-nginx annotations (
nginx.ingress.kubernetes.io/*). imagePullSecretspointing toharbor.acme.local.- Certificates issued by the internal CA mounted as Secrets or ConfigMaps.
- Hardcoded fixed IPs in configuration.
# Example: find every reference to hostPath and to node names
kubectl get deploy,sts,ds -A -o yaml | grep -nE 'hostPath:|kubernetes.io/hostname' | head
4.8 Security and compliance
Document the requirements that shape the architecture: data classification (is there personal or financial data?), data residency (which Regions are allowed?), log retention (for example, 1 year for audits), encryption at rest and in transit, environment segregation, and who must approve production changes.
4.9 Application assessment matrix
Everything above is consolidated into a per-application matrix, the main deliverable of the assessment:
| App | Criticality | State | Data | Dependencies | Complexity (1-5) | Strategy | Wave |
|---|---|---|---|---|---|---|---|
| frontend | High | Stateless | — | backend | 1 | Rehost | 1 |
| backend | High | Stateless | — | PostgreSQL, Redis, SMTP, DIAN API | 2 | Replatform (Pod Identity, secrets) | 2 |
| postgresql | Critical | Stateful | 180 GiB | backend | 4 | Replatform → RDS | 2 |
| redis | Medium | Cache | 2 GiB (volatile) | backend | 1 | Replatform → ElastiCache | 2 |
| uploads (NFS) | Medium | Files | 40 GiB | backend | 2 | Rehost → EFS | 2 |
| prometheus/grafana | Medium | Stateful | 300 GiB TSDB | all | 2 | Replatform → AMP + Grafana | 1 |
| report-legacy (CronJob) | Low | Batch | — | vendor FTP | 3 | Retire (replaced by a new service) | — |
| ldap-sync | Medium | Batch | — | on-prem AD | 2 | Retain (stays on-prem for now) | — |
Store the script outputs together with the matrix in the repository (docs/assessment/). That way the assessment is versioned and can be compared against the target during validation.
References
- Kubernetes Deprecated API Migration Guide
- Pluto · kube-no-trouble · Popeye
- Amazon EKS Kubernetes versions
5. Migration strategies
AWS describes migration strategies as the “7 Rs”. For Kubernetes, six are relevant, plus a seventh (Relocate) that applies to VMware Cloud on AWS.
5.1 The strategies
- Rehost (“lift and shift”). The same workload with the minimum changes needed to run on EKS: StorageClass, registry and Ingress. Useful for stateless applications and tight deadlines.
- Replatform (“lift, tinker and shift”). The platform changes but the code does not: PostgreSQL moves from a StatefulSet to RDS, Redis to ElastiCache, Secrets to Secrets Manager. It is the strategy with the best effort/benefit ratio in most EKS migrations.
- Refactor / Re-architect. The application is modified to take advantage of the cloud: splitting a monolith, adopting events with SQS/EventBridge or making the service stateless. It has the largest long-term benefit and the highest cost and risk.
- Repurchase. The application is replaced with SaaS. For example, self-managed Jenkins with GitHub Actions, or Keycloak with Amazon Cognito or a SaaS IdP.
- Retire. It is shut down. Every honest assessment finds 10 to 20 % of workloads that nobody uses.
- Retain. It stays on-premises, for now or for good, because of dependencies, latency or regulation.
5.2 Comparison
| Strategy | Effort | Upfront cost | Risk | Cloud benefit | Speed |
|---|---|---|---|---|---|
| Rehost | Low | Low | Low-medium | Low | Very high |
| Replatform | Medium | Medium | Medium | High | High |
| Refactor | High | High | High | Very high | Low |
| Repurchase | Medium | Variable (licenses) | Medium | High | Medium |
| Retire | Very low | None | Low | Direct savings | Very high |
| Retain | None | None | Low (short term) | None | — |
5.3 Per-workload decision matrix
For each application, answer in order:
- Does anyone use it, and does it create value? If not: Retire.
- Does it have a hard constraint that keeps it in the datacenter (latency, regulation, hardware)? If so: Retain.
- Is there a SaaS that replaces it at a lower total cost? If so: Repurchase.
- Is it stateful, and is there an equivalent managed service (RDS, ElastiCache, MSK, OpenSearch)? If so: Replatform.
- Does it have structural problems the cloud does not solve (it does not scale, extreme coupling), and is there budget? If so: Refactor, ideally after migrating.
- In every other case: Rehost.
5.4 Phases and waves
The phases overlap: the Landing Zone is built while the assessment wraps up, and each wave of applications repeats Migrate → Cutover. Durations are indicative for a medium-sized cluster like ACME’s.
View editable Mermaid code
flowchart LR
A[1. Assess<br/>inventory and dependencies] --> B[2. Plan<br/>6R, waves, RTO/RPO]
B --> C[3. Landing Zone<br/>accounts, VPC, connectivity]
C --> D[4. Build EKS<br/>Terraform + add-ons]
D --> E[5. Migrate<br/>images, manifests, data]
E --> F[6. Cutover<br/>freeze, sync, DNS]
F --> G[7. Optimize<br/>validation and FinOps]
F -. rollback .-> E Applications are grouped into waves according to their dependencies and risk:
- Wave 0 (pilot). A low-risk but representative application (with an Ingress, a ConfigMap and a Secret) that validates the whole chain: CI → ECR → Argo CD → EKS → ALB → DNS.
- Wave 1. The shared platform and stateless applications without data: observability, frontend and internal tools.
- Wave 2. Applications with data, migrated together with their dependencies (backend + PostgreSQL + Redis + uploads), because separating a service from its database across a VPN tunnel adds latency to every query.
- Wave 3. Leftovers, CronJobs, workloads that depended on something from earlier waves, and the on-premises retirement.
For each wave, define the RTO (how long it can be down) and the RPO (how much data can be lost). Those two numbers determine the data migration technique (dump vs. replication) and the cutover window.
References
6. Landing Zone: preparing AWS
A Landing Zone is the secure, multi-account base AWS environment the workloads land on. Building it before the cluster avoids the most expensive migration mistake: creating everything in a single account with administrator permissions and planning to tidy it up later.
6.1 AWS Organizations and account structure
AWS Organizations groups accounts into Organizational Units (OUs) and applies Service Control Policies (SCPs), which are permission ceilings that not even an account administrator can exceed. For ACME:
Root (management account: billing and Organizations only)
├── OU Security
│ ├── log-archive ← organization CloudTrail, Config, VPC Flow Logs (immutable S3)
│ └── audit ← Security Hub, GuardDuty (delegated administrator)
├── OU Infrastructure
│ ├── network ← Transit Gateway, VPN / Direct Connect, Route 53 Resolver
│ └── shared-services ← central ECR, pipelines, Terraform state
├── OU Workloads
│ ├── acme-dev
│ ├── acme-staging
│ └── acme-prod ← production EKS, RDS, ElastiCache
└── OU Sandbox ← experimentation with a limited budget
AWS Control Tower automates this structure, with guardrails, Account Factory and IAM Identity Center. It is the recommended option if there is no Landing Zone yet.
| Setting | Required | Recommended | Depends on the scenario |
|---|---|---|---|
| Separate accounts per environment (isolated prod) | ✔ | ||
| Organization CloudTrail in the log-archive account | ✔ | ||
| IAM Identity Center (SSO) instead of IAM users | ✔ | ||
| MFA and a locked-down root user | ✔ | ||
| SCP: deny unapproved Regions | ✔ | ||
| GuardDuty + Security Hub with a delegated administrator | ✔ | ||
| Control Tower | ✔ | ||
| Transit Gateway | Needed with many VPCs or accounts | ||
| Direct Connect | Depends on data volume and latency requirements |
6.2 Network: VPC, subnets, routing and NAT
Production VPC design:
- CIDR
10.20.0.0/16(65,536 IPs), not overlapping with the datacenter (10.0.0.0/16). With the VPC CNI, every pod consumes a VPC IP: a cluster with 1,500 pods needs at least 1,500 IPs available in the private subnets, plus headroom for rolling updates. - 3 AZs, because that is the minimum for losing one zone not to leave the service without quorum or capacity.
- Public
/20subnets for ALB and NAT, private/20subnets for nodes and pods, and data/24subnets for RDS and ElastiCache. - One NAT Gateway per AZ: with a single one, losing that AZ cuts Internet egress for the other two, and cross-AZ traffic to the NAT also costs money.
# terraform/vpc/main.tf
terraform {
required_version = ">= 1.10"
required_providers {
aws = { source = "hashicorp/aws", version = "~> 6.0" }
}
backend "s3" {
bucket = "acme-terraform-state-prod"
key = "vpc/terraform.tfstate"
region = "us-east-1"
encrypt = true
use_lockfile = true # native S3 locking (Terraform >= 1.10), no DynamoDB
}
}
provider "aws" {
region = "us-east-1"
default_tags {
tags = { Project = "acme-migration", Environment = "prod", ManagedBy = "terraform" }
}
}
locals {
cluster_name = "acme-prod"
azs = ["us-east-1a", "us-east-1b", "us-east-1c"]
}
module "vpc" {
source = "terraform-aws-modules/vpc/aws"
version = "~> 6.0"
name = "acme-prod"
cidr = "10.20.0.0/16"
azs = local.azs
public_subnets = ["10.20.0.0/20", "10.20.16.0/20", "10.20.32.0/20"]
private_subnets = ["10.20.48.0/20", "10.20.64.0/20", "10.20.80.0/20"]
database_subnets = ["10.20.96.0/24", "10.20.97.0/24", "10.20.98.0/24"]
create_database_subnet_group = true
enable_nat_gateway = true
single_nat_gateway = false
one_nat_gateway_per_az = true
enable_dns_hostnames = true
enable_dns_support = true
# VPN to the datacenter: Virtual Private Gateway with route propagation
enable_vpn_gateway = true
propagate_private_route_tables_vgw = true
# Tags the AWS Load Balancer Controller and Karpenter use to discover subnets
public_subnet_tags = {
"kubernetes.io/role/elb" = 1
}
private_subnet_tags = {
"kubernetes.io/role/internal-elb" = 1
"karpenter.sh/discovery" = local.cluster_name
}
# Network auditing
enable_flow_log = true
create_flow_log_cloudwatch_log_group = true
create_flow_log_cloudwatch_iam_role = true
flow_log_cloudwatch_log_group_retention_in_days = 90
}
6.3 VPC endpoints
VPC endpoints let you reach AWS services without going through the NAT Gateway: traffic stays on the AWS network, it is more secure, and you do not pay NAT processing. For EKS, the most important ones are S3 (Gateway, free), ecr.api, ecr.dkr, sts, logs and secretsmanager (Interface, charged per hour and per AZ).
# terraform/vpc/endpoints.tf
module "vpc_endpoints" {
source = "terraform-aws-modules/vpc/aws//modules/vpc-endpoints"
version = "~> 6.0"
vpc_id = module.vpc.vpc_id
create_security_group = true
security_group_name_prefix = "acme-prod-vpce-"
security_group_rules = {
ingress_https = {
description = "HTTPS from the VPC"
cidr_blocks = [module.vpc.vpc_cidr_block]
}
}
endpoints = {
s3 = {
service = "s3"
service_type = "Gateway"
route_table_ids = module.vpc.private_route_table_ids
}
ecr_api = { service = "ecr.api", private_dns_enabled = true, subnet_ids = module.vpc.private_subnets }
ecr_dkr = { service = "ecr.dkr", private_dns_enabled = true, subnet_ids = module.vpc.private_subnets }
sts = { service = "sts", private_dns_enabled = true, subnet_ids = module.vpc.private_subnets }
logs = { service = "logs", private_dns_enabled = true, subnet_ids = module.vpc.private_subnets }
secretsmanager = { service = "secretsmanager", private_dns_enabled = true, subnet_ids = module.vpc.private_subnets }
}
}
6.4 Hybrid connectivity: Site-to-Site VPN and Direct Connect
| Criterion | Site-to-Site VPN | Direct Connect |
|---|---|---|
| Time to set up | Hours | Weeks or months (depends on the partner and the circuit) |
| Bandwidth | Up to 1.25 Gbps per standard tunnel or 5 Gbps per large-bandwidth tunnel (2 tunnels per connection) | 1, 10, 100 Gbps dedicated (or smaller hosted connections) |
| Latency | Variable (Internet) | Stable and low |
| Cost | Low (hourly + data transfer) | Port + data transfer (cheaper per GB) |
| Encryption | Native IPsec | Not encrypted by default (MACsec or VPN over DX) |
| Typical migration use | Pilots, moderate volumes, DX backup | Large data volumes or sustained hybrid traffic |
For ACME, with about 300 GiB of data, two VPN tunnels are enough: at an effective 500 Mbps, 300 GiB transfer in about 1.5 hours, and after that only changes are replicated (CDC).
# terraform/vpc/vpn.tf
resource "aws_customer_gateway" "acme_dc" {
bgp_asn = 65010
ip_address = "203.0.113.10" # public IP of the datacenter firewall
type = "ipsec.1"
tags = { Name = "acme-dc-cgw" }
}
resource "aws_vpn_connection" "acme_dc" {
vpn_gateway_id = module.vpc.vgw_id
customer_gateway_id = aws_customer_gateway.acme_dc.id
type = "ipsec.1"
static_routes_only = true
tags = { Name = "acme-dc-vpn" }
}
resource "aws_vpn_connection_route" "dc_lan" {
vpn_connection_id = aws_vpn_connection.acme_dc.id
destination_cidr_block = "10.0.0.0/16"
}
After applying this code, AWS generates the configuration for the on-premises device (Fortinet, Palo Alto, pfSense, Cisco…), which you download from the VPN console. To connect several VPCs and accounts, replace the VGW with a Transit Gateway in the network account, shared through AWS RAM.
6.5 Hybrid DNS
During the migration, pods on EKS must resolve *.acme.local (on-premises) and on-premises servers must resolve AWS private names. Route 53 VPC Resolver (formerly Route 53 Resolver) handles it with endpoints:
- Outbound endpoint + forwarding rule:
acme.localqueries from the VPC are forwarded to the on-premises BIND. - Inbound endpoint: BIND forwards
aws.acme.internal(a Route 53 private zone) to the VPC.
# terraform/vpc/dns.tf
resource "aws_security_group" "resolver" {
name_prefix = "acme-resolver-"
vpc_id = module.vpc.vpc_id
egress {
from_port = 53
to_port = 53
protocol = "udp"
cidr_blocks = ["10.0.0.0/16"]
}
egress {
from_port = 53
to_port = 53
protocol = "tcp"
cidr_blocks = ["10.0.0.0/16"]
}
}
resource "aws_route53_resolver_endpoint" "outbound" {
name = "acme-outbound"
direction = "OUTBOUND"
security_group_ids = [aws_security_group.resolver.id]
ip_address { subnet_id = module.vpc.private_subnets[0] }
ip_address { subnet_id = module.vpc.private_subnets[1] }
}
resource "aws_route53_resolver_rule" "acme_local" {
domain_name = "acme.local"
name = "forward-acme-local"
rule_type = "FORWARD"
resolver_endpoint_id = aws_route53_resolver_endpoint.outbound.id
target_ip { ip = "10.0.0.53" }
target_ip { ip = "10.0.0.54" }
}
resource "aws_route53_resolver_rule_association" "acme_local" {
resolver_rule_id = aws_route53_resolver_rule.acme_local.id
vpc_id = module.vpc.vpc_id
}
6.6 Certificates, secrets, logging and auditing
- Public TLS: AWS Certificate Manager (ACM) issues free certificates for the ALB, validated through DNS in Route 53 and renewed automatically. ACM certificates cannot be exported to pods; for TLS inside the cluster, use cert-manager.
- Secrets: AWS Secrets Manager for credentials (with native rotation for RDS) and SSM Parameter Store for configuration. Keys are managed by AWS KMS with per-domain CMKs (
alias/acme-prod-data,alias/acme-prod-eks). - Logging and auditing: an organization CloudTrail (immutable in log-archive, with Object Lock), AWS Config with conformance rules, VPC Flow Logs and the EKS control plane logs (
api,audit,authenticator) sent to CloudWatch Logs.
References
- AWS Control Tower · AWS Organizations
- terraform-aws-modules/vpc
- AWS PrivateLink and VPC endpoints
- Route 53 VPC Resolver
7. Building the new Amazon EKS cluster
7.1 Prerequisites and tools
| Tool | Use | Check |
|---|---|---|
| AWS CLI v2 | Authentication and AWS operations | aws --version |
| kubectl | Kubernetes client (±1 minor version of the cluster) | kubectl version --client |
| eksctl | Quick cluster creation (labs) and utilities | eksctl version |
| Terraform ≥ 1.10 | Infrastructure as code | terraform version |
| Helm 3 | Installing controllers and apps | helm version |
# macOS (Homebrew)
brew install awscli kubernetes-cli eksctl helm
brew tap hashicorp/tap && brew install hashicorp/tap/terraform
# Recommended authentication: IAM Identity Center (SSO), no long-lived access keys
aws configure sso --profile acme-prod
aws sso login --profile acme-prod
export AWS_PROFILE=acme-prod
aws sts get-caller-identity # confirm the account and role before creating anything
# Kubernetes versions available on EKS and their support status
aws eks describe-cluster-versions --region us-east-1 \
--query 'clusterVersions[].{version:clusterVersion,status:versionStatus,endOfStandard:endOfStandardSupportDate}' \
--output table
7.2 Option A (lab): eksctl
eksctl creates a complete cluster from a single file. It is ideal for learning and labs, but it does not manage the rest of the infrastructure (RDS, VPN, IAM) the way Terraform does.
# lab/eksctl-cluster.yaml — Teaching example
apiVersion: eksctl.io/v1alpha5
kind: ClusterConfig
metadata:
name: acme-lab
region: us-east-1
version: "1.37"
addons:
- name: vpc-cni
- name: coredns
- name: kube-proxy
- name: eks-pod-identity-agent
managedNodeGroups:
- name: system
instanceType: m7i.large
amiFamily: AmazonLinux2023
minSize: 2
maxSize: 4
desiredCapacity: 2
privateNetworking: true
eksctl create cluster -f lab/eksctl-cluster.yaml # about 15-20 minutes
7.3 Option B (production): Terraform
# terraform/eks/main.tf — Recommended production configuration
module "eks" {
source = "terraform-aws-modules/eks/aws"
version = "~> 21.0"
name = "acme-prod"
kubernetes_version = "1.37"
# Private API; administrative access comes through the VPN or an SSM bastion
endpoint_public_access = false
endpoint_private_access = true
vpc_id = data.terraform_remote_state.vpc.outputs.vpc_id
subnet_ids = data.terraform_remote_state.vpc.outputs.private_subnets
# Control plane logs to CloudWatch
enabled_log_types = ["api", "audit", "authenticator"]
# Access: API mode (Access Entries). The creator is admin only for bootstrapping.
authentication_mode = "API"
enable_cluster_creator_admin_permissions = true
access_entries = {
platform_admins = {
principal_arn = "arn:aws:iam::111122223333:role/AWSReservedSSO_PlatformAdmins_abc123"
policy_associations = {
admin = {
policy_arn = "arn:aws:eks::aws:cluster-access-policy/AmazonEKSClusterAdminPolicy"
access_scope = { type = "cluster" }
}
}
}
developers_readonly = {
principal_arn = "arn:aws:iam::111122223333:role/AWSReservedSSO_Developers_def456"
policy_associations = {
view = {
policy_arn = "arn:aws:eks::aws:cluster-access-policy/AmazonEKSViewPolicy"
access_scope = { type = "namespace", namespaces = ["acme-frontend", "acme-backend"] }
}
}
}
}
# EKS managed add-ons
addons = {
vpc-cni = {
before_compute = true
configuration_values = jsonencode({
enableNetworkPolicy = "true"
env = { ENABLE_PREFIX_DELEGATION = "true" }
})
}
eks-pod-identity-agent = { before_compute = true }
kube-proxy = {}
coredns = {}
aws-ebs-csi-driver = {}
aws-efs-csi-driver = {}
}
# Node group for system components (Karpenter, CoreDNS, controllers)
eks_managed_node_groups = {
system = {
ami_type = "AL2023_x86_64_STANDARD"
instance_types = ["m7i.large"]
min_size = 3
max_size = 5
desired_size = 3
labels = { "acme.io/pool" = "system" }
}
}
# Karpenter discovers the node security group through this tag
node_security_group_tags = { "karpenter.sh/discovery" = "acme-prod" }
}
# IAM identities for add-ons and controllers (EKS Pod Identity)
module "ebs_csi_pod_identity" {
source = "terraform-aws-modules/eks-pod-identity/aws"
version = "~> 2.0"
name = "acme-prod-ebs-csi"
attach_aws_ebs_csi_policy = true
associations = {
this = {
cluster_name = module.eks.cluster_name
namespace = "kube-system"
service_account = "ebs-csi-controller-sa"
}
}
}
module "efs_csi_pod_identity" {
source = "terraform-aws-modules/eks-pod-identity/aws"
version = "~> 2.0"
name = "acme-prod-efs-csi"
attach_aws_efs_csi_policy = true
associations = {
this = {
cluster_name = module.eks.cluster_name
namespace = "kube-system"
service_account = "efs-csi-controller-sa"
}
}
}
module "lbc_pod_identity" {
source = "terraform-aws-modules/eks-pod-identity/aws"
version = "~> 2.0"
name = "acme-prod-aws-lbc"
attach_aws_lb_controller_policy = true
# LBC 3.7 added a permission that the policy bundled in the module does not include yet
# (verified in Nov. 2026). Always compare with the controller's docs/install/iam_policy.json.
attach_custom_policy = true
policy_statements = [{
sid = "LBCv37SecurityGroupQuota"
actions = ["ec2:ValidateSecurityGroupQuotasForInterface"]
resources = ["*"]
}]
associations = {
this = {
cluster_name = module.eks.cluster_name
namespace = "kube-system"
service_account = "aws-load-balancer-controller"
}
}
}
cd terraform/eks
terraform init
terraform plan -out tfplan # review the plan: how many resources are created? is anything destroyed?
terraform apply tfplan
aws eks update-kubeconfig --name acme-prod --region us-east-1 --alias acme-prod
kubectl get nodes -L acme.io/pool,topology.kubernetes.io/zone
Decisions explained:
authentication_mode = "API": IAM identities are registered as Access Entries managed through the EKS API, instead of theaws-authConfigMap, which was fragile because a syntax error could lock everyone out of the cluster.- AL2023: EKS AMIs based on Amazon Linux 2 are no longer published for current Kubernetes versions. Use AL2023 or Bottlerocket.
- Private endpoint: reduces the attack surface. For a lab, you can use
endpoint_public_access = truerestricted withendpoint_public_access_cidrs = ["YOUR_IP/32"].
7.4 Pod identity: EKS Pod Identity vs. IRSA
A pod that needs to read from S3 or Secrets Manager must not receive access keys. There are two mechanisms to give it temporary credentials:
| EKS Pod Identity | IRSA (IAM Roles for Service Accounts) | |
|---|---|---|
| Configuration | cluster + namespace + serviceaccount → role association through the EKS API | OIDC provider per cluster + ServiceAccount annotation + trust policy per cluster |
| Role trust policy | Generic (pods.eks.amazonaws.com), reusable across clusters | Bound to each cluster’s OIDC issuer |
| Cluster requirement | eks-pod-identity-agent add-on | None (webhook built into EKS) |
| Portability | EKS only | EKS and others (any cluster with OIDC) |
| Recommendation | Default on EKS | When you need compatibility with non-EKS clusters or very old SDKs |
Trust policy of a role for Pod Identity:
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": { "Service": "pods.eks.amazonaws.com" },
"Action": ["sts:AssumeRole", "sts:TagSession"]
}
]
}
# Associate the backend role with its ServiceAccount
aws eks create-pod-identity-association \
--cluster-name acme-prod \
--namespace acme-backend \
--service-account backend \
--role-arn arn:aws:iam::111122223333:role/acme-prod-backend
aws eks list-pod-identity-associations --cluster-name acme-prod --output table
7.5 Essential add-ons
- Amazon VPC CNI: assigns each pod an IP from the subnet. With
ENABLE_PREFIX_DELEGATIONit assigns/28blocks per ENI, which multiplies pod density per node. WithenableNetworkPolicyit enforces standard Kubernetes NetworkPolicies with eBPF. - CoreDNS: cluster DNS (
*.svc.cluster.local). Scale it according to the number of nodes and consider NodeLocal DNSCache in large clusters. - kube-proxy: programs Service rules on each node (iptables or IPVS).
- EBS CSI Driver: RWO block volumes.
- EFS CSI Driver: RWX file volumes.
# Compatible versions of an add-on for the cluster version
aws eks describe-addon-versions --addon-name vpc-cni --kubernetes-version 1.37 \
--query 'addons[].addonVersions[0:3].addonVersion'
# Status of the installed add-ons
aws eks list-addons --cluster-name acme-prod
kubectl get pods -n kube-system
Target StorageClasses:
# platform/storage/storageclasses.yaml
apiVersion: storage.k8s.io/v1
kind: StorageClass
metadata:
name: gp3
annotations:
storageclass.kubernetes.io/is-default-class: "true"
provisioner: ebs.csi.aws.com
parameters:
type: gp3
encrypted: "true"
# kmsKeyId: arn:aws:kms:us-east-1:111122223333:key/... # your own CMK (recommended in prod)
volumeBindingMode: WaitForFirstConsumer # creates the volume in the AZ where the pod is scheduled
allowVolumeExpansion: true
reclaimPolicy: Delete
---
apiVersion: storage.k8s.io/v1
kind: StorageClass
metadata:
name: efs-sc
provisioner: efs.csi.aws.com
parameters:
provisioningMode: efs-ap # one Access Point per PVC
fileSystemId: fs-0123456789abcdef0
directoryPerms: "700"
7.6 AWS Load Balancer Controller
helm repo add eks https://aws.github.io/eks-charts
helm repo update eks
VPC_ID=$(aws eks describe-cluster --name acme-prod \
--query 'cluster.resourcesVpcConfig.vpcId' --output text)
helm upgrade --install aws-load-balancer-controller eks/aws-load-balancer-controller \
--namespace kube-system \
--set clusterName=acme-prod \
--set region=us-east-1 \
--set vpcId="$VPC_ID" \
--set serviceAccount.create=true \
--set serviceAccount.name=aws-load-balancer-controller \
--set replicaCount=2
kubectl -n kube-system rollout status deploy/aws-load-balancer-controller
The ServiceAccount name matches the Pod Identity association created in Terraform (lbc_pod_identity). Without that association, the controller starts but fails when calling the ELB API with AccessDenied errors.
helm upgrade does not update the controller’s CRDs. On every upgrade, first apply the published CRDs (kubectl apply -k "github.com/aws/eks-charts/stable/aws-load-balancer-controller/crds?ref=master") and check the release notes for IAM policy changes.
7.7 Node scaling: Cluster Autoscaler vs. Karpenter
| Cluster Autoscaler | Karpenter | |
|---|---|---|
| Model | Resizes existing Auto Scaling Groups | Creates EC2 instances directly based on pending pods |
| Instance types | Fixed per node group | Picks from dozens of types (including Spot) on every decision |
| Speed | Minutes (depends on the ASG) | Usually faster (launches the instance directly) |
| Consolidation | Limited (scale-down of empty or underutilized nodes) | Replaces nodes with cheaper ones or removes them |
| Complexity | Low | Medium (NodePools, EC2NodeClass, Spot interruptions) |
For ACME, Karpenter is chosen for applications and a small Managed Node Group for the system. The Terraform submodule creates the SQS interruption queue, the node IAM role and the Pod Identity association:
# terraform/eks/karpenter.tf
module "karpenter" {
source = "terraform-aws-modules/eks/aws//modules/karpenter"
version = "~> 21.0"
cluster_name = module.eks.cluster_name
# Fixed node role name: the EC2NodeClass references it
node_iam_role_name = "KarpenterNode-acme-prod"
node_iam_role_use_name_prefix = false
# Lets you manage nodes through SSM Session Manager, without SSH
node_iam_role_additional_policies = {
AmazonSSMManagedInstanceCore = "arn:aws:iam::aws:policy/AmazonSSMManagedInstanceCore"
}
}
output "karpenter_queue_name" { value = module.karpenter.queue_name }
output "karpenter_node_role" { value = module.karpenter.node_iam_role_name }
export KARPENTER_VERSION="1.15.3" # latest stable as of Nov. 2026; check the releases at karpenter.sh
helm upgrade --install karpenter oci://public.ecr.aws/karpenter/karpenter \
--version "${KARPENTER_VERSION}" \
--namespace kube-system \
--set settings.clusterName=acme-prod \
--set settings.interruptionQueue="$(terraform -chdir=terraform/eks output -raw karpenter_queue_name)" \
--set controller.resources.requests.cpu=1 \
--set controller.resources.requests.memory=1Gi \
--wait
# platform/karpenter/nodepool-apps.yaml
apiVersion: karpenter.k8s.aws/v1
kind: EC2NodeClass
metadata:
name: default
spec:
role: "KarpenterNode-acme-prod" # node_iam_role_name from the Terraform module
amiSelectorTerms:
- alias: al2023@latest # in production, pin a version: al2023@vYYYYMMDD
subnetSelectorTerms:
- tags:
karpenter.sh/discovery: acme-prod
securityGroupSelectorTerms:
- tags:
karpenter.sh/discovery: acme-prod
---
apiVersion: karpenter.sh/v1
kind: NodePool
metadata:
name: apps
spec:
template:
metadata:
labels:
acme.io/pool: apps
spec:
nodeClassRef:
group: karpenter.k8s.aws
kind: EC2NodeClass
name: default
expireAfter: 720h # recycles nodes every 30 days (AMI patches)
requirements:
- key: karpenter.sh/capacity-type
operator: In
values: ["on-demand", "spot"]
- key: kubernetes.io/arch
operator: In
values: ["amd64"]
- key: karpenter.k8s.aws/instance-category
operator: In
values: ["c", "m", "r"]
- key: karpenter.k8s.aws/instance-generation
operator: Gt
values: ["5"]
limits:
cpu: "200"
memory: 800Gi
disruption:
consolidationPolicy: WhenEmptyOrUnderutilized
consolidateAfter: 1m
7.8 Metrics Server
Metrics Server feeds kubectl top and the Horizontal Pod Autoscaler. It is also available as a community add-on on EKS; with Helm:
helm repo add metrics-server https://kubernetes-sigs.github.io/metrics-server/
helm upgrade --install metrics-server metrics-server/metrics-server -n kube-system
kubectl top nodes
References
- terraform-aws-modules/eks · eks-pod-identity
- EKS Pod Identity · IRSA · Access Entries
- Amazon EBS CSI · Amazon EFS CSI
- AWS Load Balancer Controller · Karpenter · Cluster Autoscaler
- eksctl · Install kubectl · Install the AWS CLI
8. Migrating container images
Copying by digest (crane, or skopeo with --all) preserves multi-architecture manifest lists and lets you verify integrity: the source and target digests must match. Harbor’s native replication to ECR is a push-based alternative for continuous syncs.
8.1 Source and target registries
- Docker Registry (distribution). A minimal registry with no UI or RBAC. You list it through the
/v2/_catalogAPI. - Harbor. A CNCF enterprise registry with projects, RBAC, scanning, signatures and replication rules, which support Amazon ECR as a target.
- Amazon ECR. A managed registry integrated with IAM, encrypted with KMS, with basic or enhanced scanning (Amazon Inspector), lifecycle policies, cross-Region and cross-account replication, and pull through cache for public registries.
8.2 Inventory of images in use
Migrate the images that are actually used, not Harbor’s 4,000 historical tags:
# Images from containers and initContainers of every pod, deduplicated
kubectl get pods -A -o jsonpath='{range .items[*]}{range .spec.initContainers[*]}{.image}{"\n"}{end}{range .spec.containers[*]}{.image}{"\n"}{end}{end}' \
| sort -u | tee images-in-use.txt
# Harbor images only, without the registry prefix → project/repository:tag
grep '^harbor.acme.local/' images-in-use.txt | sed 's#^harbor.acme.local/##' > images.txt
Also add the tags of the last N versions of each application, which you need for rollbacks, and the images referenced in Helm charts and CronJobs that were not running at inventory time.
8.3 Authentication and repository creation
AWS_REGION=us-east-1
AWS_ACCOUNT_ID=$(aws sts get-caller-identity --query Account --output text)
ECR="${AWS_ACCOUNT_ID}.dkr.ecr.${AWS_REGION}.amazonaws.com"
# Docker login to ECR (the token lasts 12 hours)
aws ecr get-login-password --region "$AWS_REGION" \
| docker login --username AWS --password-stdin "$ECR"
# Repository with immutable tags, scanning and KMS encryption
aws ecr create-repository \
--repository-name acme/backend \
--image-tag-mutability IMMUTABLE \
--image-scanning-configuration scanOnPush=true \
--encryption-configuration encryptionType=KMS \
--region "$AWS_REGION"
--image-tag-mutability IMMUTABLEprevents overwriting an existing tag:1.8.2will always point to the same digest. This is essential for reliable rollbacks.encryptionType=KMSencrypts with an AWS managed KMS key, or with a CMK if you addkmsKey=....
In production, repositories are created with Terraform (aws_ecr_repository, together with aws_ecr_lifecycle_policy), not by hand.
8.4 Teaching method: docker pull, tag and push
docker pull harbor.acme.local/acme/backend:1.8.2
docker tag harbor.acme.local/acme/backend:1.8.2 "$ECR/acme/backend:1.8.2"
docker push "$ECR/acme/backend:1.8.2"
8.5 Recommended method: crane or skopeo
crane (from go-containerregistry) and skopeo copy manifests and layers directly between registries, preserve manifest lists and keep the same digest.
# crane: copies every platform by default
crane copy harbor.acme.local/acme/backend:1.8.2 "$ECR/acme/backend:1.8.2"
# skopeo: --all copies the full manifest list (without --all, only the current platform)
skopeo copy --all \
docker://harbor.acme.local/acme/backend:1.8.2 \
docker://"$ECR"/acme/backend:1.8.2
A complete, idempotent script with integrity verification:
#!/usr/bin/env bash
# migration/registry/migrate-images.sh
# Usage: HARBOR_USER=... HARBOR_PASSWORD=... ./migrate-images.sh images.txt
# images.txt: one reference per line, format project/repository:tag
set -euo pipefail
SRC_REGISTRY="harbor.acme.local"
AWS_REGION="${AWS_REGION:-us-east-1}"
AWS_ACCOUNT_ID="$(aws sts get-caller-identity --query Account --output text)"
DST_REGISTRY="${AWS_ACCOUNT_ID}.dkr.ecr.${AWS_REGION}.amazonaws.com"
IMAGES_FILE="${1:-images.txt}"
crane auth login "$SRC_REGISTRY" -u "$HARBOR_USER" -p "$HARBOR_PASSWORD"
aws ecr get-login-password --region "$AWS_REGION" \
| crane auth login "$DST_REGISTRY" -u AWS --password-stdin
ensure_repo() {
local repo="$1"
if ! aws ecr describe-repositories --repository-names "$repo" --region "$AWS_REGION" >/dev/null 2>&1; then
aws ecr create-repository --repository-name "$repo" --region "$AWS_REGION" \
--image-tag-mutability IMMUTABLE \
--image-scanning-configuration scanOnPush=true \
--encryption-configuration encryptionType=KMS >/dev/null
echo "Repository created: $repo"
fi
}
while IFS= read -r ref; do
[[ -z "$ref" || "$ref" == \#* ]] && continue
repo="${ref%:*}"
tag="${ref##*:}"
src="${SRC_REGISTRY}/${ref}"
dst="${DST_REGISTRY}/${repo}:${tag}"
ensure_repo "$repo"
if crane digest "$dst" >/dev/null 2>&1; then
echo "SKIP $dst (already exists)"
continue
fi
crane copy "$src" "$dst"
src_digest="$(crane digest "$src")"
dst_digest="$(crane digest "$dst")"
if [[ "$src_digest" == "$dst_digest" ]]; then
echo "OK $ref $dst_digest"
else
echo "ERROR digest mismatch for $ref: $src_digest != $dst_digest" >&2
exit 1
fi
done < "$IMAGES_FILE"
8.6 Alternative: replication from Harbor
Harbor can push images to ECR with a replication rule: you register an “AWS ECR” endpoint with credentials for a role or user with push permissions, and define a project or tag filter with a manual, scheduled or event-based trigger. It is useful when teams keep publishing to Harbor during the migration and ECR must stay in sync until cutover.
8.7 Scanning, tags, versioning and integrity
# Continuous scanning with Amazon Inspector (enhanced scanning) for the whole registry
aws inspector2 enable --resource-types ECR
aws ecr put-registry-scanning-configuration --scan-type ENHANCED \
--rules '[{"scanFrequency":"CONTINUOUS_SCAN","repositoryFilters":[{"filter":"*","filterType":"WILDCARD"}]}]'
# Findings for an image
aws ecr describe-image-scan-findings --repository-name acme/backend --image-id imageTag=1.8.2
Lifecycle policy to avoid piling up unused images:
{
"rules": [
{
"rulePriority": 1,
"description": "Expire untagged images after 7 days",
"selection": { "tagStatus": "untagged", "countType": "sinceImagePushed", "countUnit": "days", "countNumber": 7 },
"action": { "type": "expire" }
},
{
"rulePriority": 2,
"description": "Keep the last 50 release versions",
"selection": { "tagStatus": "tagged", "tagPrefixList": ["v", "1.", "2."], "countType": "imageCountMoreThan", "countNumber": 50 },
"action": { "type": "expire" }
}
]
}
Tagging and versioning best practices:
- Semantic tags (
1.8.2) for releases and the commit SHA (git-3f9c2a1) for CI builds. Never deploylatestto production. - In production manifests, reference the image by digest (
acme/backend@sha256:...) or use immutable tags. That way what was tested is exactly what gets deployed. - If images are signed with cosign or Notation, the signatures are separate artifacts in the registry and must be copied too (
cosign copy, or crane with the signature tags), and verification must be reconfigured on the target cluster. - For public images (Docker Hub, Quay, registry.k8s.io), configure ECR pull through cache: you avoid download rate limits and cache what you use in your own account.
References
9. Migrating Kubernetes resources
9.1 What to do with each resource type
| Resource | Migration treatment | Key difference on EKS |
|---|---|---|
| Namespaces | Recreated with Pod Security Admission labels | pod-security.kubernetes.io/enforce labels |
| Deployments | Migrated with image, resource and affinity changes | Image in ECR, no imagePullSecrets, zone topologySpreadConstraints |
| StatefulSets | Migrated only if they stay in the cluster; databases move to RDS | storageClassName: gp3; EBS is zonal |
| DaemonSets | Review one by one: infrastructure ones (Calico, node-exporter, fluentd) are not migrated | Replaced by EKS add-ons or managed observability |
| Services | ClusterIP unchanged; NodePort and LoadBalancer are redesigned | type: LoadBalancer creates an NLB via the AWS LBC |
| Ingress | Rewritten from nginx to alb | alb.ingress.kubernetes.io/* annotations |
| ConfigMaps | Migrated; review on-premises hostnames and IPs | RDS and ElastiCache endpoints |
| Secrets | Not copied in plain text: created in Secrets Manager | External Secrets Operator syncs them |
| ServiceAccounts | Migrated; Pod Identity associations are added | No annotations (Pod Identity) or eks.amazonaws.com/role-arn (IRSA) |
| RBAC | Roles and Bindings are migrated; groups move to Access Entries | IAM users are mapped to Kubernetes groups with Access Entries |
| NetworkPolicies | Standard ones are migrated; Calico ones (projectcalico.org) are converted | The VPC CNI enforces standard NetworkPolicies |
| Jobs | Completed ones are not migrated | — |
| CronJobs | Migrated suspended and enabled at cutover | Avoids duplicate runs at source and target |
| CRDs | Installed with the operator’s chart before their resources | Versions compatible with Kubernetes 1.37 |
| Custom controllers | Reinstalled with their chart; review IAM permissions | Pod Identity for those that call AWS |
| Helm releases | Reinstalled from the chart and versioned values | Per-environment values (values-eks.yaml) |
9.2 Three approaches to migrating manifests
1. YAML manifests exported from the cluster. Export what is there (kubectl get -o yaml), clean it up and apply it at the target.
# Export and strip cluster-generated fields (requires yq v4)
kubectl get deploy,sts,svc,cm,sa,role,rolebinding,ing,networkpolicy,cronjob \
-n acme-backend -o yaml \
| yq 'del(
.items[].metadata.managedFields,
.items[].metadata.uid,
.items[].metadata.resourceVersion,
.items[].metadata.creationTimestamp,
.items[].metadata.generation,
.items[].metadata.annotations."kubectl.kubernetes.io/last-applied-configuration",
.items[].metadata.annotations."deployment.kubernetes.io/revision",
.items[].status,
(.items[] | select(.kind == "Service") | .spec.clusterIP),
(.items[] | select(.kind == "Service") | .spec.clusterIPs)
)' > export/acme-backend.yaml
- Pros: fast, and it does not require the manifests’ source code.
- Cons: it drags everything along, including manual drift (changes made with
kubectl editthat nobody documented), and the result is not maintainable. - When to use it: when there is no manifest repository, as a starting point to create one.
2. Helm and Kustomize from Git. Manifests live in Git and each environment is a variant (overlay) or a values file.
- Pros: reproducible, reviewable in pull requests and a direct foundation for GitOps.
- Cons: it requires the repository to reflect reality. If there was drift, it must be reconciled first.
- When to use it: always as the end state. This is the approach chosen for ACME.
3. Velero. It backs up cluster objects (and optionally volumes) to S3 and restores them into another cluster.
- Pros: a faithful copy of the state, including resources nobody has in Git, and it migrates volume data with File System Backup.
- Cons: unless filtered, it also restores what should not exist on EKS (nginx annotations, Ceph StorageClasses), and it does not transform manifests except through plugins and mappings.
- When to use it: for workloads without manifests in Git, to migrate non-transactional volume data, and as a safety net (full backup before cutover).
| Criterion | Exported YAML | Helm/Kustomize + Git | Velero |
|---|---|---|---|
| Fidelity to the current state | High | Depends on drift | Very high |
| Maintainability afterwards | Low | Very high | Low (it is a backup) |
| On-prem → EKS transformations | Manual (yq) | Overlays and values | Mapping ConfigMaps, plugins |
| Migrates PV data | No | No | Yes (FSB / snapshots) |
| Fits GitOps | No | Yes | No |
9.3 Before and after: Deployment
# BEFORE — on-premises
apiVersion: apps/v1
kind: Deployment
metadata:
name: backend
namespace: acme-backend
spec:
replicas: 4
selector:
matchLabels: { app: backend }
template:
metadata:
labels: { app: backend }
spec:
imagePullSecrets:
- name: harbor-pull
nodeSelector:
kubernetes.io/hostname: worker-02 # pinned to a physical server
containers:
- name: backend
image: harbor.acme.local/acme/backend:1.8.2
envFrom:
- secretRef: { name: backend-db } # password in a base64 Secret
env:
- name: SPRING_DATASOURCE_URL
value: jdbc:postgresql://postgresql.acme-data.svc:5432/acme
- name: SPRING_DATA_REDIS_HOST
value: redis.acme-data.svc
# AFTER — Amazon EKS
apiVersion: apps/v1
kind: Deployment
metadata:
name: backend
namespace: acme-backend
spec:
replicas: 3 # the HPA handles the rest
selector:
matchLabels: { app: backend }
template:
metadata:
labels: { app: backend }
spec:
serviceAccountName: backend # Pod Identity → backend IAM role
topologySpreadConstraints: # spread replicas across AZs
- maxSkew: 1
topologyKey: topology.kubernetes.io/zone
whenUnsatisfiable: DoNotSchedule
labelSelector:
matchLabels: { app: backend }
nodeSelector:
acme.io/pool: apps # Karpenter NodePool
containers:
- name: backend
image: 111122223333.dkr.ecr.us-east-1.amazonaws.com/acme/backend:1.8.2
resources:
requests: { cpu: 500m, memory: 1Gi }
limits: { memory: 1Gi }
envFrom:
- secretRef: { name: backend-db } # created by External Secrets from Secrets Manager
env:
- name: SPRING_DATASOURCE_URL
value: jdbc:postgresql://acme-prod.cluster-abc123.us-east-1.rds.amazonaws.com:5432/acme?sslmode=require
- name: SPRING_DATA_REDIS_HOST
value: master.acme-prod-cache.abc123.use1.cache.amazonaws.com
- name: SPRING_DATA_REDIS_SSL_ENABLED
value: "true"
readinessProbe:
httpGet: { path: /actuator/health/readiness, port: 8080 }
livenessProbe:
httpGet: { path: /actuator/health/liveness, port: 8080 }
9.4 Before and after: Ingress
# BEFORE — ingress-nginx
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name: web
namespace: acme-frontend
annotations:
nginx.ingress.kubernetes.io/proxy-body-size: "20m"
nginx.ingress.kubernetes.io/ssl-redirect: "true"
spec:
ingressClassName: nginx
tls:
- hosts: [app.acme.local]
secretName: app-tls # certificate from the internal CA
rules:
- host: app.acme.local
http:
paths:
- path: /api
pathType: Prefix
backend: { service: { name: backend, port: { number: 8080 } } }
- path: /
pathType: Prefix
backend: { service: { name: frontend, port: { number: 80 } } }
# AFTER — AWS Load Balancer Controller (ALB)
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name: web
namespace: acme-frontend
annotations:
alb.ingress.kubernetes.io/scheme: internet-facing
alb.ingress.kubernetes.io/target-type: ip
alb.ingress.kubernetes.io/group.name: acme-public # several Ingresses share one ALB
alb.ingress.kubernetes.io/listen-ports: '[{"HTTP": 80}, {"HTTPS": 443}]'
alb.ingress.kubernetes.io/ssl-redirect: "443"
alb.ingress.kubernetes.io/certificate-arn: arn:aws:acm:us-east-1:111122223333:certificate/1a2b3c4d-...
alb.ingress.kubernetes.io/ssl-policy: ELBSecurityPolicy-TLS13-1-2-2021-06
alb.ingress.kubernetes.io/healthcheck-path: /healthz
spec:
ingressClassName: alb
rules:
- host: app.acme.com
http:
paths:
- path: /api
pathType: Prefix
backend: { service: { name: backend, port: { number: 8080 } } }
- path: /
pathType: Prefix
backend: { service: { name: frontend, port: { number: 80 } } }
An Ingress can only point to Services in its own namespace. If the backend lives in acme-backend, create a second Ingress in that namespace with the same alb.ingress.kubernetes.io/group.name: the controller merges both into a single ALB with ordered rules (you can control precedence with alb.ingress.kubernetes.io/group.order).
9.5 Kustomize: one base, two targets
workloads/backend/
├── base/
│ ├── deployment.yaml
│ ├── service.yaml
│ ├── serviceaccount.yaml
│ └── kustomization.yaml
└── overlays/
├── onprem/
│ └── kustomization.yaml # Harbor, ceph-rbd, ingress nginx
└── eks-prod/
├── kustomization.yaml # ECR, gp3, ALB, ExternalSecret
├── externalsecret.yaml
└── patch-topology.yaml
# workloads/backend/overlays/eks-prod/kustomization.yaml
apiVersion: kustomize.config.k8s.io/v1beta1
kind: Kustomization
namespace: acme-backend
resources:
- ../../base
- externalsecret.yaml
images:
- name: harbor.acme.local/acme/backend
newName: 111122223333.dkr.ecr.us-east-1.amazonaws.com/acme/backend
newTag: "1.8.2"
patches:
- path: patch-topology.yaml
- target: { kind: Deployment, name: backend }
patch: |-
- op: remove
path: /spec/template/spec/imagePullSecrets
# Render the final result before applying it (and compare it with on-premises)
kubectl kustomize workloads/backend/overlays/eks-prod
diff <(kubectl kustomize workloads/backend/overlays/onprem) \
<(kubectl kustomize workloads/backend/overlays/eks-prod)
9.6 Apply order
Order matters because resources depend on each other:
- CRDs and operators (cert-manager, External Secrets, Argo CD).
- Namespaces with their security labels.
- ServiceAccounts, Roles and RoleBindings; Pod Identity associations.
- ConfigMaps,
SecretStoreandExternalSecret. - PVCs (with the
gp3orefs-scStorageClasses already created). - Services.
- Deployments and StatefulSets.
- Ingress and HPAs.
- CronJobs (suspended until cutover).
# Target CronJobs created paused
kubectl patch cronjob report-daily -n acme-backend -p '{"spec":{"suspend":true}}'
References
10. Backup and restore with Velero
10.1 What Velero is and how it works
Velero is an open source tool to back up, restore and migrate Kubernetes resources and their volumes. It runs inside the cluster and stores backups in object storage (S3 or compatible).
CSI snapshots from Ceph or Longhorn cannot be restored on AWS, so the data travels to S3 with File System Backup (Kopia). At the target, a Velero ConfigMap changes the StorageClass from ceph-rbd to gp3 during the restore.
View editable Mermaid code
sequenceDiagram
participant V1 as Velero (on-prem)
participant NA1 as node-agent (Kopia)
participant S3 as Amazon S3
participant V2 as Velero (EKS, BSL readOnly)
participant NA2 as node-agent (EKS)
V1->>V1: reads API resources (namespaces acme-*)
NA1->>S3: uploads PV data (File System Backup)
V1->>S3: uploads .tar.gz manifests + metadata
V2->>S3: syncs the backup list
V2->>V2: restore: creates PVCs (gp3) and resources
NA2->>S3: downloads data
NA2->>NA2: writes to EBS volumes Components:
- Velero server (a Deployment in the
veleronamespace): reconciles theBackup,Restore,Schedule,BackupStorageLocation(BSL) andVolumeSnapshotLocation(VSL) CRDs. - Plugins (initContainers of the server): the AWS plugin (
velero-plugin-for-aws) implements S3 storage and EBS snapshots. CSI support is built into recent Velero versions. - node-agent (DaemonSet): reads and writes the files of pod volumes. It is used by File System Backup and CSI Snapshot Data Movement, with Kopia as the upload engine (deduplication, compression and encryption). Since Velero 1.19, the Restic path has been removed entirely: Kopia is the only File System Backup engine.
veleroCLI: creates and queries backups and restores. Under the hood it creates CRD objects.
Three ways to back up volumes:
| Method | How it works | Portable across providers | Consistency |
|---|---|---|---|
| Native snapshots (VSL) | Provider snapshot (e.g. EBS) | No: a Ceph snapshot cannot be restored onto EBS | Crash-consistent |
CSI Snapshot Data Movement (--snapshot-move-data) | CSI snapshot + copy of its data to S3 with Kopia | Yes | Crash-consistent (point in time) |
| File System Backup (FSB) | The node-agent reads the files of the volume mounted in a running pod | Yes | No guarantee: copies files “live” |
For an on-premises → EKS migration, the last two work. If the source CSI driver (Ceph RBD, Longhorn) supports snapshots, CSI Snapshot Data Movement is preferable because it copies a point in time. Otherwise, use FSB with the applications stopped or in read-only mode during the final backup.
10.2 Lab: on-premises backup and restore on EKS
Step 1. S3 bucket (in the production account).
BUCKET=acme-velero-migration
aws s3api create-bucket --bucket "$BUCKET" --region us-east-1
aws s3api put-bucket-versioning --bucket "$BUCKET" --versioning-configuration Status=Enabled
aws s3api put-public-access-block --bucket "$BUCKET" \
--public-access-block-configuration BlockPublicAcls=true,IgnorePublicAcls=true,BlockPublicPolicy=true,RestrictPublicBuckets=true
aws s3api put-bucket-encryption --bucket "$BUCKET" \
--server-side-encryption-configuration '{"Rules":[{"ApplyServerSideEncryptionByDefault":{"SSEAlgorithm":"aws:kms","KMSMasterKeyID":"alias/acme-velero"}}]}'
Step 2. IAM permissions. The minimum policy, based on the one in the plugin repository, to work with S3 only:
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": ["s3:GetObject", "s3:DeleteObject", "s3:PutObject", "s3:AbortMultipartUpload", "s3:ListMultipartUploadParts"],
"Resource": "arn:aws:s3:::acme-velero-migration/*"
},
{
"Effect": "Allow",
"Action": ["s3:ListBucket"],
"Resource": "arn:aws:s3:::acme-velero-migration"
},
{
"Effect": "Allow",
"Action": ["kms:Encrypt", "kms:Decrypt", "kms:GenerateDataKey"],
"Resource": "arn:aws:kms:us-east-1:111122223333:key/REPLACE_ME"
}
]
}
- On-premises: the cluster has no AWS identity, so a dedicated IAM user with this policy and temporary, project-only access keys is used, and they are deleted at the end. A more robust alternative is IAM Roles Anywhere.
- EKS: a role with this policy, associated through Pod Identity with the
veleroServiceAccount in theveleronamespace.
Step 3. Install Velero on the on-premises cluster.
# Velero 1.19 ↔ AWS plugin 1.15 (plugin compatibility matrix, Nov. 2026)
# Use the SAME Velero version on the source and target clusters.
VELERO_PLUGIN=velero/velero-plugin-for-aws:v1.15.0
cat > credentials-velero <<'EOF'
[default]
aws_access_key_id=AKIA...REPLACE_ME
aws_secret_access_key=REPLACE_ME
EOF
velero install \
--provider aws \
--plugins "$VELERO_PLUGIN" \
--bucket acme-velero-migration \
--prefix acme \
--backup-location-config region=us-east-1 \
--use-volume-snapshots=false \
--use-node-agent \
--secret-file ./credentials-velero
rm credentials-velero # do not leave credentials on disk
velero backup-location get # must show PHASE = Available
--use-volume-snapshots=falsedisables native snapshots, which are not portable.--use-node-agentdeploys the DaemonSet needed for FSB and data movement.--prefix acmegroups backups unders3://acme-velero-migration/acme/.
Step 4. Backup. Exclude resources that must not reach EKS (nginx Ingresses, Secrets that will come from Secrets Manager) and back up volumes with FSB:
velero backup create acme-wave2-rehearsal \
--include-namespaces acme-frontend,acme-backend,acme-reports \
--exclude-resources ingresses.networking.k8s.io \
--default-volumes-to-fs-backup \
--wait
velero backup describe acme-wave2-rehearsal --details
velero backup logs acme-wave2-rehearsal | grep -iE 'error|warn'
To exclude a specific volume from FSB (for example, a cache emptyDir), annotate the pod: backup.velero.io/backup-volumes-excludes=cache.
If the application writes files continuously, use hooks to get a consistent copy:
# Annotations on the pod template
metadata:
annotations:
pre.hook.backup.velero.io/container: reports
pre.hook.backup.velero.io/command: '["/bin/sh", "-c", "touch /data/.velero-freeze && sync"]'
post.hook.backup.velero.io/command: '["/bin/sh", "-c", "rm -f /data/.velero-freeze"]'
Step 5. Install Velero on EKS pointing to the same bucket and prefix, without a secret (Pod Identity) and with the BSL in read-only mode so the source backups are never touched:
aws eks create-pod-identity-association --cluster-name acme-prod \
--namespace velero --service-account velero \
--role-arn arn:aws:iam::111122223333:role/acme-prod-velero
velero install \
--provider aws \
--plugins "$VELERO_PLUGIN" \
--bucket acme-velero-migration \
--prefix acme \
--backup-location-config region=us-east-1 \
--use-volume-snapshots=false \
--use-node-agent \
--no-secret \
--service-account-name velero
kubectl -n velero patch backupstoragelocation default --type merge \
-p '{"spec":{"accessMode":"ReadOnly"}}'
velero backup get # the on-premises backup shows up after the sync
Step 6. Map StorageClasses and modify resources. Velero does not “translate” the platform on its own; you have to declare each transformation:
# migration/velero/change-storage-class.yaml
apiVersion: v1
kind: ConfigMap
metadata:
name: change-storage-class-config
namespace: velero
labels:
velero.io/plugin-config: ""
velero.io/change-storage-class: RestoreItemAction
data:
ceph-rbd: gp3 # source: target
nfs-client: efs-sc
---
# migration/velero/change-image-name.yaml — rewrites the image registry
apiVersion: v1
kind: ConfigMap
metadata:
name: change-image-name-config
namespace: velero
labels:
velero.io/plugin-config: ""
velero.io/change-image-name: RestoreItemAction
data:
# "<old part>,<new part>" (the delimiter can only be a comma)
harbor-to-ecr: "harbor.acme.local/acme/,111122223333.dkr.ecr.us-east-1.amazonaws.com/acme/"
# migration/velero/restore-modifiers.yaml — Resource Modifiers (JSON patches at restore time)
version: v1
resourceModifierRules:
- conditions:
groupResource: deployments.apps
namespaces: ["acme-frontend", "acme-backend", "acme-reports"]
patches:
- operation: remove
path: "/spec/template/spec/imagePullSecrets"
- operation: remove
path: "/spec/template/spec/nodeSelector"
Step 7. Restore.
kubectl apply -f migration/velero/change-storage-class.yaml -f migration/velero/change-image-name.yaml
kubectl create configmap acme-restore-modifiers -n velero --from-file=migration/velero/restore-modifiers.yaml
velero restore create acme-wave2-rehearsal-restore \
--from-backup acme-wave2-rehearsal \
--resource-modifier-configmap acme-restore-modifiers \
--wait
velero restore describe acme-wave2-rehearsal-restore --details
kubectl get pvc -A | grep acme- # storageClass gp3, STATUS Bound
kubectl get pods -n acme-reports -w # restore-wait init container until the data restore finishes
With the image mapping, the restored workloads already point to ECR. Even so, at ACME Argo CD (chapter 15) then takes over and applies the final manifests from Git on top of what was restored: Velero provides the state and the data, and from that point on Git is the source of truth.
To create Velero’s IAM role on EKS, the terraform-aws-modules/eks-pod-identity module includes attach_velero_policy.
10.3 What needs a special procedure and what is not migrated
| Item | Does Velero migrate it? | What to do |
|---|---|---|
| Deployments, Services, ConfigMaps, SAs, RBAC | Yes | Review references to the on-premises platform |
| Service ClusterIPs | No (reassigned) | No action: use DNS names, never IPs |
| Non-transactional PV data | Yes (FSB / data mover) | Map the StorageClass and stop writes for the final backup |
| Live databases | Not consistently | Native replication or DMS (chapter 11) |
hostPath | No | Redesign (EBS/EFS) |
| StorageClasses, CNI, Ingress Controller, CSI | Should not be migrated | Replaced by the EKS equivalents |
| Load balancers, DNS, internal CA certificates | No | ALB/NLB, Route 53 and ACM/cert-manager |
| Identity (tokens, kubeconfigs, users) | No | Access Entries and Pod Identity |
| Operator CRDs and CRs | Yes, but the operator must exist first | Install the operator in a compatible version, then restore |
10.4 Velero troubleshooting
- BSL
Unavailable: wrong credentials or Region, or the bucket does not exist. Checkkubectl -n velero logs deploy/velero | grep -i backupstoragelocation. - Backup
PartiallyFailed: some resource or volume failed. Runvelero backup describe NAME --detailsandvelero backup logs NAME. - Pod stuck in
Init:restore-wait: the node-agent is not running on that node or the volume restore failed. Checkkubectl -n velero get podvolumerestoresand the logs of thenode-agentDaemonSet. - PVC
Pendingafter the restore: the target StorageClass does not exist or the mapping is missing. Check thechange-storage-class-configConfigMap. - Resources that “won’t restore”: by default Velero does not overwrite existing objects. Use
--existing-resource-policy=updatecarefully, or delete the objects at the target before restoring.
References
- Velero Documentation · velero-plugin-for-aws (compatibility and IAM policy)
- Velero — File System Backup · CSI Snapshot Data Movement
- Velero — Restore Resource Modifiers
11. Migrating Persistent Volumes and databases
Copying a PVC’s disk does not guarantee consistency for a live database. The right method depends on what is inside the volume, not on where it is stored.
11.1 Options by source storage type
| Source | Typical content | Recommended target | Method | Limitations |
|---|---|---|---|---|
Local PV / hostPath | Data bound to a node | EBS gp3 | Velero FSB or a copy through S3 | No CSI snapshot; writes must be stopped |
NFS (nfs-client) | Shared RWX files | Amazon EFS | AWS DataSync (or rsync) | UID/GID permissions and symlinks must be verified |
| Ceph RBD | RWO block | EBS gp3 | CSI data movement or FSB | Ceph snapshots are not portable |
| CephFS | RWX files | Amazon EFS | DataSync (mounted over NFS) or FSB | — |
| Longhorn | RWO block | EBS gp3 | CSI data movement or FSB; Longhorn also exports backups to S3 (its own format) | Native Longhorn backups only restore into Longhorn |
| VMware (vSphere CSI / VMDK) | RWO block | EBS gp3 | FSB, or migrate the VM with AWS MGN if the volume belongs to a VM | VMDKs cannot be mounted on EKS |
| Objects inside a PV (uploads, reports) | Blobs | Amazon S3 | DataSync or aws s3 sync | The application must be adapted to the S3 API (modernization) |
Choosing between EBS, EFS and S3:
- EBS: block, RWO, one AZ, low latency. For single-replica data (indexes, embedded queues).
- EFS: NFS files, RWX, multi-AZ, elastic, higher latency and a higher per-GB cost. For content shared across replicas.
- S3: objects, 11 nines of durability and the lowest cost, but it is not a file system. For uploads and artifacts, ideally accessed through the API.
11.2 Copying a volume through S3 (generic pattern)
When there is neither Velero nor DataSync, a simple, auditable pattern is to package the volume in a source Job and unpack it in a target Job:
# SOURCE (on-premises): with the app stopped (replicas=0), a temporary pod mounts the PVC
kubectl -n acme-reports run pv-export --restart=Never --image=amazon/aws-cli:latest \
--overrides='{"spec":{"volumes":[{"name":"d","persistentVolumeClaim":{"claimName":"reports-data"}}],
"containers":[{"name":"c","image":"amazon/aws-cli:latest","command":["sh","-c",
"tar -C /data -czf - . | aws s3 cp - s3://acme-velero-migration/raw/reports-data.tar.gz"],
"volumeMounts":[{"name":"d","mountPath":"/data"}],
"envFrom":[{"secretRef":{"name":"aws-migration-creds"}}]}]}}'
# TARGET (EKS): a Job with Pod Identity restores into a freshly created gp3 PVC
# aws s3 cp s3://acme-velero-migration/raw/reports-data.tar.gz - | tar -C /data -xzf -
# Verification: compare file counts and checksums on both sides
# find /data -type f | wc -l ; find /data -type f -exec sha256sum {} + | sort | sha256sum
11.3 NFS → Amazon EFS with AWS DataSync
AWS DataSync copies data between on-premises storage (NFS, SMB, HDFS, object storage) and AWS services. It uses an agent (a VM on VMware, KVM or Hyper-V on-premises) that reads the NFS share and sends the data, encrypted and verified, to EFS.
# 1. Source location: the on-premises NFS export, read by the agent
aws datasync create-location-nfs \
--server-hostname nfs01.acme.local \
--subdirectory /exports/uploads \
--on-prem-config AgentArns=arn:aws:datasync:us-east-1:111122223333:agent/agent-0abc123
# 2. Target location: the EFS file system
aws datasync create-location-efs \
--efs-filesystem-arn arn:aws:elasticfilesystem:us-east-1:111122223333:file-system/fs-0123456789abcdef0 \
--subdirectory /uploads \
--ec2-config SubnetArn=arn:aws:ec2:us-east-1:111122223333:subnet/subnet-0aaa,SecurityGroupArns=arn:aws:ec2:us-east-1:111122223333:security-group/sg-0bbb
# 3. Task with integrity verification and POSIX metadata preservation
aws datasync create-task \
--source-location-arn arn:aws:datasync:...:location/loc-src \
--destination-location-arn arn:aws:datasync:...:location/loc-dst \
--name acme-uploads \
--options VerifyMode=ONLY_FILES_TRANSFERRED,PreserveDeletedFiles=REMOVE,PosixPermissions=PRESERVE,Uid=INT_VALUE,Gid=INT_VALUE
# 4. Run it: the first run copies everything; later runs copy only changes (incremental)
aws datasync start-task-execution --task-arn arn:aws:datasync:...:task/task-0ccc
Strategy: one full copy days in advance, daily incremental copies and a final incremental during cutover with the application in read-only mode. In the pod, the EFS PVC is mounted at the same path the NFS share used.
11.4 PostgreSQL: why copying the PVC is not enough
Copying the PGDATA files while PostgreSQL is running produces an inconsistent backup: data files and WAL are copied at different moments, and the result may not start or, worse, may start with silently corrupted data. Besides, you cannot “copy the disk” into Amazon RDS, because RDS does not expose its file system. The migration happens at the logical level: SQL, replication or DMS.
First the schema is created, then data is replicated with CDC until lag reaches zero. Downtime is limited to the moment writes switch from one side to the other. Logical replication does not copy DDL or sequence state, so those are handled separately.
View editable Mermaid code
flowchart LR
subgraph OnPrem[On-premises]
APP1[backend] -->|writes| PG[(PostgreSQL 14<br/>wal_level=logical)]
end
subgraph AWS
RDS[(RDS PostgreSQL 16<br/>Multi-AZ)]
APP2[backend on EKS]
end
PG -- 1. pg_dump --schema-only --> RDS
PG -- 2. PUBLICATION / SUBSCRIPTION --> RDS
PG -. 2b. AWS DMS full load + CDC .-> RDS
APP2 -. 3. cutover .-> RDS
RDS -. rollback: reverse replication .-> PG 11.5 Option 1: pg_dump and pg_restore (downtime = dump + restore time)
Suitable for small databases (a few dozen GiB) or when a maintenance window is acceptable.
# From a host with access to both (e.g. a pod on EKS with VPN connectivity)
export PGPASSWORD=... # better: ~/.pgpass with 600 permissions
# Directory-format dump, parallel (4 jobs), consistent (single-transaction snapshot)
pg_dump -h postgresql.acme.local -U acme_admin -d acme \
-Fd -j 4 --no-owner --no-privileges -f /work/acme.dump
# Parallel restore into RDS
pg_restore -h acme-prod.abc123.us-east-1.rds.amazonaws.com -U acme_admin -d acme \
-j 4 --no-owner --no-privileges /work/acme.dump
# Roles and grants are exported separately (RDS has no superuser: review the ALTER ROLE statements)
pg_dumpall -h postgresql.acme.local -U postgres --roles-only --no-role-passwords > roles.sql
-Fd -j 4uses the directory format, the only one that supports parallel dumps.--no-owner --no-privilegesavoids errors when restoring objects owned by a role that does not exist in RDS.- RDS does not grant
SUPERUSER: the master user hasrds_superuser. Extensions must be on RDS’s supported list.
11.6 Option 2: native logical replication (recommended for ACME)
PostgreSQL logical replication sends table changes (INSERT, UPDATE, DELETE) from a publisher to a subscriber. It copies the initial load and keeps replicating until cutover, even across major versions (14 → 16), which takes care of the upgrade along the way.
Prepare RDS (Terraform):
# terraform/data/rds.tf (excerpt)
resource "aws_db_parameter_group" "acme" {
name = "acme-pg16"
family = "postgres16"
parameter {
name = "rds.force_ssl"
value = "1"
}
# Only needed if RDS will act as a publisher (reverse replication for rollback)
parameter {
name = "rds.logical_replication"
value = "1"
apply_method = "pending-reboot"
}
}
resource "aws_db_instance" "acme" {
identifier = "acme-prod"
engine = "postgres"
engine_version = "16"
instance_class = "db.m7g.large"
allocated_storage = 200
max_allocated_storage = 500
storage_type = "gp3"
storage_encrypted = true
kms_key_id = aws_kms_key.data.arn
db_name = "acme"
username = "acme_admin"
manage_master_user_password = true # the password lives in Secrets Manager, with rotation
multi_az = true
db_subnet_group_name = data.terraform_remote_state.vpc.outputs.database_subnet_group_name
vpc_security_group_ids = [aws_security_group.rds.id]
parameter_group_name = aws_db_parameter_group.acme.name
backup_retention_period = 14
deletion_protection = true
copy_tags_to_snapshot = true
performance_insights_enabled = true
enabled_cloudwatch_logs_exports = ["postgresql"]
}
Prepare the source (on-premises):
# postgresql.conf (requires a restart)
wal_level = logical
max_replication_slots = 10
max_wal_senders = 10
# pg_hba.conf: allow the replication connection from the AWS data subnets
hostssl acme replicator 10.20.96.0/22 scram-sha-256
Because PostgreSQL runs inside Kubernetes, RDS must be able to reach it over the VPN. Expose the StatefulSet with a Service reachable from the corporate network (a MetalLB LoadBalancer or a firewall-restricted NodePort) and open port 5432 only from 10.20.96.0/22.
Step by step:
-- 1) SOURCE: replication user and publication
CREATE ROLE replicator WITH LOGIN REPLICATION PASSWORD 'REPLACE_ME';
GRANT USAGE ON SCHEMA public TO replicator;
GRANT SELECT ON ALL TABLES IN SCHEMA public TO replicator;
-- Every table needs a PRIMARY KEY (or REPLICA IDENTITY FULL) to replicate UPDATE/DELETE
SELECT n.nspname, c.relname
FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace
WHERE c.relkind = 'r' AND n.nspname NOT IN ('pg_catalog', 'information_schema')
AND NOT EXISTS (SELECT 1 FROM pg_constraint p WHERE p.conrelid = c.oid AND p.contype = 'p');
CREATE PUBLICATION acme_pub FOR ALL TABLES;
# 2) SCHEMA in RDS (logical replication does NOT replicate DDL)
pg_dump -h postgresql.acme.local -U acme_admin -d acme --schema-only --no-owner --no-privileges \
| psql -h acme-prod.abc123.us-east-1.rds.amazonaws.com -U acme_admin -d acme
-- 3) TARGET (RDS, with the rds_superuser master user): subscription.
-- It copies the initial load and then applies changes continuously.
CREATE SUBSCRIPTION acme_sub
CONNECTION 'host=10.0.20.15 port=5432 dbname=acme user=replicator password=REPLACE_ME sslmode=require'
PUBLICATION acme_pub;
-- Initial sync status per table: 'r' = ready (in continuous replication)
SELECT srrelid::regclass AS table_name, srsubstate FROM pg_subscription_rel ORDER BY 2;
-- 4) Lag MONITORING from the SOURCE
SELECT slot_name, active,
pg_size_pretty(pg_wal_lsn_diff(pg_current_wal_lsn(), confirmed_flush_lsn)) AS lag
FROM pg_replication_slots;
11.7 Option 3: AWS Database Migration Service (DMS)
AWS DMS performs the full load plus CDC (Change Data Capture) as a managed service, with monitoring, retries and built-in data validation. It makes sense when you do not want to manage slots and subscriptions by hand, when there are many databases, or when the target is a different engine (heterogeneous migration, with AWS SCT or DMS Schema Conversion).
- PostgreSQL source requirements:
wal_level = logical, a user with replication permissions, and connectivity from the DMS replication instance (or DMS Serverless) to the source. - Schema: create it first with
pg_dump --schema-only(as in option 2) and configure the task withTargetTablePrepMode: DO_NOTHING. DMS migrates tables and data, but not every secondary object (views, functions, triggers).
{
"rules": [
{
"rule-type": "selection",
"rule-id": "1",
"rule-name": "public-schema",
"object-locator": { "schema-name": "public", "table-name": "%" },
"rule-action": "include"
}
]
}
aws dms create-replication-task \
--replication-task-identifier acme-pg-full-cdc \
--source-endpoint-arn arn:aws:dms:us-east-1:111122223333:endpoint:SRC \
--target-endpoint-arn arn:aws:dms:us-east-1:111122223333:endpoint:TGT \
--replication-instance-arn arn:aws:dms:us-east-1:111122223333:rep:INST \
--migration-type full-load-and-cdc \
--table-mappings file://table-mappings.json \
--replication-task-settings '{"TargetMetadata":{"TargetTablePrepMode":"DO_NOTHING"},"ValidationSettings":{"EnableValidation":true}}'
| Criterion | pg_dump/restore | Native logical replication | AWS DMS |
|---|---|---|---|
| Downtime | High (hours for large databases) | Minutes | Minutes |
| Complexity | Low | Medium | Medium |
| Cost | None | None | Replication instance or DMS Serverless |
| Built-in validation | No | No | Yes |
| Major version change | Yes | Yes | Yes |
| Best for | Small databases, dev/staging | A single PostgreSQL → PostgreSQL database | Many or heterogeneous databases, teams that prefer managed services |
Choice for ACME: native logical replication. It is a single 180 GiB database, the same engine, and a team experienced with PostgreSQL. DMS would be plan B if tables without primary keys that are hard to fix, or performance problems during the initial load, showed up.
11.8 Consistency validation
-- Exact row count per table: run on source and target and compare
SELECT format('SELECT %L AS table_name, count(*) FROM %I.%I;', schemaname || '.' || relname, schemaname, relname)
FROM pg_stat_user_tables ORDER BY 1;
-- Checksum of a table (suitable for moderately sized tables)
SELECT md5(string_agg(t::text, '|' ORDER BY t.id)) FROM public.invoices t;
-- Checksum by range, for large tables (compares blocks of IDs)
SELECT id / 100000 AS block, md5(string_agg(t::text, '|' ORDER BY t.id))
FROM public.invoice_lines t GROUP BY 1 ORDER BY 1;
Besides the data, validate: extensions (\dx), indexes, constraints, functions, triggers, application role permissions and the collation. A glibc or ICU version change between source and target can alter the ordering of text indexes.
11.9 Final sync and handling downtime
- Put the application in maintenance mode or read-only:
kubectl scale deploy/backend --replicas=0at the source, or a feature flag. - Verify that no write connections remain:
SELECT * FROM pg_stat_activity WHERE datname = 'acme' AND state <> 'idle';. - Wait for the lag to reach 0 (the
pg_replication_slotsquery). - Sync the sequences in RDS:
-- On the SOURCE: generates the setval statements to run on the TARGET
SELECT format('SELECT setval(%L, %s, true);', schemaname || '.' || sequencename, last_value)
FROM pg_sequences WHERE last_value IS NOT NULL;
- Run the validations from section 11.8.
ALTER SUBSCRIPTION acme_sub DISABLE;in RDS, and point the application on EKS to the RDS endpoint.- Rollback ready: with
rds.logical_replication = 1, create a publication in RDS and a subscription at the source (withcopy_data = false) so changes made on AWS flow back on-premises during the rollback window.
11.10 Redis → Amazon ElastiCache
First, a question: what does Redis store?
- Cache (the most common case): it is not migrated. An empty ElastiCache is created and the application fills it through use (warm-up). If a cold start is expensive, you can pre-warm it with a script that walks the most used keys.
- Sessions: when Redis changes, users have to sign in again. This is usually acceptable if communicated; otherwise, migrate the data.
- Persistent data (queues, counters, leaderboards): requires a real migration.
Options to migrate data:
- Seed from an RDB file:
redis-cli --rdb dump.rdbat the source, upload it to S3 and create the (node-based) ElastiCache cluster with that RDB as the source. Changes made after the RDB are lost. - ElastiCache online migration: replicates from a self-managed Valkey or Redis OSS into a node-based cluster until cutover. It is designed for sources on Amazon EC2 and has strict requirements: the target must have Multi-AZ and no in-transit encryption, the source cannot have AUTH enabled (and needs
protected-mode no), and the number of shards and logical databases must match. For an on-premises Redis with a password, running in a Kubernetes cluster, it does not fit without changes: ACME rules it out. - Key replication tools such as RIOT (Redis Input/Output Tools), which read from the source and write to the target, with a continuous replication mode based on keyspace notifications.
Target: ElastiCache offers the Valkey engine (an open source fork of Redis, protocol-compatible and cheaper) and Redis OSS. For ACME, Valkey is chosen, with a replica in another AZ, automatic failover, encryption in transit (TLS) and at rest, and authentication with users and ACLs. In the application, Spring Boot only needs the new host and spring.data.redis.ssl.enabled=true.
References
- PostgreSQL — Logical Replication · pg_dump
- AWS DMS — PostgreSQL as a source · AWS DMS User Guide
- AWS DataSync
- Amazon RDS for PostgreSQL · Amazon ElastiCache
12. Migrating networking
12.1 Pod networking: overlay vs. VPC IPs
In the on-premises cluster, Calico assigns pods IPs from a private range (192.168.0.0/16) that only exists inside the cluster: it is an overlay network (IP-in-IP or VXLAN). To reach a pod from outside, you have to go through a node (NodePort, hostNetwork) or a load balancer.
On EKS, the Amazon VPC CNI assigns each pod a real IP from the VPC subnet, attaching secondary ENIs to each node. The consequences are significant:
- An ALB or NLB can send traffic directly to the pod (
target-type: ip), without a NodePort. - Pods are reachable from other VPCs or from on-premises (if routes and Security Groups allow it).
- Every pod consumes a VPC IP. The maximum number of pods per node depends on the instance type (ENIs × IPs per ENI). With prefix delegation, the limit rises considerably.
- If IPs are scarce, you can add a secondary CIDR (for example,
100.64.0.0/16) with custom networking for pods.
12.2 Services, Ingress and DNS
| Concept | On-premises (ACME) | Amazon EKS |
|---|---|---|
| ClusterIP | kube-proxy with iptables | Same (kube-proxy managed as an add-on) |
| NodePort | Used by F5 to reach ingress-nginx | Avoided: the ALB reaches pods directly |
type: LoadBalancer | Requires MetalLB | AWS LBC creates an NLB (with annotations) |
| Ingress | ingress-nginx | AWS LBC creates an ALB |
| Internal DNS | CoreDNS (cluster.local) | Same; for acme.local, Route 53 Resolver |
| External DNS | BIND + manual records | Route 53 (+ ExternalDNS to automate it) |
| NetworkPolicy | Calico | VPC CNI with standard policies, or Calico/Cilium if advanced CRDs are needed |
| Perimeter firewall | Physical firewall | Security Groups, NACLs, AWS WAF, AWS Network Firewall |
| Internet egress | Corporate firewall NAT | NAT Gateway per AZ (fixed Elastic IP) |
On-premises, the request goes through a VIP, a NodePort, ingress-nginx and kube-proxy before reaching an overlay IP. On EKS with target-type ip, the ALB delivers straight to the pod IP, which is a native VPC IP. There are fewer hops, and Security Groups can be applied per pod.
12.3 Service type LoadBalancer → Network Load Balancer
For non-HTTP TCP/UDP traffic (for example, a gRPC service without TLS termination at the load balancer, or a proprietary protocol):
apiVersion: v1
kind: Service
metadata:
name: events-gateway
namespace: acme-backend
annotations:
service.beta.kubernetes.io/aws-load-balancer-type: external # managed by the AWS LBC
service.beta.kubernetes.io/aws-load-balancer-nlb-target-type: ip
service.beta.kubernetes.io/aws-load-balancer-scheme: internal # only inside the VPC / VPN
spec:
type: LoadBalancer
selector: { app: events-gateway }
ports:
- port: 9443
targetPort: 9443
protocol: TCP
Without the aws-load-balancer-type: external annotation, the Service would be handled by the legacy controller in the Kubernetes cloud provider, which creates load balancers with different behavior. With the AWS LBC installed, always use the controller’s annotations.
12.4 Replacing ingress-nginx… or keeping it
When to replace it with ALB (ACME’s option):
- Most rules are host- and path-based, with TLS, redirects and health checks: ALB annotations cover all of this.
- You want to integrate ACM (managed certificates), AWS WAF and Cognito/OIDC at the load balancer.
- You want to remove a layer: with ALB and
target-type: ipthere are no ingress pods to scale or patch.
When to keep an NGINX controller (or another in-cluster proxy):
- You use features the ALB does not offer: configuration snippets, complex regex rewrites, per-key rate limiting, very specific external authentication, or ingress-nginx’s TCP streaming.
- There are hundreds of Ingresses with
nginx.ingress.kubernetes.io/*annotations and the deadline does not allow rewriting them.
In that case, the recommended architecture is NLB → in-cluster controller: an NLB (target-type: ip) in front of the controller, which must be a maintained alternative (F5 NGINX Ingress Controller, Traefik, HAProxy, Envoy Gateway or whatever controller the team chooses), never the retired ingress-nginx. In the medium term, it pays to converge on Gateway API, the successor to Ingress. Gateway API support in the AWS Load Balancer Controller has been GA since version 3.0 (ALB for HTTP/gRPC routes and NLB for L4 routes), and most of the controllers mentioned support it too.
12.5 NetworkPolicies
Standard NetworkPolicies (networking.k8s.io/v1) migrate unchanged when the VPC CNI has enableNetworkPolicy enabled. Calico-specific policies (GlobalNetworkPolicy, NetworkPolicy from projectcalico.org) must be converted to standard policies or, if you need their capabilities (global policies, FQDN rules), install Calico or Cilium for policy enforcement.
# Zero-trust baseline per namespace: deny all ingress and allow explicitly
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: default-deny-ingress
namespace: acme-backend
spec:
podSelector: {}
policyTypes: [Ingress]
---
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: allow-frontend-to-backend
namespace: acme-backend
spec:
podSelector:
matchLabels: { app: backend }
policyTypes: [Ingress]
ingress:
- from:
- namespaceSelector:
matchLabels: { kubernetes.io/metadata.name: acme-frontend }
ports:
- port: 8080
protocol: TCP
With target-type: ip, ALB traffic reaches pods from the load balancer’s IPs in the public subnets. If you apply default-deny, you must allow that source (the public subnets’ CIDR block) to the exposed pod ports.
12.6 Firewall, NAT and VPN
- Security Groups: the ALB SG allows 443 from
0.0.0.0/0; the node SG allows traffic from the ALB SG; the RDS SG allows 5432 only from the node SG. With Security Groups for Pods (ENABLE_POD_ENI) you can restrict RDS to the backend pods instead of every node. - Egress IP: outbound calls from pods leave through the Elastic IP of each AZ’s NAT Gateway. Give those IPs to vendors with allowlists (banks, government APIs) well in advance.
- VPN: verify that routes to
10.0.0.0/16are propagated to the private and data subnet route tables, and that the on-premises firewall allows return traffic from10.20.0.0/16.
References
- Amazon VPC CNI · Network policies with the VPC CNI
- Ingress NGINX Retirement (Kubernetes blog)
- AWS LBC — Service annotations · Gateway API
13. Security and compliance
The migration is the best opportunity to pay down security debt, because everything gets rebuilt. These are the controls by layer:
13.1 Identity and access: IAM, Access Entries and RBAC
- People: IAM Identity Center (SSO) → per-team roles → Access Entries with EKS access policies (
AmazonEKSClusterAdminPolicy,AmazonEKSAdminPolicy,AmazonEKSEditPolicy,AmazonEKSViewPolicy) or Kubernetes groups bound to your own RBAC. - Pipelines: GitHub Actions or GitLab with OIDC to an IAM role, no access keys. With GitOps, the pipeline does not need cluster access.
- Pods: EKS Pod Identity with one role per application and minimal permissions.
- Least privilege in practice: start with permissions scoped to specific resources (ARNs, not
*), use IAM Access Analyzer to generate policies from actual CloudTrail activity, and periodically review unused permissions.
# RBAC: developers can view and restart deployments only in their namespace
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
name: deployer
namespace: acme-backend
rules:
- apiGroups: ["apps"]
resources: ["deployments", "deployments/scale"]
verbs: ["get", "list", "watch", "patch"]
- apiGroups: [""]
resources: ["pods", "pods/log"]
verbs: ["get", "list", "watch"]
13.2 Pod Security Standards
The Pod Security Standards (privileged, baseline, restricted) are enforced per namespace by Pod Security Admission, built into Kubernetes. They replace PodSecurityPolicies, which were removed in version 1.25.
apiVersion: v1
kind: Namespace
metadata:
name: acme-backend
labels:
pod-security.kubernetes.io/enforce: restricted
pod-security.kubernetes.io/enforce-version: latest
pod-security.kubernetes.io/warn: restricted
pod-security.kubernetes.io/audit: restricted
restricted requires, among other things, runAsNonRoot, allowPrivilegeEscalation: false, dropping all capabilities and using the RuntimeDefault seccomp profile. Apply it first in warn and audit mode to find out which workloads violate it before enforcing it with enforce.
13.3 Secrets management: Secrets Manager, KMS and External Secrets
EKS encrypts Kubernetes API data (including Secrets) in etcd with envelope encryption, and you can use your own KMS CMK. Even so, a Kubernetes Secret is readable by anyone with get secrets permission in the namespace. The recommended practice is for Secrets Manager to be the source of truth and for the cluster to hold only a synced copy:
# ClusterSecretStore: External Secrets Operator authenticates with Pod Identity
apiVersion: external-secrets.io/v1
kind: ClusterSecretStore
metadata:
name: aws-secrets-manager
spec:
provider:
aws:
service: SecretsManager
region: us-east-1
---
# ExternalSecret: creates/updates the "backend-db" Secret from Secrets Manager
apiVersion: external-secrets.io/v1
kind: ExternalSecret
metadata:
name: backend-db
namespace: acme-backend
spec:
refreshInterval: 1h
secretStoreRef:
kind: ClusterSecretStore
name: aws-secrets-manager
target:
name: backend-db
data:
- secretKey: SPRING_DATASOURCE_USERNAME
remoteRef: { key: acme/prod/backend/db, property: username }
- secretKey: SPRING_DATASOURCE_PASSWORD
remoteRef: { key: acme/prod/backend/db, property: password }
External Secrets holds the permission to read Secrets Manager, not the application: associate a role with the ESO controller’s ServiceAccount through Pod Identity (the eks-pod-identity module includes attach_external_secrets_policy) and scope it to the acme/prod/* ARNs.
An alternative is the Secrets Store CSI Driver with the AWS provider (ASCP), which mounts secrets as files without creating Secret objects. External Secrets is more convenient when applications expect environment variables.
13.4 TLS everywhere
- Edge: TLS 1.2/1.3 on the ALB with ACM certificates.
- ALB → pods: if end-to-end encryption is required, use
alb.ingress.kubernetes.io/backend-protocol: HTTPSwith internal certificates (cert-manager). - Data:
rds.force_ssl = 1on RDS, TLS on ElastiCache andsslmode=require(orverify-fullwith the RDS CA bundle) in the application. - Between services: if compliance requires it, you can use mTLS with a service mesh.
13.5 Detection, vulnerabilities and compliance
| Tool | Type | What it provides |
|---|---|---|
| Amazon Inspector | AWS service | Continuous scanning of ECR images and EC2 instances |
| Trivy | Open source | Scanning of images, IaC (Terraform), manifests and SBOMs in the pipeline (shift left) |
| Amazon GuardDuty | AWS service | EKS Protection (audit log analysis) and Runtime Monitoring (agent on the nodes) |
| Falco | Open source (CNCF) | Runtime anomaly detection with custom rules |
| AWS CloudTrail | AWS service | Auditing of every AWS API call (including EKS ones) |
| AWS Security Hub (and Security Hub CSPM) | AWS service | Consolidates findings (GuardDuty, Inspector, Config) and evaluates standards such as AWS Foundational Security Best Practices or CIS |
| AWS Config | AWS service | Inventory and conformance rules for resource configuration |
13.6 The most common security mistakes (and how to avoid them)
- Access keys in Secrets or CI variables. Use Pod Identity and OIDC: not a single long-lived access key should exist.
- Public cluster endpoint open to
0.0.0.0/0. Make it private or restrict the CIDRs. - Over-privileged node roles. Pods inherit the node role if they have no identity of their own: give each pod permissions with Pod Identity and block pod access to the node’s IMDS (
httpPutResponseHopLimit = 1in the launch template). - Security Groups with
0.0.0.0/0to databases. RDS and ElastiCache never go in public subnets or with open access. - Secrets copied “as is” from on-premises. Rotate every credential during the migration: assume the old ones may have leaked over years of operation.
- Ignoring control plane logs. Enable
auditandauthenticatorfrom day one; investigating an incident without them is impossible. - Images running as root and without scanning. Pod Security
restrictedplus Inspector and Trivy in the pipeline.
References
- EKS Best Practices — Security
- External Secrets Operator · AWS Secrets Manager
- GuardDuty Runtime Monitoring · Amazon Inspector · AWS Security Hub
- Trivy · Falco
14. Observability and monitoring
14.1 What to keep and what to integrate
The practical rule is to keep the languages and interfaces the team already knows (PromQL, Grafana dashboards and Alertmanager rules) and hand storage and operations over to managed services.
| Signal | On-premises (ACME) | On AWS | Decision |
|---|---|---|---|
| Metrics | Prometheus (300 GiB local TSDB) | Amazon Managed Service for Prometheus (AMP) with remote_write | Keep PromQL, delegate storage and HA |
| Dashboards | Self-managed Grafana | Amazon Managed Grafana (or Grafana in the cluster) | Export and import the dashboard JSON |
| Alerts | Alertmanager | AMP alert manager → SNS → Slack/PagerDuty | Migrate rules (same YAML format) |
| Logs | kubectl logs and a small ELK | CloudWatch Logs via the amazon-cloudwatch-observability add-on (Fluent Bit) | Centralized logs with defined retention |
| Infrastructure metrics | node-exporter | Container Insights (enhanced observability) | Cluster, node and pod view with no maintenance |
| Traces | Did not exist | OpenTelemetry (ADOT) → AWS X-Ray | New capability, introduced gradually |
Metrics travel via SigV4-signed remote_write to Amazon Managed Service for Prometheus. Logs go to CloudWatch Logs through the amazon-cloudwatch-observability add-on (CloudWatch agent + Fluent Bit), and OTLP traces go to X-Ray. Grafana queries all three sources.
14.2 Metrics: Prometheus → AMP
There are two ways to send metrics to AMP:
- In-cluster collector: Prometheus in agent mode or the ADOT Collector scrapes and sends with SigV4-signed
remote_write(using Pod Identity). - AMP managed collector (scraper): AWS scrapes the cluster’s endpoints without deploying anything into it. It is simpler, with less configuration flexibility.
# kube-prometheus-stack chart values.yaml in "agent" mode towards AMP (excerpt)
prometheus:
serviceAccount:
name: amp-ingest # associated through Pod Identity with a role that has aps:RemoteWrite
prometheusSpec:
retention: 2h # minimal local storage: AMP is the source of truth
remoteWrite:
- url: https://aps-workspaces.us-east-1.amazonaws.com/workspaces/ws-xxxxxxxx/api/v1/remote_write
sigv4:
region: us-east-1
queueConfig:
maxSamplesPerSend: 1000
capacity: 2500
14.3 Logs and Container Insights
# Managed add-on: CloudWatch agent + Fluent Bit + Container Insights
aws eks create-addon --cluster-name acme-prod --addon-name amazon-cloudwatch-observability
# Explicit retention: without it, logs are kept forever (and paid for forever)
aws logs put-retention-policy --log-group-name /aws/containerinsights/acme-prod/application --retention-in-days 30
The CloudWatch agent needs permissions (the CloudWatchAgentServerPolicy policy), granted to its ServiceAccount through Pod Identity.
14.4 Distributed tracing with OpenTelemetry
OpenTelemetry is the CNCF standard for instrumenting traces, metrics and logs. For Spring Boot, the OpenTelemetry Java agent instruments HTTP, JDBC and Redis without code changes. The ADOT Collector (AWS Distro for OpenTelemetry) receives traces over OTLP and exports them to X-Ray, or to any other OTLP-compatible backend. With tracing, new latency caused by the migration (for example, a call that still crosses the VPN back to on-premises) shows up immediately in the service map.
14.5 Minimum alerts for cutover day
- ALB 5xx error rate (
HTTPCode_Target_5XX_Count) and p95 latency (TargetResponseTime). - Pods not
Readyand restarts (kube_pod_container_status_restarts_total). - RDS CPU and connections (
CPUUtilization,DatabaseConnections) and read and write latency. - ElastiCache hits/misses and evictions (relevant during warm-up).
- CoreDNS DNS errors and AWS API throttling in the controllers.
References
- Amazon Managed Service for Prometheus · Amazon Managed Grafana
- CloudWatch Observability add-on
- AWS Distro for OpenTelemetry · OpenTelemetry · Fluent Bit
15. CI/CD and GitOps
15.1 From “push” to “pull”
On-premises, ACME’s GitLab deployed with kubectl apply using an administrator kubeconfig stored as a CI variable. That is a push model: the pipeline holds cluster credentials, and anyone who can modify a pipeline can modify production.
With GitOps, the model is inverted (pull). An agent inside the cluster (Argo CD or Flux) watches a Git repository and reconciles the cluster with what is declared there. The CI pipeline only builds, tests, publishes the image and updates the tag in Git. As a result:
- Git is the auditable source of truth: every deployment is a commit, and a rollback is a
git revert. - The pipeline has no cluster credentials.
- Drift (manual changes with
kubectl edit) is detected and corrected automatically.
The pipeline never receives cluster credentials. It pushes the image to ECR with temporary credentials (OIDC) and updates the tag in the GitOps repository. Argo CD, running inside EKS, detects the change and reconciles the desired state.
View editable Mermaid code
flowchart LR
DEV[Developer] -->|1. git push| REPO[App repo]
REPO -->|2. trigger| GHA[GitHub Actions]
GHA -->|3-4. build, test, Trivy, docker build| GHA
GHA -->|OIDC AssumeRoleWithWebIdentity| IAM[IAM role]
GHA -->|5. push image| ECR[(Amazon ECR)]
GHA -->|6. commit image.tag| GITOPS[GitOps repo]
ARGO[Argo CD] -->|7. watches| GITOPS
ARGO -->|8. sync| EKS[Amazon EKS]
EKS -->|9. pull| ECR | Argo CD | Flux CD | |
|---|---|---|
| Interface | Full web UI, RBAC and SSO | Mostly CLI and CRDs (third-party UIs) |
| Model | Application / ApplicationSet | Kustomization / HelmRelease |
| Multi-cluster | Central hub that manages several clusters | One Flux per cluster (or hierarchies) |
| Choice for ACME | Yes: the team values the UI for visualizing drift and sync status | — |
15.2 OIDC trust between GitHub Actions and AWS
# terraform/cicd/github-oidc.tf
resource "aws_iam_openid_connect_provider" "github" {
url = "https://token.actions.githubusercontent.com"
client_id_list = ["sts.amazonaws.com"]
}
data "aws_iam_policy_document" "gha_trust" {
statement {
actions = ["sts:AssumeRoleWithWebIdentity"]
principals {
type = "Federated"
identifiers = [aws_iam_openid_connect_provider.github.arn]
}
condition {
test = "StringEquals"
variable = "token.actions.githubusercontent.com:aud"
values = ["sts.amazonaws.com"]
}
# Only the acme/backend repository, main branch, can assume this role
condition {
test = "StringEquals"
variable = "token.actions.githubusercontent.com:sub"
values = ["repo:acme/backend:ref:refs/heads/main"]
}
}
}
resource "aws_iam_role" "gha_ecr_push" {
name = "acme-gha-ecr-push"
assume_role_policy = data.aws_iam_policy_document.gha_trust.json
}
data "aws_iam_policy_document" "ecr_push" {
statement {
actions = ["ecr:GetAuthorizationToken"]
resources = ["*"]
}
statement {
actions = [
"ecr:BatchCheckLayerAvailability", "ecr:InitiateLayerUpload", "ecr:UploadLayerPart",
"ecr:CompleteLayerUpload", "ecr:PutImage", "ecr:BatchGetImage", "ecr:DescribeImages"
]
resources = ["arn:aws:ecr:us-east-1:111122223333:repository/acme/backend"]
}
}
resource "aws_iam_role_policy" "gha_ecr_push" {
role = aws_iam_role.gha_ecr_push.id
policy = data.aws_iam_policy_document.ecr_push.json
}
15.3 Complete pipeline (GitHub Actions)
The pipeline covers all 7 steps: build, test, scan for vulnerabilities, build the image, publish it to ECR, update the version in the GitOps repository and deploy to EKS through Argo CD.
# .github/workflows/ci.yaml (acme/backend repository)
name: backend-ci
on:
push:
branches: [main]
pull_request:
permissions:
contents: read
id-token: write # required for OIDC with AWS
env:
AWS_REGION: us-east-1
ECR_REPOSITORY: acme/backend
jobs:
build-test-scan:
runs-on: ubuntu-latest
outputs:
image_tag: ${{ steps.meta.outputs.tag }}
steps:
- uses: actions/checkout@v7
# 1. Build
- uses: actions/setup-java@v6
with:
distribution: temurin
java-version: "21"
cache: maven
- name: Build
run: ./mvnw -B -DskipTests package
# 2. Tests
- name: Tests
run: ./mvnw -B verify
# 3a. Dependency and Dockerfile scan (before building)
- name: Trivy filesystem scan
uses: aquasecurity/trivy-action@v0.36.0 # in production, pin it by commit SHA
with:
scan-type: fs
scan-ref: .
severity: CRITICAL,HIGH
exit-code: "1"
ignore-unfixed: true
# 4. Build the image
- name: Image metadata
id: meta
run: echo "tag=git-${GITHUB_SHA::7}" >> "$GITHUB_OUTPUT"
- name: Docker build
run: docker build -t "$ECR_REPOSITORY:${{ steps.meta.outputs.tag }}" .
# 3b. Scan the resulting image
- name: Trivy image scan
uses: aquasecurity/trivy-action@v0.36.0
with:
image-ref: ${{ env.ECR_REPOSITORY }}:${{ steps.meta.outputs.tag }}
severity: CRITICAL,HIGH
exit-code: "1"
ignore-unfixed: true
# 5. Publish to ECR (main only), with temporary credentials via OIDC
- name: Configure AWS credentials
if: github.ref == 'refs/heads/main'
uses: aws-actions/configure-aws-credentials@v6
with:
role-to-assume: arn:aws:iam::111122223333:role/acme-gha-ecr-push
aws-region: ${{ env.AWS_REGION }}
- name: Login to ECR
if: github.ref == 'refs/heads/main'
id: ecr
uses: aws-actions/amazon-ecr-login@v2
- name: Push
if: github.ref == 'refs/heads/main'
run: |
IMAGE="${{ steps.ecr.outputs.registry }}/$ECR_REPOSITORY:${{ steps.meta.outputs.tag }}"
docker tag "$ECR_REPOSITORY:${{ steps.meta.outputs.tag }}" "$IMAGE"
docker push "$IMAGE"
# 6. Update the version in the GitOps repository (7. Argo CD deploys)
update-gitops:
needs: build-test-scan
if: github.ref == 'refs/heads/main'
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v7
with:
repository: acme/platform-gitops
token: ${{ secrets.GITOPS_TOKEN }} # GitHub App token with write access to that repo only
- name: Bump image tag
run: |
cd workloads/backend/overlays/eks-prod
kustomize edit set image \
harbor.acme.local/acme/backend=111122223333.dkr.ecr.us-east-1.amazonaws.com/acme/backend:${{ needs.build-test-scan.outputs.image_tag }}
git config user.name "acme-ci"
git config user.email "ci@acme.example"
git commit -am "backend: ${{ needs.build-test-scan.outputs.image_tag }}"
git push
GitLab CI follows the same pattern: GitLab’s ID token (id_tokens: in the job) is exchanged for AWS credentials with aws sts assume-role-with-web-identity, and the final stage commits to the GitOps repository. AWS CodeBuild is an option when you want the build to run inside the AWS account (for example, to access private VPC resources), and it can be used as a managed GitHub Actions runner.
15.4 Argo CD: installation and applications
helm repo add argo https://argoproj.github.io/argo-helm
helm upgrade --install argocd argo/argo-cd \
--namespace argocd --create-namespace \
--set configs.params."server\.insecure"=true # TLS terminates at the ALB; expose the UI only on the internal network/SSO
# gitops/argocd/apps/backend.yaml
apiVersion: argoproj.io/v1alpha1
kind: Application
metadata:
name: backend-prod
namespace: argocd
spec:
project: acme-prod
source:
repoURL: https://github.com/acme/platform-gitops.git
targetRevision: main
path: workloads/backend/overlays/eks-prod
destination:
server: https://kubernetes.default.svc
namespace: acme-backend
syncPolicy:
automated:
prune: true # removes from the cluster whatever is deleted from Git
selfHeal: true # reverts manual changes (drift)
syncOptions:
- CreateNamespace=false
- ServerSideApply=true
The app of apps pattern (or an ApplicationSet with generators) lets a single root Application create the applications for every wave from the GitOps repository’s directory tree.
15.5 Terraform in the flow
Infrastructure follows its own cycle: terraform plan on every pull request (with the plan posted as a comment) and terraform apply after approval, with remote state in S3 and native locking. Tools such as Atlantis or HCP Terraform workflows automate this flow. The rule is that no infrastructure is created by hand in the console, not even “temporarily”.
References
- Argo CD · Flux
- aws-actions/configure-aws-credentials · amazon-ecr-login
- Trivy Action · Terraform Documentation
16. Cutover: switching production
The cutover is the moment AWS becomes the production system. Everything before it exists to make this step boring, predictable and reversible.
The bars show what percentage of traffic AWS serves at each point. As long as reverse replication exists and the rollback window is open, going back to on-premises means changing the Route 53 weights.
View editable Mermaid code
stateDiagram-v2
[*] --> Freeze: T-7d
Freeze --> Rehearsal: T-1d
Rehearsal --> Maintenance: Go
Rehearsal --> Freeze: No-Go
Maintenance --> FinalSync: lag = 0
FinalSync --> Canary10: Route 53 weight 10%
Canary10 --> Full100: SLOs OK
Canary10 --> Rollback: SLOs fail
Full100 --> Hypercare
Full100 --> Rollback: major incident
Rollback --> [*]: Route 53 100% on-prem
Hypercare --> [*] 16.1 Preparation (T−7 days to T−1 day)
- Change freeze: only critical fixes, applied in both environments.
- Lower the TTL of DNS records to 60 seconds at least a week in advance, so the destination change propagates quickly (and so does a rollback).
- Full rehearsal (dry-run) in staging with realistic data, timing every step.
- Runbook with each step, its owner, the estimated time, the exact command and the rollback criterion.
- Go/No-Go meeting: replication lag steady at zero, load tests passed, alarms configured and owners available.
16.2 Traffic shifting with Route 53
# Weighted records: 90 % on-premises / 10 % AWS (two records with the same name)
cat > shift-10.json <<'EOF'
{
"Comment": "ACME cutover: 10% to AWS",
"Changes": [
{
"Action": "UPSERT",
"ResourceRecordSet": {
"Name": "app.acme.com", "Type": "A", "SetIdentifier": "aws", "Weight": 10,
"AliasTarget": {
"HostedZoneId": "Z35SXDOTRQ7X7K",
"DNSName": "dualstack.k8s-acmepublic-abc123.us-east-1.elb.amazonaws.com",
"EvaluateTargetHealth": true
}
}
},
{
"Action": "UPSERT",
"ResourceRecordSet": {
"Name": "app.acme.com", "Type": "A", "SetIdentifier": "onprem", "Weight": 90,
"TTL": 60, "ResourceRecords": [{ "Value": "203.0.113.20" }],
"HealthCheckId": "11111111-2222-3333-4444-555555555555"
}
}
]
}
EOF
aws route53 change-resource-record-sets --hosted-zone-id Z0123456789ABC --change-batch file://shift-10.json
HostedZoneId inside AliasTarget is the ALB’s zone (fixed per Region; the example value is the one for ALBs in us-east-1), not your zone. EvaluateTargetHealth and the health check make Route 53 stop sending traffic to an unhealthy target.
16.3 Cutover day sequence (ACME)
- T−2 h · Maintenance announcement. On-premises CronJobs suspended (
suspend: true). - T−1 h · On-premises backend in read-only mode; wait for
lag = 0; sync sequences; data validation (chapter 11). Final DataSync incremental for the uploads. - T−30 min · On-premises backend and EKS backend reconfigured to write to RDS. Subscription disabled; reverse replication RDS → on-premises enabled (for rollback).
- T0 · Route 53: 10 % to the ALB. Automated smoke tests (login, issuing an invoice, a query).
- T+15 min · If SLOs are met (errors below 1 % and p95 below 400 ms): 50 %.
- T+1 h · 100 % on AWS. CronJobs enabled on EKS. On-premises stays in hot standby.
- T+7 d · End of hypercare. The rollback window closes and reverse replication is disabled.
- T+30 d · Final on-premises backup archived; cluster retired.
16.4 Blue/Green and Canary inside EKS
After cutover, regular deployments use the same techniques at the application level:
- Blue/Green: two complete versions, and the ALB switches target group. With the AWS LBC this can be done with weighted target groups in the Ingress action (
alb.ingress.kubernetes.io/actions.*). - Canary: Argo Rollouts or Flagger shift traffic in steps (5 %, 25 %, 50 %…) and analyze metrics (Prometheus/AMP, CloudWatch) to promote or roll back the version automatically.
16.5 Rollback plan
| Trigger | Action | Expected time |
|---|---|---|
| 5xx errors above 5 % for 5 min after a traffic step | Route 53: 100 % weight on-premises | 1-2 min + TTL |
| Data inconsistency detected | Stop writes on AWS; reverse replication caught up; writer = on-premises | 15-30 min |
| RDS performance degradation | Scale the instance (Multi-AZ minimizes the interruption) or go back on-premises | 10-30 min |
| Platform component failure (DNS, LBC, IAM) | Route 53 → on-premises while it is fixed | 1-2 min + TTL |
Rule: a single person (the cutover lead) makes the rollback decision, based on criteria written before cutover day, not under pressure in the middle of it.
16.6 Production checklist
- Images in ECR verified by digest; scanning with no open critical vulnerabilities.
- Every manifest in Git; Argo CD
SyncedandHealthyfor every application. - PDBs (
PodDisruptionBudget) and HPAs configured for critical services. - Replicas spread across 3 AZs (
topologySpreadConstraints). - RDS Multi-AZ, automated backups and PITR verified;
deletion_protectionenabled. - Secrets in Secrets Manager; old credentials rotated.
- ACM certificate issued and attached; TLS 1.2+ on the ALB.
- Vendor allowlists updated with the NAT Gateway IPs.
- Cutover alarms and dashboards active; on-call informed.
- DNS TTL at 60 s; weighted records prepared and tested in staging.
- Runbook rehearsed, with measured timings and a tested rollback.
- Full Velero backup of the on-premises cluster state before cutover.
- Communication sent to users and customers.
17. Post-migration validation
“It works” is not a criterion. The migration is successful when there is evidence that the functional and non-functional requirements are met.
| Validation | What to prove | Tools and commands |
|---|---|---|
| Functional | Business flows work end to end | Smoke tests and E2E suites (Playwright, Postman/Newman) against app.acme.com |
| Infrastructure | Every component is healthy and in place | kubectl get nodes,pods -A, argocd app list, aws eks describe-cluster, Terraform with no drift (empty terraform plan) |
| Data | Same data as the source at cutover time | Counts and checksums (11.8), DMS validation if used, business reconciliation (daily invoiced totals) |
| Performance | Latencies equal to or better than on-premises | Compare ALB and trace p50/p95/p99 with the assessment baseline |
| Load | Handles the month-end peak with headroom | k6 or Locust simulating 4× normal traffic; verify that Karpenter and the HPA react |
| Resilience | Tolerates losing pods, nodes and an AZ | AWS Fault Injection Service (actions on EKS pods and EC2 instances), Chaos Mesh, RDS failover (aws rds reboot-db-instance --force-failover) |
| Security | No undue exposure or excessive permissions | Security Hub, Inspector and GuardDuty findings; kube-bench (CIS); review of Access Entries and SGs |
| Backups | You can restore, not just back up | Point-in-time RDS restore into a new instance; Velero restore into a test cluster |
| High availability | No single points of failure | Replicas per AZ (kubectl get pods -o wide), NAT per AZ, RDS Multi-AZ, ElastiCache with a replica |
| Observability | What happens is visible and alerts | Fire a test alert; confirm logs, metrics and traces for a specific request |
| DR | You can recover in another Region if the RTO requires it | Documented exercise: snapshots copied across Regions, cluster recreated with Terraform, restore |
# Example k6 load test (month-end peak scenario)
k6 run --vus 400 --duration 15m tests/load/month-end.js
# During the test: watch the scaling
kubectl get hpa -n acme-backend -w
kubectl get nodeclaims -w # nodes created by Karpenter
# Controlled RDS failover (in an agreed window)
aws rds reboot-db-instance --db-instance-identifier acme-prod --force-failover
References
18. Optimization and FinOps
Migrating does not save money by itself. Savings come when you pay only for what you use, and that requires continuously measuring, allocating and adjusting.
18.1 What drives EKS cost
- Compute (EC2): usually 50 to 70 % of the bill. It depends on right-sizing the
requests, the instance type, Spot and commitments (Savings Plans). - Network: NAT Gateway (per hour and per GB), cross-AZ traffic, Internet egress and interface VPC endpoints.
- Managed data services: RDS (instance, Multi-AZ and storage), ElastiCache, EFS (per GB stored) and EBS.
- Observability: CloudWatch Logs ingestion, custom metrics and AMP samples.
- Control plane: fixed per cluster. It is multiplied by 6 if the version enters extended support.
18.2 Monthly estimate for ACME (example)
| Component | Assumption | Approx. USD/month |
|---|---|---|
| EKS control plane | 1 cluster, standard support | 73 |
| System node group | 3 × m7i.large on-demand (USD 0.1008/h) | 220 |
| Application nodes (Karpenter) | ~6 × m7i.xlarge equivalents (USD 0.2016/h on-demand), 50 % Spot | 600 |
| NAT Gateway | 3 × USD 0.045/h + 300 GB × USD 0.045/GB | 115 |
| ALB | 1 ALB + moderate LCUs | 35 |
| Interface VPC endpoints | 5 endpoints × 3 AZs × USD 0.01/h | 110 |
| RDS PostgreSQL | db.m7g.large Multi-AZ (USD 0.337/h) + 200 GB gp3 + backups | 300 |
| ElastiCache (Valkey) | 2 cache.m7g.large nodes (USD 0.1264/h) | 185 |
| EBS + EFS | 300 GB gp3 + 50 GB EFS | 40 |
| S3 (Velero backups, artifacts) | 1 TB Standard | 25 |
| CloudWatch (logs + Container Insights) | 150 GB/month ingested, 30-day retention | 120 |
| AMP + Managed Grafana | Metrics for 1 cluster + 5 editors | 120 |
| Site-to-Site VPN | 1 connection (while the migration lasts) | 40 |
| Approximate total | ≈ 2,000 |
The percentages matter more than the total: application compute, RDS and networking account for most of it, and that is where optimization should focus.
18.3 Optimization levers
- Pod right-sizing. Set
requeststo the real p95 (chapter 4.3). The Vertical Pod Autoscaler inOffmode (recommendations only) is a good, risk-free data source. - Horizontal Pod Autoscaler to follow demand, combined with Karpenter so nodes also follow demand and consolidate onto cheaper instances.
- Spot Instances for interruption-tolerant workloads (stateless replicas with a PDB). Karpenter diversifies instance types and handles interruption notices through the SQS queue. Typical savings of up to 70-90 % versus on-demand, depending on the type and Region.
- Graviton (arm64): better price/performance if images are multi-architecture. Add
arm64to the NodePool once the pipeline builds both platforms. - Compute Savings Plans: a USD/hour commitment for 1 or 3 years that applies to EC2 (any family or Region), Fargate and Lambda. Buy only on top of the stable baseline Cost Explorer shows after 1 or 2 months of operation, not before.
- Reserved Instances: they make sense for RDS and ElastiCache (Compute Savings Plans do not cover these services), once the instance size has stabilized.
- EBS and EFS: gp3 instead of gp2 (cheaper, with higher baseline performance), delete orphaned volumes and snapshots, and use EFS lifecycle management (Infrequent Access) for cold files.
- NAT Gateway: the S3 Gateway VPC endpoint (free) and interface endpoints for ECR, STS, Logs and Secrets Manager. Use VPC Flow Logs to see which destinations generate the most traffic.
- Log control: appropriate levels, Fluent Bit filters, per-group retention and export to S3 for long-term auditing.
- Kubernetes versions: plan upgrades so you never fall into extended support.
- Shutting down non-production: scale dev and staging to zero outside working hours (Karpenter removes the empty nodes).
18.4 Visibility: Cost Explorer, Budgets and cost allocation
# Monthly budget with alerts at 80 % actual and 100 % forecasted
aws budgets create-budget --account-id 111122223333 \
--budget '{"BudgetName":"acme-prod-monthly","BudgetLimit":{"Amount":"2300","Unit":"USD"},"TimeUnit":"MONTHLY","BudgetType":"COST"}' \
--notifications-with-subscribers '[
{"Notification":{"NotificationType":"ACTUAL","ComparisonOperator":"GREATER_THAN","Threshold":80},
"Subscribers":[{"SubscriptionType":"EMAIL","Address":"finops@acme.example"}]},
{"Notification":{"NotificationType":"FORECASTED","ComparisonOperator":"GREATER_THAN","Threshold":100},
"Subscribers":[{"SubscriptionType":"EMAIL","Address":"finops@acme.example"}]}]'
- Cost Allocation Tags: activate the
Project,Environment,TeamandCostCentertags in Billing (Terraform’sdefault_tagsapplies them) to filter Cost Explorer by team. - Split cost allocation data for EKS: splits the cost of EC2 instances across pods based on their consumption, at the namespace and label level, in the Cost and Usage Report.
- OpenCost / Kubecost: cost visibility per namespace, deployment and label inside the cluster.
References
- AWS Pricing Calculator · Amazon EKS pricing · Savings Plans
- EKS Best Practices — Cost Optimization
- Cost allocation tags · OpenCost
19. Troubleshooting
Every problem follows the same structure: symptoms → causes → diagnosis → fix → prevention.
19.1 Pods stuck in Pending
- Symptoms:
kubectl get podsshowsPendingfor minutes. - Causes: no capacity (CPU/memory), the Karpenter NodePool does not admit the pod’s requirements (architecture, zone, taints), an unbound PVC, or
topologySpreadConstraintsthat cannot be satisfied. - Diagnosis:
kubectl describe pod POD -n NS | sed -n '/Events/,$p' # "0/5 nodes are available: ..."
kubectl logs -n kube-system deploy/karpenter | grep -iE 'could not schedule|incompatible'
kubectl get nodepools,nodeclaims
- Fix: adjust the
requests, widen the NodePool requirements, and check the NodePoollimitsand the EC2 vCPU quota in Service Quotas. - Prevention: realistic requests, flexible NodePools (several instance families) and alarms on Pending pods.
19.2 ImagePullBackOff
- Symptoms:
ErrImagePull/ImagePullBackOff. - Causes: the image or tag does not exist in ECR, the node role lacks ECR read permissions, there is no route to ECR (missing NAT or the
ecr.apiandecr.dkrVPC endpoints and the S3 Gateway endpoint, where the layers live), or a manifest still points toharbor.acme.local. - Diagnosis:
kubectl describe pod POD -n NS | grep -A3 -i 'failed'
aws ecr describe-images --repository-name acme/backend --image-ids imageTag=1.8.2
# From a node (via SSM Session Manager):
# sudo crictl pull 111122223333.dkr.ecr.us-east-1.amazonaws.com/acme/backend:1.8.2
- Fix: copy the image, fix the reference or add
AmazonEC2ContainerRegistryReadOnly(or the PullOnly policy) to the node role; create any missing endpoints. - Prevention: validate in CI that every image in the manifests exists in ECR (
crane digest) before merging.
19.3 CrashLoopBackOff
- Symptoms: the container starts and dies repeatedly.
- Typical causes in migrations: missing variables or secrets (the ExternalSecret did not sync), connection refused by RDS (SG or mandatory TLS), an unresolvable
*.acme.localhostname, or OOMKilled because of differentlimits. - Diagnosis:
kubectl logs POD -n NS --previous
kubectl describe pod POD -n NS | grep -iE 'reason|exit code|oomkilled'
kubectl get externalsecret -n NS # STATUS / READY column
- Fix: depends on the cause (secret, SG,
sslmode, DNS, memory). - Prevention: readiness and startup probes,
ExternalSecretvalidation in the pipeline and staging tests with the same configuration.
19.4 PVC Pending and StorageClass incompatibility
- Symptoms: PVC
Pending; pods inContainerCreating. - Causes: the StorageClass does not exist (
ceph-rbdon EKS), the EBS CSI driver has no IAM permissions,volumeBindingMode: WaitForFirstConsumer(normal until the pod is scheduled), or RWX requested from EBS (which only supports RWO). - Diagnosis:
kubectl describe pvc PVC -n NS
kubectl get storageclass
kubectl logs -n kube-system deploy/ebs-csi-controller -c csi-provisioner | tail -50
- Fix: map the StorageClass (Kustomize or Velero ConfigMap), fix the driver’s Pod Identity association and use
efs-scfor RWX. - Prevention: a default StorageClass (
gp3) and a provisioning test when the cluster is created.
19.5 IAM permission errors
- Symptoms:
AccessDenied,is not authorized to performorNoCredentialProvidersin the logs of an application or controller. - Causes: the Pod Identity association does not exist, the ServiceAccount or namespace name does not match, the policy is insufficient, or the pod started before the association was created.
- Diagnosis:
aws eks list-pod-identity-associations --cluster-name acme-prod --namespace NS
kubectl exec -n NS POD -- env | grep -E 'AWS_CONTAINER_CREDENTIALS_FULL_URI|AWS_ROLE_ARN'
kubectl exec -n NS POD -- aws sts get-caller-identity # if the image includes the AWS CLI
# CloudTrail: look up the denied event to find the exact action and resource
- Fix: create or fix the association, extend the policy with the specific permission and restart the pod (credentials are injected at startup).
- Prevention: associations in Terraform next to the application; IAM Access Analyzer to validate policies.
19.6 Amazon VPC CNI problems
- Symptoms: pods in
ContainerCreatingwithfailed to assign an IP address to container; nodes with many “stuck” pods. - Causes: the subnet has no free IPs, the instance type’s ENI/IP limit has been reached, or prefix delegation lacks contiguous
/28space. - Diagnosis:
kubectl logs -n kube-system -l k8s-app=aws-node -c aws-node --tail=100 | grep -i error
aws ec2 describe-subnets --subnet-ids subnet-0aaa \
--query 'Subnets[].{id:SubnetId,free:AvailableIpAddressCount}'
- Fix: larger subnets or a secondary CIDR with custom networking, enable prefix delegation, or use larger instances.
- Prevention: IP planning in the VPC design (chapter 6) and alarms on available IPs per subnet.
19.7 DNS problems
- Symptoms:
UnknownHostException, intermittent resolution timeouts. - Causes: the Route 53 Resolver rule for
acme.localis missing, CoreDNS is saturated or has too few replicas,ndots:5generates extra queries, or per-ENI DNS packet limits are hit. - Diagnosis:
kubectl run -it --rm dnsutils --image=registry.k8s.io/e2e-test-images/agnhost:2.39 --restart=Never -- \
nslookup ldap.acme.local
kubectl logs -n kube-system -l k8s-app=kube-dns --tail=50
aws route53resolver list-resolver-rules --query "ResolverRules[].{name:Name,domain:DomainName,type:RuleType}"
- Fix: add the forwarding rule and its VPC association, scale CoreDNS, and use fully qualified names with a trailing dot in critical configuration, or NodeLocal DNSCache.
- Prevention: test resolution of every external hostname found in the assessment before cutover.
19.8 Ingress not responding
- Symptoms: the Ingress has no
ADDRESS, or the ALB returns 502/503/504. - Causes: subnets without the
kubernetes.io/role/elbtags, the LBC lacks permissions, a wrongingressClassName, unhealthy targets (a health check against a path that returns 404), or node/pod SGs that do not allow traffic from the ALB. - Diagnosis:
kubectl describe ingress web -n acme-frontend # controller events
kubectl logs -n kube-system deploy/aws-load-balancer-controller | grep -i error
aws elbv2 describe-target-health --target-group-arn arn:aws:elasticloadbalancing:...
- Fix: depends on the cause (tags, IAM, class,
healthcheck-path, SG rules). - Prevention: a test (“hello”) Ingress created as part of cluster bootstrap.
19.9 Connectivity errors between microservices
- Symptoms: timeouts between services that used to work.
- Causes: default-deny NetworkPolicies without allow rules, a service that stayed on-premises (VPN latency or a missing firewall rule), misconfigured Security Groups for Pods, or a different Service name at the target.
- Diagnosis:
kubectl get networkpolicy -n NS
kubectl run -it --rm netcheck --image=nicolaka/netshoot --restart=Never -n NS -- \
sh -c 'nc -vz backend.acme-backend.svc.cluster.local 8080; curl -sS -m 5 http://backend.acme-backend:8080/actuator/health'
- Fix: add the required NetworkPolicy or SG rules, and migrate services that call each other frequently together (dependency-based waves).
- Prevention: the assessment’s dependency map turned into explicit NetworkPolicies, with automated connectivity tests.
19.10 CRD problems
- Symptoms:
no matches for kind "X" in version "Y"when applying or restoring. - Causes: the operator is not installed at the target, a version was installed whose CRD no longer serves that
apiVersion, or the apply order is wrong. - Diagnosis:
kubectl api-resources | grep -i Xandkubectl get crd X -o jsonpath='{.spec.versions[*].name}'. - Fix: install the operator in a version that serves the required API, or convert the resources to the new version; apply CRDs before their resources (in Argo CD, sync waves).
- Prevention: a CRD inventory with versions (chapter 4.6) and a compatibility matrix per operator.
19.11 Velero restore errors
See section 10.4. The three most frequent ones are an unmapped StorageClass, the node-agent not running on the restored pod’s node, and existing objects that Velero does not overwrite.
19.12 Data consistency problems
- Symptoms: different row counts, duplicate key errors after cutover (
duplicate key value violates unique constraint) or “lost” records. - Causes: unsynced sequences (the most common cause of duplicates), writes at the source after the cutoff, tables without a primary key that did not replicate UPDATE/DELETE, or DDL applied on one side only.
- Diagnosis: the validation queries from 11.8,
pg_stat_subscription, comparing sequencelast_values, and reviewingpg_stat_activityat the source at cutoff time. - Fix:
setvalon the sequences, reconcile the diverging records from the application logs and, if the scope is large, execute the rollback. - Prevention: a cutover checklist with verified write blocking, sequences in the runbook and a full rehearsal in staging.
References
20. End-to-end case study: ACME Technologies
This lab brings all the chapters together in the order they would run in the real project. Each step points to the chapter with the details so they are not repeated.
20.1 Final architecture
This layered view complements Figure 2, which shows the network: here you see every service that runs the platform once the migration is done.
20.2 Sample repository
kubernetes-cloud-migration/
├── README.md
├── docs/
│ ├── architecture/ # diagrams (Mermaid sources and exports) and ADRs
│ ├── assessment/ # inventory script outputs and the app matrix
│ ├── migration-plan/ # waves, RTO/RPO, owners
│ └── runbooks/ # cutover.md, rollback.md, dr.md
├── on-premise/
│ ├── manifests/ # clean export of the source cluster (starting point)
│ ├── helm/ # values used on-premises
│ └── backup/ # Velero scripts at the source
├── terraform/
│ ├── modules/ # in-house modules (e.g. app-iam with Pod Identity)
│ ├── vpc/ # VPC, endpoints, VPN, DNS (chapter 6)
│ ├── eks/ # cluster, add-ons, Karpenter, identities (chapter 7)
│ ├── data/ # RDS, ElastiCache, EFS, KMS (chapter 11)
│ └── cicd/ # GitHub OIDC, ECR roles (chapter 15)
├── migration/
│ ├── registry/ # migrate-images.sh, images.txt (chapter 8)
│ ├── velero/ # installation, mapping ConfigMaps and modifiers (chapter 10)
│ ├── storage/ # DataSync tasks, copy jobs through S3
│ ├── databases/ # publication/subscription SQL, validation, sequences
│ └── networking/ # DNS and connectivity tests
├── workloads/
│ ├── frontend/ # base + overlays (onprem, eks-staging, eks-prod)
│ ├── backend/
│ └── redis/ # on-prem overlay only (AWS uses ElastiCache)
├── platform/
│ ├── storage/ # gp3 and efs-sc StorageClasses
│ ├── karpenter/ # NodePools and EC2NodeClass
│ └── external-secrets/ # ClusterSecretStore
├── gitops/
│ └── argocd/
│ ├── root-app.yaml # app of apps
│ ├── projects/
│ └── apps/
├── observability/ # Prometheus agent values, alert rules, dashboard JSON
└── scripts/ # inventory, validation and utilities
20.3 Main files
README.md (excerpt):
# ACME — Migrating on-premises Kubernetes to Amazon EKS
## Execution order
1. `terraform/vpc` → `terraform/eks` → `terraform/data` → `terraform/cicd`
2. `kubectl apply -k platform/` (StorageClasses, NodePools, SecretStore)
3. `kubectl apply -f gitops/argocd/root-app.yaml` (Argo CD deploys the rest)
4. `migration/registry/migrate-images.sh migration/registry/images.txt`
5. Data rehearsal: `migration/databases/README.md`
6. Cutover: `docs/runbooks/cutover.md`
## Requirements
AWS CLI v2, kubectl, Helm 3, Terraform >= 1.10, crane, velero, psql 16
gitops/argocd/root-app.yaml: the root application that creates all the others.
apiVersion: argoproj.io/v1alpha1
kind: Application
metadata:
name: root
namespace: argocd
spec:
project: default
source:
repoURL: https://github.com/acme/kubernetes-cloud-migration.git
targetRevision: main
path: gitops/argocd/apps
destination:
server: https://kubernetes.default.svc
namespace: argocd
syncPolicy:
automated: { prune: true, selfHeal: true }
terraform/modules/app-iam/main.tf: a reusable per-application role with Pod Identity.
variable "cluster_name" { type = string }
variable "app" { type = string }
variable "namespace" { type = string }
variable "service_account" { type = string }
variable "policy_json" { type = string }
data "aws_iam_policy_document" "trust" {
statement {
actions = ["sts:AssumeRole", "sts:TagSession"]
principals {
type = "Service"
identifiers = ["pods.eks.amazonaws.com"]
}
}
}
resource "aws_iam_role" "this" {
name = "${var.cluster_name}-${var.app}"
assume_role_policy = data.aws_iam_policy_document.trust.json
}
resource "aws_iam_role_policy" "this" {
role = aws_iam_role.this.id
policy = var.policy_json
}
resource "aws_eks_pod_identity_association" "this" {
cluster_name = var.cluster_name
namespace = var.namespace
service_account = var.service_account
role_arn = aws_iam_role.this.arn
}
output "role_arn" { value = aws_iam_role.this.arn }
# terraform/eks/apps.tf — the backend can only read and write its own S3 prefix.
# (External Secrets reads its secrets with its own role, not the application.)
module "backend_iam" {
source = "../modules/app-iam"
cluster_name = module.eks.cluster_name
app = "backend"
namespace = "acme-backend"
service_account = "backend"
policy_json = jsonencode({
Version = "2012-10-17"
Statement = [{
Effect = "Allow"
Action = ["s3:GetObject", "s3:PutObject"]
Resource = "arn:aws:s3:::acme-prod-documents/invoices/*"
}]
})
}
scripts/validate-db.sh: compares row counts of every table between source and target.
#!/usr/bin/env bash
# Usage: SRC="host=postgresql.acme.local dbname=acme user=auditor" DST="host=acme-prod...rds.amazonaws.com dbname=acme user=auditor" ./validate-db.sh
set -euo pipefail
query="SELECT schemaname||'.'||relname FROM pg_stat_user_tables ORDER BY 1"
fail=0
for t in $(psql "$SRC" -Atc "$query"); do
s=$(psql "$SRC" -Atc "SELECT count(*) FROM $t")
d=$(psql "$DST" -Atc "SELECT count(*) FROM $t")
if [[ "$s" == "$d" ]]; then printf 'OK %-40s %s\n' "$t" "$s"
else printf 'DIFF %-40s source=%s target=%s\n' "$t" "$s" "$d"; fail=1; fi
done
exit $fail
docs/runbooks/cutover.md (structure): numbered steps with owner, planned time, exact command, expected check and rollback criterion, following the sequence in section 16.3.
20.4 Step-by-step execution
| # | Stage | Key actions | Exit evidence |
|---|---|---|---|
| 1 | Inventory | Scripts from 4.2-4.7 against the source cluster | docs/assessment/*.csv, Pluto and kubent reports |
| 2 | Assessment | App matrix, per-app strategy (6R) and waves | Approved docs/assessment/matrix.md |
| 3 | Terraform | vpc → eks → data → cicd | terraform plan with no pending changes |
| 4 | EKS | Add-ons, LBC, Karpenter, External Secrets, Argo CD | Healthy kubectl get pods -A; “hello” Ingress responds |
| 5 | ECR | migrate-images.sh | Every digest verified (OK) |
| 6 | Velero | Rehearsal backup of acme-reports and restore on EKS | Restore Completed; matching file counts and checksums |
| 7 | Data migration | Logical subscription to RDS; DataSync to EFS | srsubstate = r on every table; steady lag |
| 8 | Networking | VPN, Resolver, NetworkPolicies, ALB Ingress | DNS and connectivity tests from 19.7 and 19.9 green |
| 9 | Security | Pod Security restricted, Pod Identity, Inspector, GuardDuty | No open critical findings in Security Hub |
| 10 | CI/CD | GitHub Actions pipeline + OIDC | A commit on main deploys to staging with no intervention |
| 11 | GitOps | Argo CD root app | Every app Synced/Healthy |
| 12 | Cutover | Chapter 16 runbook | 100 % of traffic on AWS; write downtime measured |
| 13 | Validation | Chapter 17 matrix | Signed-off validation report |
| 14 | Optimization | Right-sizing, Spot, Savings Plans after 60 days | Monthly cost against the 18.2 estimate |
20.5 Expected results
At project close, ACME should be able to demonstrate:
- Write downtime of about 10 minutes (the final sync window), with no data loss, verified by checksums.
- Multi-AZ availability tested with FIS (losing an AZ’s nodes with no user impact).
- Deployments that take minutes and are auditable in Git, with no cluster credentials in CI.
- Operations: Kubernetes upgrades planned quarterly, with no Ceph or etcd patching.
- Cost within budget, with per-team visibility and a commitment plan (Savings Plans) based on real data.
21. Tool comparison
AWS managed services
| Name | Purpose | Phase | Alternatives | Pros | Limitations | Cost | Documentation |
|---|---|---|---|---|---|---|---|
| Amazon EKS | Managed Kubernetes | Build / Operate | Self-managed Kubernetes, ECS | Upstream Kubernetes, IAM/VPC integration | Mandatory version cycle | Per cluster-hour + resources | Docs |
| Amazon ECR | Image registry | Images | Harbor, GHCR, Docker Hub | IAM, KMS, Inspector, replication | Per Region and account (use replication) | Per GB stored + data transfer | Docs |
| Amazon RDS for PostgreSQL | Managed database | Data | Aurora PostgreSQL, PostgreSQL on EKS | HA, PITR, patching | No superuser; limited extensions | Per instance-hour + storage | Docs |
| AWS DMS | Database migration with CDC | Data | Native replication, pglogical | Managed, validation | Does not migrate every schema object | Per replication instance-hour or DCU (Serverless) | Docs |
| AWS DataSync | File transfer | Data | rsync, rclone | Incremental, verification, encryption | Requires an on-premises agent | Per GB transferred | Docs |
| Amazon ElastiCache | Managed cache (Valkey/Redis OSS) | Data | Redis on EKS | Failover, no operations | Restrictions on administrative commands | Per node-hour or serverless | Docs |
| AWS Load Balancer Controller + ELB | ALB/NLB from Kubernetes | Networking | NGINX (F5), Traefik, Envoy Gateway | Managed, ACM, WAF, target-type: ip | Less rewrite flexibility than a proxy | ALB/NLB per hour + LCU | Docs |
| Amazon Managed Service for Prometheus | Metrics storage | Observability | Self-managed Prometheus/Thanos/Mimir | No operations, PromQL-compatible | Per-sample cost at high cardinality | Per samples ingested and queried | Docs |
| Amazon CloudWatch | Logs, metrics, Container Insights | Observability | Loki, OpenSearch, ELK | Native integration | Log ingestion cost | Per GB ingested and stored | Docs |
| Amazon Inspector / GuardDuty / Security Hub | Vulnerabilities, detection, posture | Security | Trivy, Falco, CNAPP tools | Managed, multi-account | Cost per resource scanned/analyzed | Usage-based | Inspector |
Open source tools
| Name | Purpose | Phase | Alternatives | Pros | Limitations | License | Documentation |
|---|---|---|---|---|---|---|---|
| Terraform | Infrastructure as code | Landing Zone / Build | OpenTofu, AWS CDK, CloudFormation | Module ecosystem, multi-provider | State to manage; BSL license since 1.6 | BSL 1.1 (OpenTofu: MPL 2.0) | Docs |
| eksctl | EKS cluster creation | Build (labs) | Terraform, console | Very fast | Does not manage the rest of the infrastructure | Apache 2.0 | Docs |
| Velero | K8s backup/restore/migration | Migration / DR | Kasten K10 (commercial), Trilio | Portable, FSB and data mover | Does not migrate live databases consistently | Apache 2.0 | Docs |
| crane / skopeo | Copying images between registries | Images | regctl, Harbor replication | Preserves manifest lists and digests | CLI (needs orchestration) | Apache 2.0 | crane · skopeo |
| Helm | Application packaging | Resources / CI/CD | Kustomize, Jsonnet | De facto standard for third-party apps | Complex templates | Apache 2.0 | Docs |
| Kustomize | Manifest variants | Resources / CI/CD | Helm | No templates, built into kubectl | Less expressive for logic | Apache 2.0 | Docs |
| Argo CD | GitOps | CI/CD | Flux CD | UI, multi-cluster, drift detection | One more component to operate | Apache 2.0 | Docs |
| Karpenter | Node provisioning | Build / FinOps | Cluster Autoscaler, EKS Auto Mode | Fast, Spot, consolidation | Learning curve | Apache 2.0 | Docs |
| External Secrets Operator | Secret syncing | Security | Secrets Store CSI Driver (ASCP) | Many providers; environment variables | Secrets exist as Secret objects | Apache 2.0 | Docs |
| Pluto / kubent | Deprecated API detection | Assessment | EKS upgrade insights | Fast and accurate | They only detect; they do not fix | Apache 2.0 / MIT | Pluto · kubent |
| Trivy | Vulnerability and IaC scanning | Security / CI | Grype, Inspector | All-in-one, fast | Vulnerability database must be kept updated | Apache 2.0 | Docs |
| Falco | Runtime security | Security | GuardDuty Runtime Monitoring | Customizable rules | Noise tuning | Apache 2.0 | Docs |
| OpenTelemetry / Fluent Bit | Telemetry and logs | Observability | Proprietary agents | Open standard | Detailed configuration | Apache 2.0 | OTel · Fluent Bit |
22. Conclusions
Migrating on-premises Kubernetes to Amazon EKS is not a container project but a platform and data project. Containers are the portable part. The real work lies in replacing, with judgment, every piece that depended on the datacenter, and in moving state without losing it.
The lessons that repeat in every project are:
- The assessment defines success. Surprises at cutover are dependencies that were never inventoried.
- Replatform the data during the migration and refactor the applications afterwards. Moving PostgreSQL to RDS saves migrating the data twice; rewriting the backend at the same time multiplies the risk.
- No single tool migrates everything. Velero, DMS, DataSync and crane solve different parts, and all of them need configuration, mappings and validation.
- GitOps makes the migration repeatable. If the desired state lives in Git, migrating the next application or recreating the cluster in another Region takes hours.
- Security and identity are designed from day one: Pod Identity, Access Entries, secrets outside the cluster and audit logs.
- Cost is an operational metric, not a quarterly report: tags, budgets, right-sizing and an explicit Kubernetes version policy.
- Every cutover needs a rehearsed rollback. If it was never tested, it does not exist.
With these foundations, ACME’s team goes from operating servers to operating a platform, and can spend its time on what sets the company apart: its product.
Glossary
| Term | Definition |
|---|---|
| Access Entry | An EKS record that links an IAM identity to Kubernetes permissions, without the aws-auth ConfigMap |
| ALB / NLB | Application Load Balancer (layer 7, HTTP/HTTPS) / Network Load Balancer (layer 4, TCP/UDP/TLS) |
| AZ | Availability Zone: one or more isolated datacenters within an AWS Region |
| CDC | Change Data Capture: continuous capture and replication of a database’s changes |
| CNI | Container Network Interface: the plugin that provides pod networking (Calico, VPC CNI, Cilium) |
| CRD | Custom Resource Definition: an extension of the Kubernetes API with new object types |
| CSI | Container Storage Interface: the standard for storage drivers (EBS CSI, EFS CSI) |
| Cutover | The moment the target system becomes the production system |
| Digest | SHA-256 hash that immutably identifies an image’s content |
| FSB | Velero File System Backup: file-level copy of pod volumes |
| GitOps | Operating model in which Git is the source of truth and an agent reconciles the cluster with it |
| IRSA | IAM Roles for Service Accounts: IAM credentials for pods through OIDC |
| Karpenter | Node provisioner that launches EC2 instances based on pending pods |
| Landing Zone | Secure, governed multi-account AWS environment where workloads are deployed |
| Manifest list | Image index that groups variants per architecture (amd64, arm64) |
| Multi-AZ | Redundant deployment across several Availability Zones |
| NAT Gateway | Service that enables outbound Internet traffic from private subnets |
| Pod Identity | EKS mechanism to associate an IAM role with a ServiceAccount |
| PV / PVC | PersistentVolume (the volume) / PersistentVolumeClaim (a pod’s request) |
| RPO / RTO | Recovery Point Objective (data that can be lost) / Recovery Time Objective (time to recover) |
| SCP | Service Control Policy: a permission boundary enforced by AWS Organizations |
| StorageClass | Template for dynamic volume provisioning |
| VPC endpoint | Private connection from the VPC to an AWS service without going over the Internet |
| Wave | A group of applications migrated together |
Official references
AWS
- Amazon EKS User Guide
- Amazon EKS Best Practices Guide
- AWS Prescriptive Guidance
- AWS Well-Architected Framework
- AWS Database Migration Service
- AWS DataSync
- Amazon ECR
- AWS Load Balancer Controller
- Karpenter
Kubernetes and CNCF
- Kubernetes Documentation
- Deprecated API Migration Guide
- Velero · velero-plugin-for-aws
- Helm · Kustomize
- Argo CD · Flux
- OpenTelemetry
Infrastructure as code
- Terraform Documentation
- terraform-aws-modules/eks · terraform-aws-modules/vpc
- terraform-aws-modules (GitHub)
Databases