es en de
aws kubernetes amazon-eks cloud-migration terraform velero gitops

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.

Juan Manuel Hoyos Contreras 88 min read
Kubernetes
Amazon EKS
Amazon ECR
Amazon VPC
Amazon RDS
ElastiCache
Amazon EFS
AWS DMS
Terraform
Argo CD

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:

DecisionChoice for ACMEReason
Container platformAmazon EKS with Managed Node Groups + KarpenterManaged control plane and efficient node scaling
DatabaseAmazon RDS for PostgreSQL Multi-AZ (replatform)Removes the burden of running backups, HA and patching for a critical StatefulSet
CacheAmazon ElastiCache (Valkey or Redis OSS)Redis is used as a cache: it is rebuilt, not migrated
IngressAWS Load Balancer Controller + ALBingress-nginx was retired by the Kubernetes community
Manifest migrationHelm/Kustomize in Git + Argo CD, with Velero as a safety netReproducibility, auditability and rollback
Data migrationPostgreSQL logical replication (or AWS DMS) with a cutover of minutesMinimal, verifiable downtime
Pod identityEKS Pod IdentityTemporary credentials per ServiceAccount, no access keys
ObservabilityPrometheus → Amazon Managed Service for Prometheus + Grafana, logs in CloudWatchKeeps 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) and kube-controller-manager (the reconciliation loops).
  • Worker nodes: run kubelet (the node agent), a container runtime such as containerd, and kube-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 kubeconfig stored in a CI variable.

1.4 Self-managed Kubernetes vs. managed Kubernetes

AspectSelf-managed (on-premises kubeadm)Managed (Amazon EKS)
Control planeYou install, scale, back up and upgrade itAWS runs it across several AZs with an SLA
etcdYou handle backup, defragmentation and restoreInvisible to you; AWS manages it
UpgradesManual, node by nodeOne command or a Terraform change for the control plane; nodes with rolling updates
Load balancersMetalLB, F5, HAProxyALB/NLB via the AWS Load Balancer Controller
StorageCeph, NFS, Longhorn: you operate the storageManaged EBS, EFS, S3
IdentityCertificates, tokens, LDAPIAM + Access Entries + Pod Identity
CostCAPEX (hardware) + peopleOPEX: cluster fee + consumed resources
ControlFull (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

BenefitsRisksLimitationsCosts to watch
Managed, multi-AZ control planeDowntime or data loss during cutoverSome apiserver flags are not configurablePer-cluster fee (higher in extended support)
Node scaling in minutesUnexpected bill (NAT, logs, data transfer)Pod IPs consume VPC addressesNAT Gateway: per hour and per GB processed
Managed services for dataOverly permissive IAM configurationsEBS volumes are bound to one AZCross-AZ and Internet data transfer
Built-in security (KMS, GuardDuty, IAM)Vendor lock-inService quotas (ENIs, IPs, LBs)CloudWatch Logs (ingestion)
Reproducible infrastructure as codeTeam learning curveKubernetes versions have a fixed support cycleOrphaned volumes and snapshots

1.8 Migrating containers, migrating a cluster or modernizing

These are three different scopes that are often confused:

  1. 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.
  2. 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.
  3. 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

Figure 1 Source architecture: ACME Technologies on-premises Kubernetes cluster
ACME Technologies — On-premises datacenter Kubernetes cluster · kubeadm v1.29 · containerd · Calico Control plane (3 nodes) — stacked etcd cp-01 apiserver · etcd cp-02 apiserver · etcd cp-03 apiserver · etcd Worker nodes (4) — Deployments · StatefulSets · DaemonSets ingress-nginx DaemonSet frontend Deployment ×3 backend Spring Boot ×4 redis StatefulSet postgresql StatefulSet + PVC prometheus kube-prometheus-stack grafana dashboards ConfigMaps / Secrets Secrets in base64 StorageClass: ceph-rbd (RWO, default) · nfs-client (RWX) Users Internet / corp. VPN Firewall + F5 VIP 10.0.0.10 Harbor private registry GitLab CI runners on-prem Ceph RBD / NFS storage DNS + NTP BIND / AD HTTPS scrape pull deploy PVs DNS / NTP

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

ComponentACME implementationRole
Distributionkubeadm v1.29, 3 control plane nodes with stacked etcdCluster installation and lifecycle
Control planecp-01..03 behind an HAProxy VIP (:6443)Highly available Kubernetes API
Worker nodes4 servers (32 vCPU, 128 GiB)Run the application pods
Container runtimecontainerd 1.7Pulls images and runs containers (CRI)
CNICalico (IP-in-IP overlay, pods in 192.168.0.0/16)Pod networking and NetworkPolicies
Deploymentsfrontend (React served by NGINX), backend (Spring Boot)Stateless applications with replicas
StatefulSetspostgresql (14), redis (7)Applications with stable identity and storage
ServicesClusterIP for everything; NodePort for ingressInternal discovery and load balancing
Ingressingress-nginx as a DaemonSet; F5 points to NodePort 30443HTTP(S) entry point, TLS, host-based routing
PV / PVC200 GiB PVC (PostgreSQL), 50 GiB (uploads, RWX)Persistent storage for pods
StorageClassceph-rbd (RWO, default), nfs-client (RWX)Dynamic volume provisioning
RegistryHarbor 2.x at harbor.acme.localStores private images
DatabasePostgreSQL 14 in a StatefulSet, nightly pg_dump backupsTransactional invoicing data
CacheRedis 7 in a StatefulSet, no critical persistenceSessions and query cache
ConfigurationConfigMaps + Secrets (base64, not encrypted in etcd)Parameters and credentials
Observabilitykube-prometheus-stack (Prometheus, Alertmanager, Grafana)Metrics, alerts and dashboards
CI/CDGitLab CI with on-premises runners and kubectl applyBuild and deployment
DNSInternal BIND (*.acme.local)Corporate name resolution

3. Target architecture: AWS

Figure 2 Target architecture on AWS: Amazon EKS in a multi-AZ VPC
AWS Cloud Region us-east-1 VPC acme-prod · 10.20.0.0/16 AZ us-east-1a AZ us-east-1b Public · 10.20.0.0/20 Public · 10.20.16.0/20 Private app · 10.20.48.0/20 Private app · 10.20.64.0/20 Private data · 10.20.96.0/24 Private data · 10.20.97.0/24 Application LB AZ a node NAT Gateway Application LB AZ b node NAT Gateway EC2 node Managed Node Group Pods VPC IPs EC2 node Karpenter Pods VPC IPs RDS PostgreSQL primary ElastiCache primary RDS PostgreSQL standby ElastiCache replica IGW VPC endpoints Site-to-Site VPN Amazon EKS AWS control plane Amazon ECR Secrets Manager Amazon S3 Velero backups CloudWatch Managed Prometheus Users Route 53 app.acme.com ACM ALB TLS ACME DC DNS HTTPS target-type: ip synchronous Multi-AZ replication asynchronous replication private API

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 /20 because 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 with 0.0.0.0/0 → NAT in 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 LoadBalancer Services.
  • 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 componentAWS targetDecisionRationale
kubeadm control planeEKS control planeReplaceRemoves etcd operations and manual upgrades
Physical workersMNG + Karpenter (EC2)ReplaceElasticity and right-sizing
containerdcontainerd (AL2023 / Bottlerocket AMIs)KeepSame runtime; only who manages it changes
Calico (CNI)Amazon VPC CNI (+ native NetworkPolicies)ReplacePods with VPC IPs and integration with SGs and ALB
frontend/backend DeploymentsDeployments on EKSKeepImage, resource and probe adjustments
ingress-nginxAWS Load Balancer Controller + ALBModernizeRetired project; managed ALB with ACM and WAF
F5 / HAProxyALB / NLBReplaceCreated by the controller from manifests
Ceph RBDEBS gp3 via CSIReplaceManaged block storage with snapshots
NFSAmazon EFS via CSIReplaceManaged multi-AZ RWX
HarborAmazon ECRReplaceNo operations, integrated with IAM and Inspector
PostgreSQL StatefulSetAmazon RDS for PostgreSQLModernize (replatform)Managed HA, PITR backups and patching
Redis StatefulSetAmazon ElastiCacheModernizeAutomatic failover and no operations
Secrets (base64)Secrets Manager + External SecretsModernizeKMS encryption, rotation and auditing
kube-prometheus-stackPrometheus agent → AMP + GrafanaModernize (partial)Keeps PromQL and dashboards; removes storage
GitLab CI + kubectl applyCI (GitLab or GitHub Actions) + Argo CDModernizeGitOps: the pipeline no longer has cluster access
Internal BINDRoute 53 (private zones) + ResolverReplace / integrateHybrid 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.

Figure 3 Hybrid architecture during the migration: what moves from on-premises to AWS, and with which tool
ACME DC (source) AWS (target) Users Route 53 weighted routing 90% → 0% 10% → 100% Traffic SQL data Files Images Backups ingress-nginx workloads on-prem Site-to-Site VPN or Direct Connect ALB → Amazon EKS workloads on AWS PostgreSQL 14 StatefulSet Logical replication / DMS full load + CDC Amazon RDS PostgreSQL 16 NFS (RWX) uploads / media AWS DataSync on-prem agent Amazon EFS EFS CSI Driver Harbor private registry crane / Harbor replication copy by digest Amazon ECR immutable tags VEL Velero (on-prem) backup Amazon S3 backup bucket VEL Velero (EKS) restore

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:

  1. 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.
  2. 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.
  3. Gradual, reversible traffic. Route 53 weighted records let you move 1 %, then 10 %, then 100 %, and go back with a weight change.

References

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:

  1. 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.
  2. Real traffic. Use Calico flow logs, service mesh metrics if there is one, or conntrack and tcpdump on the nodes during a representative window.
  3. 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, affinity or tolerations targeting physical node names or labels (kubernetes.io/hostname: worker-03).
  • hostPath or local volumes.
  • MetalLB, F5 (CIS) or ingress-nginx annotations (nginx.ingress.kubernetes.io/*).
  • imagePullSecrets pointing to harbor.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:

AppCriticalityStateDataDependenciesComplexity (1-5)StrategyWave
frontendHighStateless—backend1Rehost1
backendHighStateless—PostgreSQL, Redis, SMTP, DIAN API2Replatform (Pod Identity, secrets)2
postgresqlCriticalStateful180 GiBbackend4Replatform → RDS2
redisMediumCache2 GiB (volatile)backend1Replatform → ElastiCache2
uploads (NFS)MediumFiles40 GiBbackend2Rehost → EFS2
prometheus/grafanaMediumStateful300 GiB TSDBall2Replatform → AMP + Grafana1
report-legacy (CronJob)LowBatch—vendor FTP3Retire (replaced by a new service)—
ldap-syncMediumBatch—on-prem AD2Retain (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

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

StrategyEffortUpfront costRiskCloud benefitSpeed
RehostLowLowLow-mediumLowVery high
ReplatformMediumMediumMediumHighHigh
RefactorHighHighHighVery highLow
RepurchaseMediumVariable (licenses)MediumHighMedium
RetireVery lowNoneLowDirect savingsVery high
RetainNoneNoneLow (short term)None—

5.3 Per-workload decision matrix

For each application, answer in order:

  1. Does anyone use it, and does it create value? If not: Retire.
  2. Does it have a hard constraint that keeps it in the datacenter (latency, regulation, hardware)? If so: Retain.
  3. Is there a SaaS that replaces it at a lower total cost? If so: Repurchase.
  4. Is it stateful, and is there an equivalent managed service (RDS, ElastiCache, MSK, OpenSearch)? If so: Replatform.
  5. 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.
  6. In every other case: Rehost.

5.4 Phases and waves

Figure 4 Phased migration process overview
1 Assess Cluster inventoryDependenciesDeprecated APIsApp matrix Weeks 1–3 2 Plan 6R strategyMigration wavesRTO / RPO per appRollback plan Weeks 3–4 3 Landing Zone Accounts and OUsVPC multi-AZVPN / Direct ConnectIAM · KMS · logs Weeks 3–6 4 Build EKS TerraformNode groupsAdd-onsLB Controller Weeks 5–7 5 Migrate Images → ECRManifests / VeleroData (replication)Testing on EKS Weeks 7–10 6 Cutover FreezeFinal syncRoute 53 weightsRollback ready Week 11 7 Optimize ValidationRight-sizingSavings PlansOn-prem retirement Week 12+

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.

SettingRequiredRecommendedDepends 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 GatewayNeeded with many VPCs or accounts
Direct ConnectDepends 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 /20 subnets for ALB and NAT, private /20 subnets for nodes and pods, and data /24 subnets 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

CriterionSite-to-Site VPNDirect Connect
Time to set upHoursWeeks or months (depends on the partner and the circuit)
BandwidthUp 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)
LatencyVariable (Internet)Stable and low
CostLow (hourly + data transfer)Port + data transfer (cheaper per GB)
EncryptionNative IPsecNot encrypted by default (MACsec or VPN over DX)
Typical migration usePilots, moderate volumes, DX backupLarge 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.local queries 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

7. Building the new Amazon EKS cluster

7.1 Prerequisites and tools

ToolUseCheck
AWS CLI v2Authentication and AWS operationsaws --version
kubectlKubernetes client (±1 minor version of the cluster)kubectl version --client
eksctlQuick cluster creation (labs) and utilitieseksctl version
Terraform ≥ 1.10Infrastructure as codeterraform version
Helm 3Installing controllers and appshelm 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 the aws-auth ConfigMap, 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 = true restricted with endpoint_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 IdentityIRSA (IAM Roles for Service Accounts)
Configurationcluster + namespace + serviceaccount → role association through the EKS APIOIDC provider per cluster + ServiceAccount annotation + trust policy per cluster
Role trust policyGeneric (pods.eks.amazonaws.com), reusable across clustersBound to each cluster’s OIDC issuer
Cluster requirementeks-pod-identity-agent add-onNone (webhook built into EKS)
PortabilityEKS onlyEKS and others (any cluster with OIDC)
RecommendationDefault on EKSWhen 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_DELEGATION it assigns /28 blocks per ENI, which multiplies pod density per node. With enableNetworkPolicy it 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 AutoscalerKarpenter
ModelResizes existing Auto Scaling GroupsCreates EC2 instances directly based on pending pods
Instance typesFixed per node groupPicks from dozens of types (including Spot) on every decision
SpeedMinutes (depends on the ASG)Usually faster (launches the instance directly)
ConsolidationLimited (scale-down of empty or underutilized nodes)Replaces nodes with cheaper ones or removes them
ComplexityLowMedium (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

8. Migrating container images

Figure 5 Container image migration: Harbor → Amazon ECR
On-premises AWS · us-east-1 Harbor harbor.acme.local Migration runner crane copy · skopeo --all Amazon ECR acme/backend:1.8.2 Amazon EKS nodes pull Amazon Inspector enhanced scanning IAM node role: ECR read-only Verification src digest == dst digestimmutable tagsscan on push / continuous Alternative: Harbor → ECR replication rule pull by digest push (manifest list) pull via VPC endpoint

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/_catalog API.
  • 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 IMMUTABLE prevents overwriting an existing tag: 1.8.2 will always point to the same digest. This is essential for reliable rollbacks.
  • encryptionType=KMS encrypts with an AWS managed KMS key, or with a CMK if you add kmsKey=....

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"

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 deploy latest to 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

ResourceMigration treatmentKey difference on EKS
NamespacesRecreated with Pod Security Admission labelspod-security.kubernetes.io/enforce labels
DeploymentsMigrated with image, resource and affinity changesImage in ECR, no imagePullSecrets, zone topologySpreadConstraints
StatefulSetsMigrated only if they stay in the cluster; databases move to RDSstorageClassName: gp3; EBS is zonal
DaemonSetsReview one by one: infrastructure ones (Calico, node-exporter, fluentd) are not migratedReplaced by EKS add-ons or managed observability
ServicesClusterIP unchanged; NodePort and LoadBalancer are redesignedtype: LoadBalancer creates an NLB via the AWS LBC
IngressRewritten from nginx to albalb.ingress.kubernetes.io/* annotations
ConfigMapsMigrated; review on-premises hostnames and IPsRDS and ElastiCache endpoints
SecretsNot copied in plain text: created in Secrets ManagerExternal Secrets Operator syncs them
ServiceAccountsMigrated; Pod Identity associations are addedNo annotations (Pod Identity) or eks.amazonaws.com/role-arn (IRSA)
RBACRoles and Bindings are migrated; groups move to Access EntriesIAM users are mapped to Kubernetes groups with Access Entries
NetworkPoliciesStandard ones are migrated; Calico ones (projectcalico.org) are convertedThe VPC CNI enforces standard NetworkPolicies
JobsCompleted ones are not migrated—
CronJobsMigrated suspended and enabled at cutoverAvoids duplicate runs at source and target
CRDsInstalled with the operator’s chart before their resourcesVersions compatible with Kubernetes 1.37
Custom controllersReinstalled with their chart; review IAM permissionsPod Identity for those that call AWS
Helm releasesReinstalled from the chart and versioned valuesPer-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 edit that 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).
CriterionExported YAMLHelm/Kustomize + GitVelero
Fidelity to the current stateHighDepends on driftVery high
Maintainability afterwardsLowVery highLow (it is a backup)
On-prem → EKS transformationsManual (yq)Overlays and valuesMapping ConfigMaps, plugins
Migrates PV dataNoNoYes (FSB / snapshots)
Fits GitOpsNoYesNo

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:

  1. CRDs and operators (cert-manager, External Secrets, Argo CD).
  2. Namespaces with their security labels.
  3. ServiceAccounts, Roles and RoleBindings; Pod Identity associations.
  4. ConfigMaps, SecretStore and ExternalSecret.
  5. PVCs (with the gp3 or efs-sc StorageClasses already created).
  6. Services.
  7. Deployments and StatefulSets.
  8. Ingress and HPAs.
  9. 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).

Figure 6 Cross-cluster backup and restore with Velero
On-prem cluster (source) Amazon EKS (target) VEL Velero server Deployment NA node-agent DaemonSet · Kopia Namespaces acme-* Deploy, PVC, CM, Secret PVs ceph-rbd app data Amazon S3 acme-velero-backups AWS KMS SSE-KMS VEL Velero server BSL readOnly NA node-agent DaemonSet Restored namespaces same names EBS gp3 via EBS CSI 1 · reads resources 2 · reads PVs 3 · manifests .tar.gz 4 · data (Kopia) 5 · backup sync 6 · restores data 7 · creates resources 8 · writes change-storage-class: ceph-rbd → gp3

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 velero namespace): reconciles the Backup, Restore, Schedule, BackupStorageLocation (BSL) and VolumeSnapshotLocation (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.
  • velero CLI: creates and queries backups and restores. Under the hood it creates CRD objects.

Three ways to back up volumes:

MethodHow it worksPortable across providersConsistency
Native snapshots (VSL)Provider snapshot (e.g. EBS)No: a Ceph snapshot cannot be restored onto EBSCrash-consistent
CSI Snapshot Data Movement (--snapshot-move-data)CSI snapshot + copy of its data to S3 with KopiaYesCrash-consistent (point in time)
File System Backup (FSB)The node-agent reads the files of the volume mounted in a running podYesNo 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 velero ServiceAccount in the velero namespace.

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=false disables native snapshots, which are not portable.
  • --use-node-agent deploys the DaemonSet needed for FSB and data movement.
  • --prefix acme groups backups under s3://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

ItemDoes Velero migrate it?What to do
Deployments, Services, ConfigMaps, SAs, RBACYesReview references to the on-premises platform
Service ClusterIPsNo (reassigned)No action: use DNS names, never IPs
Non-transactional PV dataYes (FSB / data mover)Map the StorageClass and stop writes for the final backup
Live databasesNot consistentlyNative replication or DMS (chapter 11)
hostPathNoRedesign (EBS/EFS)
StorageClasses, CNI, Ingress Controller, CSIShould not be migratedReplaced by the EKS equivalents
Load balancers, DNS, internal CA certificatesNoALB/NLB, Route 53 and ACM/cert-manager
Identity (tokens, kubeconfigs, users)NoAccess Entries and Pod Identity
Operator CRDs and CRsYes, but the operator must exist firstInstall the operator in a compatible version, then restore

10.4 Velero troubleshooting

  • BSL Unavailable: wrong credentials or Region, or the bucket does not exist. Check kubectl -n velero logs deploy/velero | grep -i backupstoragelocation.
  • Backup PartiallyFailed: some resource or volume failed. Run velero backup describe NAME --details and velero backup logs NAME.
  • Pod stuck in Init:restore-wait: the node-agent is not running on that node or the volume restore failed. Check kubectl -n velero get podvolumerestores and the logs of the node-agent DaemonSet.
  • PVC Pending after the restore: the target StorageClass does not exist or the mapping is missing. Check the change-storage-class-config ConfigMap.
  • Resources that “won’t restore”: by default Velero does not overwrite existing objects. Use --existing-resource-policy=update carefully, or delete the objects at the target before restoring.

References

11. Migrating Persistent Volumes and databases

Figure 7 Persistent Volume migration: choose the method by data type
What is inside the PV? Classify every PVC in theinventory by data type Transactional database PostgreSQL, MySQL, MongoDB…Migrate at application level: logicalreplication, DMS, dump/restore Shared files (RWX) NFS, CephFS, uploads, mediaFile-level copy withAWS DataSync or rsync Application data (RWO) Indexes, embedded queues, local filesVelero File System Backup (Kopia)and restore onto EBS gp3 Rebuildable / cache Redis cache, temp files, build cacheNot migrated: rebuiltat the target (warm-up) DMS / pglogical AWS DataSync VEL Velero FSB Amazon RDS / Aurora Amazon EFS (or S3 for objects) Amazon EBS gp3 ElastiCache empty + warm-up no data migration

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

SourceTypical contentRecommended targetMethodLimitations
Local PV / hostPathData bound to a nodeEBS gp3Velero FSB or a copy through S3No CSI snapshot; writes must be stopped
NFS (nfs-client)Shared RWX filesAmazon EFSAWS DataSync (or rsync)UID/GID permissions and symlinks must be verified
Ceph RBDRWO blockEBS gp3CSI data movement or FSBCeph snapshots are not portable
CephFSRWX filesAmazon EFSDataSync (mounted over NFS) or FSB—
LonghornRWO blockEBS gp3CSI 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 blockEBS gp3FSB, or migrate the VM with AWS MGN if the volume belongs to a VMVMDKs cannot be mounted on EKS
Objects inside a PV (uploads, reports)BlobsAmazon S3DataSync or aws s3 syncThe 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.

Figure 8 Migrating PostgreSQL to Amazon RDS with minimal downtime
On-premises AWS backend writes to the source PostgreSQL 14 wal_level=logical backend (EKS) after cutover RDS PostgreSQL 16 Multi-AZ AWS DMS writes ③ cutover ① schema: pg_dump --schema-only | psql ② initial load + CDC: PUBLICATION → SUBSCRIPTION alternative ②: managed full load + CDC rollback: reverse replication RDS → on-prem ④ Validation before and after cutover row counts · per-table checksums · lag = 0 · sequences synced

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 4 uses the directory format, the only one that supports parallel dumps.
  • --no-owner --no-privileges avoids errors when restoring objects owned by a role that does not exist in RDS.
  • RDS does not grant SUPERUSER: the master user has rds_superuser. Extensions must be on RDS’s supported list.

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 with TargetTablePrepMode: 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}}'
Criterionpg_dump/restoreNative logical replicationAWS DMS
DowntimeHigh (hours for large databases)MinutesMinutes
ComplexityLowMediumMedium
CostNoneNoneReplication instance or DMS Serverless
Built-in validationNoNoYes
Major version changeYesYesYes
Best forSmall databases, dev/stagingA single PostgreSQL → PostgreSQL databaseMany 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

  1. Put the application in maintenance mode or read-only: kubectl scale deploy/backend --replicas=0 at the source, or a feature flag.
  2. Verify that no write connections remain: SELECT * FROM pg_stat_activity WHERE datname = 'acme' AND state <> 'idle';.
  3. Wait for the lag to reach 0 (the pg_replication_slots query).
  4. 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;
  1. Run the validations from section 11.8.
  2. ALTER SUBSCRIPTION acme_sub DISABLE; in RDS, and point the application on EKS to the RDS endpoint.
  3. Rollback ready: with rds.logical_replication = 1, create a publication in RDS and a subscription at the source (with copy_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:

  1. Seed from an RDB file: redis-cli --rdb dump.rdb at 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.
  2. 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.
  3. 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

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

ConceptOn-premises (ACME)Amazon EKS
ClusterIPkube-proxy with iptablesSame (kube-proxy managed as an add-on)
NodePortUsed by F5 to reach ingress-nginxAvoided: the ALB reaches pods directly
type: LoadBalancerRequires MetalLBAWS LBC creates an NLB (with annotations)
Ingressingress-nginxAWS LBC creates an ALB
Internal DNSCoreDNS (cluster.local)Same; for acme.local, Route 53 Resolver
External DNSBIND + manual recordsRoute 53 (+ ExternalDNS to automate it)
NetworkPolicyCalicoVPC CNI with standard policies, or Calico/Cilium if advanced CRDs are needed
Perimeter firewallPhysical firewallSecurity Groups, NACLs, AWS WAF, AWS Network Firewall
Internet egressCorporate firewall NATNAT Gateway per AZ (fixed Elastic IP)
Figure 9 Networking before and after: the path of a request
BEFORE · on-premises (kubeadm + Calico) AFTER · Amazon EKS (VPC CNI + AWS LB Controller) Client https://app.acme.local Internal DNS BIND: app → VIP 10.0.0.10 F5 / HAProxy (L4) VIP → NodePort 30443 on every node ingress-nginx terminates TLS · routes by host/path Service ClusterIP → Pod kube-proxy (iptables) · Pod 192.168.x.x (overlay) Client https://app.acme.com Route 53 alias → ALB (weighted during cutover) Application Load Balancer TLS with ACM · public subnets · optional WAF TG Target group (target-type: ip) the AWS LB Controller registers the pod IPs Pod 10.20.52.17 real VPC IP (Amazon VPC CNI)

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: ip there 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/16 are propagated to the private and data subnet route tables, and that the on-premises firewall allows return traffic from 10.20.0.0/16.

References

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: HTTPS with internal certificates (cert-manager).
  • Data: rds.force_ssl = 1 on RDS, TLS on ElastiCache and sslmode=require (or verify-full with 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

ToolTypeWhat it provides
Amazon InspectorAWS serviceContinuous scanning of ECR images and EC2 instances
TrivyOpen sourceScanning of images, IaC (Terraform), manifests and SBOMs in the pipeline (shift left)
Amazon GuardDutyAWS serviceEKS Protection (audit log analysis) and Runtime Monitoring (agent on the nodes)
FalcoOpen source (CNCF)Runtime anomaly detection with custom rules
AWS CloudTrailAWS serviceAuditing of every AWS API call (including EKS ones)
AWS Security Hub (and Security Hub CSPM)AWS serviceConsolidates findings (GuardDuty, Inspector, Config) and evaluates standards such as AWS Foundational Security Best Practices or CIS
AWS ConfigAWS serviceInventory and conformance rules for resource configuration

13.6 The most common security mistakes (and how to avoid them)

  1. Access keys in Secrets or CI variables. Use Pod Identity and OIDC: not a single long-lived access key should exist.
  2. Public cluster endpoint open to 0.0.0.0/0. Make it private or restrict the CIDRs.
  3. 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 = 1 in the launch template).
  4. Security Groups with 0.0.0.0/0 to databases. RDS and ElastiCache never go in public subnets or with open access.
  5. Secrets copied “as is” from on-premises. Rotate every credential during the migration: assume the old ones may have leaked over years of operation.
  6. Ignoring control plane logs. Enable audit and authenticator from day one; investigating an incident without them is impossible.
  7. Images running as root and without scanning. Pod Security restricted plus Inspector and Trivy in the pipeline.

References

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.

SignalOn-premises (ACME)On AWSDecision
MetricsPrometheus (300 GiB local TSDB)Amazon Managed Service for Prometheus (AMP) with remote_writeKeep PromQL, delegate storage and HA
DashboardsSelf-managed GrafanaAmazon Managed Grafana (or Grafana in the cluster)Export and import the dashboard JSON
AlertsAlertmanagerAMP alert manager → SNS → Slack/PagerDutyMigrate rules (same YAML format)
Logskubectl logs and a small ELKCloudWatch Logs via the amazon-cloudwatch-observability add-on (Fluent Bit)Centralized logs with defined retention
Infrastructure metricsnode-exporterContainer Insights (enhanced observability)Cluster, node and pod view with no maintenance
TracesDid not existOpenTelemetry (ADOT) → AWS X-RayNew capability, introduced gradually
Figure 13 Observability architecture on EKS
Amazon EKS Managed services apps /metrics · OTLP KSM kube-state-metrics node-exporter ADOT Collector or Prometheus agent CW agent + Fluent Bit EKS add-on Managed Prometheus AMP workspace CloudWatch Logs + Container Insights AWS X-Ray traces Managed Grafana dashboards AM Alertmanager (AMP) → SNS → Slack / PagerDuty scrape + OTLP remote_write (SigV4) traces logs PromQL alert rules

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:

  1. In-cluster collector: Prometheus in agent mode or the ADOT Collector scrapes and sends with SigV4-signed remote_write (using Pod Identity).
  2. 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 Ready and 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

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.
Figure 10 CI/CD with GitHub Actions and GitOps deployment with Argo CD
Developer App repo acme/backend GitHub Actions CI CI pipeline build → tests → Trivy → docker build Amazon ECR tag = git SHA IAM role (OIDC) no access keys GitOps repo acme/platform-gitops Argo CD inside EKS Amazon EKS backend Deployment 1 · git push 2 · trigger 5 · push AssumeRoleWithWebIdentity temporary credentials 6 · commit image.tag 7 · watches repo 8 · sync 9 · pull image

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 CDFlux CD
InterfaceFull web UI, RBAC and SSOMostly CLI and CRDs (third-party UIs)
ModelApplication / ApplicationSetKustomization / HelmRelease
Multi-clusterCentral hub that manages several clustersOne Flux per cluster (or hierarchies)
Choice for ACMEYes: 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

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.

Figure 11 Cutover and rollback: production switchover timeline
T−7 d Release freeze 1 TTL DNS → 60 s AWS 0 % T−1 d Final rehearsal 2 Go / No-Go decision AWS 0 % T−2 h Maintenance 3 writes blocked AWS 0 % T−1 h Final sync 4 lag = 0 · sequences AWS 0 % T0 Route 53 → 10 % 5 smoke tests AWS 10 % T+1 h 50 % → 100 % 6 SLO monitoring AWS 100 % T+7 d Hypercare 7 on-prem retired T+30 d AWS 100 % Rollback: Route 53 → 100 % on-prem · reverse replication RDS → on-prem

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)

  1. T−2 h · Maintenance announcement. On-premises CronJobs suspended (suspend: true).
  2. 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.
  3. T−30 min · On-premises backend and EKS backend reconfigured to write to RDS. Subscription disabled; reverse replication RDS → on-premises enabled (for rollback).
  4. T0 · Route 53: 10 % to the ALB. Automated smoke tests (login, issuing an invoice, a query).
  5. T+15 min · If SLOs are met (errors below 1 % and p95 below 400 ms): 50 %.
  6. T+1 h · 100 % on AWS. CronJobs enabled on EKS. On-premises stays in hot standby.
  7. T+7 d · End of hypercare. The rollback window closes and reverse replication is disabled.
  8. 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

TriggerActionExpected time
5xx errors above 5 % for 5 min after a traffic stepRoute 53: 100 % weight on-premises1-2 min + TTL
Data inconsistency detectedStop writes on AWS; reverse replication caught up; writer = on-premises15-30 min
RDS performance degradationScale the instance (Multi-AZ minimizes the interruption) or go back on-premises10-30 min
Platform component failure (DNS, LBC, IAM)Route 53 → on-premises while it is fixed1-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 Synced and Healthy for 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_protection enabled.
  • 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.

ValidationWhat to proveTools and commands
FunctionalBusiness flows work end to endSmoke tests and E2E suites (Playwright, Postman/Newman) against app.acme.com
InfrastructureEvery component is healthy and in placekubectl get nodes,pods -A, argocd app list, aws eks describe-cluster, Terraform with no drift (empty terraform plan)
DataSame data as the source at cutover timeCounts and checksums (11.8), DMS validation if used, business reconciliation (daily invoiced totals)
PerformanceLatencies equal to or better than on-premisesCompare ALB and trace p50/p95/p99 with the assessment baseline
LoadHandles the month-end peak with headroomk6 or Locust simulating 4× normal traffic; verify that Karpenter and the HPA react
ResilienceTolerates losing pods, nodes and an AZAWS Fault Injection Service (actions on EKS pods and EC2 instances), Chaos Mesh, RDS failover (aws rds reboot-db-instance --force-failover)
SecurityNo undue exposure or excessive permissionsSecurity Hub, Inspector and GuardDuty findings; kube-bench (CIS); review of Access Entries and SGs
BackupsYou can restore, not just back upPoint-in-time RDS restore into a new instance; Velero restore into a test cluster
High availabilityNo single points of failureReplicas per AZ (kubectl get pods -o wide), NAT per AZ, RDS Multi-AZ, ElastiCache with a replica
ObservabilityWhat happens is visible and alertsFire a test alert; confirm logs, metrics and traces for a specific request
DRYou can recover in another Region if the RTO requires itDocumented 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

  1. Compute (EC2): usually 50 to 70 % of the bill. It depends on right-sizing the requests, the instance type, Spot and commitments (Savings Plans).
  2. Network: NAT Gateway (per hour and per GB), cross-AZ traffic, Internet egress and interface VPC endpoints.
  3. Managed data services: RDS (instance, Multi-AZ and storage), ElastiCache, EFS (per GB stored) and EBS.
  4. Observability: CloudWatch Logs ingestion, custom metrics and AMP samples.
  5. Control plane: fixed per cluster. It is multiplied by 6 if the version enters extended support.

18.2 Monthly estimate for ACME (example)

ComponentAssumptionApprox. USD/month
EKS control plane1 cluster, standard support73
System node group3 × m7i.large on-demand (USD 0.1008/h)220
Application nodes (Karpenter)~6 × m7i.xlarge equivalents (USD 0.2016/h on-demand), 50 % Spot600
NAT Gateway3 × USD 0.045/h + 300 GB × USD 0.045/GB115
ALB1 ALB + moderate LCUs35
Interface VPC endpoints5 endpoints × 3 AZs × USD 0.01/h110
RDS PostgreSQLdb.m7g.large Multi-AZ (USD 0.337/h) + 200 GB gp3 + backups300
ElastiCache (Valkey)2 cache.m7g.large nodes (USD 0.1264/h)185
EBS + EFS300 GB gp3 + 50 GB EFS40
S3 (Velero backups, artifacts)1 TB Standard25
CloudWatch (logs + Container Insights)150 GB/month ingested, 30-day retention120
AMP + Managed GrafanaMetrics for 1 cluster + 5 editors120
Site-to-Site VPN1 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 requests to the real p95 (chapter 4.3). The Vertical Pod Autoscaler in Off mode (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 arm64 to 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, Team and CostCenter tags in Billing (Terraform’s default_tags applies 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

19. Troubleshooting

Every problem follows the same structure: symptoms → causes → diagnosis → fix → prevention.

19.1 Pods stuck in Pending

  • Symptoms: kubectl get pods shows Pending for minutes.
  • Causes: no capacity (CPU/memory), the Karpenter NodePool does not admit the pod’s requirements (architecture, zone, taints), an unbound PVC, or topologySpreadConstraints that 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 NodePool limits and 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.api and ecr.dkr VPC endpoints and the S3 Gateway endpoint, where the layers live), or a manifest still points to harbor.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.local hostname, or OOMKilled because of different limits.
  • 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, ExternalSecret validation in the pipeline and staging tests with the same configuration.

19.4 PVC Pending and StorageClass incompatibility

  • Symptoms: PVC Pending; pods in ContainerCreating.
  • Causes: the StorageClass does not exist (ceph-rbd on 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-sc for 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 perform or NoCredentialProviders in 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 ContainerCreating with failed 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 /28 space.
  • 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.local is missing, CoreDNS is saturated or has too few replicas, ndots:5 generates 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/elb tags, the LBC lacks permissions, a wrong ingressClassName, 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 X and kubectl 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 sequence last_values, and reviewing pg_stat_activity at the source at cutoff time.
  • Fix: setval on 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

Figure 12 Final production architecture: the complete platform by layer
Edge and access Users Route 53 health checks ACM TLS ALB multi-AZ Delivery (CI/CD + GitOps + IaC) GitHub Actions OIDC Amazon ECR immutable Argo CD GitOps Terraform state in S3 Compute · Amazon EKS in 3 AZs EKS control plane System MNG critical add-ons KAR Karpenter On-Demand + Spot frontend HPA backend HPA + PDB LBC AWS LB Controller CSI EBS / EFS CSI Pod Identity per-pod IAM Data RDS PostgreSQL Multi-AZ ElastiCache replica + failover Amazon EFS RWX Amazon S3 objects Resilience AWS Backup RDS · EBS · EFS VEL Velero K8s resources Multi-AZ failover Cross-region copy DR Security and compliance KMS Secrets Mgr GuardDuty EKS Runtime Inspector ECR + EC2 Security Hub CloudTrail Observability CloudWatch Container Insights Managed Prometheus Managed Grafana ADOT OpenTelemetry X-Ray traces

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

#StageKey actionsExit evidence
1InventoryScripts from 4.2-4.7 against the source clusterdocs/assessment/*.csv, Pluto and kubent reports
2AssessmentApp matrix, per-app strategy (6R) and wavesApproved docs/assessment/matrix.md
3Terraformvpc → eks → data → cicdterraform plan with no pending changes
4EKSAdd-ons, LBC, Karpenter, External Secrets, Argo CDHealthy kubectl get pods -A; “hello” Ingress responds
5ECRmigrate-images.shEvery digest verified (OK)
6VeleroRehearsal backup of acme-reports and restore on EKSRestore Completed; matching file counts and checksums
7Data migrationLogical subscription to RDS; DataSync to EFSsrsubstate = r on every table; steady lag
8NetworkingVPN, Resolver, NetworkPolicies, ALB IngressDNS and connectivity tests from 19.7 and 19.9 green
9SecurityPod Security restricted, Pod Identity, Inspector, GuardDutyNo open critical findings in Security Hub
10CI/CDGitHub Actions pipeline + OIDCA commit on main deploys to staging with no intervention
11GitOpsArgo CD root appEvery app Synced/Healthy
12CutoverChapter 16 runbook100 % of traffic on AWS; write downtime measured
13ValidationChapter 17 matrixSigned-off validation report
14OptimizationRight-sizing, Spot, Savings Plans after 60 daysMonthly 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

NamePurposePhaseAlternativesProsLimitationsCostDocumentation
Amazon EKSManaged KubernetesBuild / OperateSelf-managed Kubernetes, ECSUpstream Kubernetes, IAM/VPC integrationMandatory version cyclePer cluster-hour + resourcesDocs
Amazon ECRImage registryImagesHarbor, GHCR, Docker HubIAM, KMS, Inspector, replicationPer Region and account (use replication)Per GB stored + data transferDocs
Amazon RDS for PostgreSQLManaged databaseDataAurora PostgreSQL, PostgreSQL on EKSHA, PITR, patchingNo superuser; limited extensionsPer instance-hour + storageDocs
AWS DMSDatabase migration with CDCDataNative replication, pglogicalManaged, validationDoes not migrate every schema objectPer replication instance-hour or DCU (Serverless)Docs
AWS DataSyncFile transferDatarsync, rcloneIncremental, verification, encryptionRequires an on-premises agentPer GB transferredDocs
Amazon ElastiCacheManaged cache (Valkey/Redis OSS)DataRedis on EKSFailover, no operationsRestrictions on administrative commandsPer node-hour or serverlessDocs
AWS Load Balancer Controller + ELBALB/NLB from KubernetesNetworkingNGINX (F5), Traefik, Envoy GatewayManaged, ACM, WAF, target-type: ipLess rewrite flexibility than a proxyALB/NLB per hour + LCUDocs
Amazon Managed Service for PrometheusMetrics storageObservabilitySelf-managed Prometheus/Thanos/MimirNo operations, PromQL-compatiblePer-sample cost at high cardinalityPer samples ingested and queriedDocs
Amazon CloudWatchLogs, metrics, Container InsightsObservabilityLoki, OpenSearch, ELKNative integrationLog ingestion costPer GB ingested and storedDocs
Amazon Inspector / GuardDuty / Security HubVulnerabilities, detection, postureSecurityTrivy, Falco, CNAPP toolsManaged, multi-accountCost per resource scanned/analyzedUsage-basedInspector

Open source tools

NamePurposePhaseAlternativesProsLimitationsLicenseDocumentation
TerraformInfrastructure as codeLanding Zone / BuildOpenTofu, AWS CDK, CloudFormationModule ecosystem, multi-providerState to manage; BSL license since 1.6BSL 1.1 (OpenTofu: MPL 2.0)Docs
eksctlEKS cluster creationBuild (labs)Terraform, consoleVery fastDoes not manage the rest of the infrastructureApache 2.0Docs
VeleroK8s backup/restore/migrationMigration / DRKasten K10 (commercial), TrilioPortable, FSB and data moverDoes not migrate live databases consistentlyApache 2.0Docs
crane / skopeoCopying images between registriesImagesregctl, Harbor replicationPreserves manifest lists and digestsCLI (needs orchestration)Apache 2.0crane · skopeo
HelmApplication packagingResources / CI/CDKustomize, JsonnetDe facto standard for third-party appsComplex templatesApache 2.0Docs
KustomizeManifest variantsResources / CI/CDHelmNo templates, built into kubectlLess expressive for logicApache 2.0Docs
Argo CDGitOpsCI/CDFlux CDUI, multi-cluster, drift detectionOne more component to operateApache 2.0Docs
KarpenterNode provisioningBuild / FinOpsCluster Autoscaler, EKS Auto ModeFast, Spot, consolidationLearning curveApache 2.0Docs
External Secrets OperatorSecret syncingSecuritySecrets Store CSI Driver (ASCP)Many providers; environment variablesSecrets exist as Secret objectsApache 2.0Docs
Pluto / kubentDeprecated API detectionAssessmentEKS upgrade insightsFast and accurateThey only detect; they do not fixApache 2.0 / MITPluto · kubent
TrivyVulnerability and IaC scanningSecurity / CIGrype, InspectorAll-in-one, fastVulnerability database must be kept updatedApache 2.0Docs
FalcoRuntime securitySecurityGuardDuty Runtime MonitoringCustomizable rulesNoise tuningApache 2.0Docs
OpenTelemetry / Fluent BitTelemetry and logsObservabilityProprietary agentsOpen standardDetailed configurationApache 2.0OTel · 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:

  1. The assessment defines success. Surprises at cutover are dependencies that were never inventoried.
  2. 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.
  3. No single tool migrates everything. Velero, DMS, DataSync and crane solve different parts, and all of them need configuration, mappings and validation.
  4. 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.
  5. Security and identity are designed from day one: Pod Identity, Access Entries, secrets outside the cluster and audit logs.
  6. Cost is an operational metric, not a quarterly report: tags, budgets, right-sizing and an explicit Kubernetes version policy.
  7. 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

TermDefinition
Access EntryAn EKS record that links an IAM identity to Kubernetes permissions, without the aws-auth ConfigMap
ALB / NLBApplication Load Balancer (layer 7, HTTP/HTTPS) / Network Load Balancer (layer 4, TCP/UDP/TLS)
AZAvailability Zone: one or more isolated datacenters within an AWS Region
CDCChange Data Capture: continuous capture and replication of a database’s changes
CNIContainer Network Interface: the plugin that provides pod networking (Calico, VPC CNI, Cilium)
CRDCustom Resource Definition: an extension of the Kubernetes API with new object types
CSIContainer Storage Interface: the standard for storage drivers (EBS CSI, EFS CSI)
CutoverThe moment the target system becomes the production system
DigestSHA-256 hash that immutably identifies an image’s content
FSBVelero File System Backup: file-level copy of pod volumes
GitOpsOperating model in which Git is the source of truth and an agent reconciles the cluster with it
IRSAIAM Roles for Service Accounts: IAM credentials for pods through OIDC
KarpenterNode provisioner that launches EC2 instances based on pending pods
Landing ZoneSecure, governed multi-account AWS environment where workloads are deployed
Manifest listImage index that groups variants per architecture (amd64, arm64)
Multi-AZRedundant deployment across several Availability Zones
NAT GatewayService that enables outbound Internet traffic from private subnets
Pod IdentityEKS mechanism to associate an IAM role with a ServiceAccount
PV / PVCPersistentVolume (the volume) / PersistentVolumeClaim (a pod’s request)
RPO / RTORecovery Point Objective (data that can be lost) / Recovery Time Objective (time to recover)
SCPService Control Policy: a permission boundary enforced by AWS Organizations
StorageClassTemplate for dynamic volume provisioning
VPC endpointPrivate connection from the VPC to an AWS service without going over the Internet
WaveA group of applications migrated together

Official references

AWS

Kubernetes and CNCF

Infrastructure as code

Databases

© 2026 Juan Hoyos.