Use Amazon EBS as Persistent Storage in a Self-Managed Kubernetes Cluster on EC2

  1. Create an IAM instance profile for the EBS CSI driver
aws iam create-role \
    --role-name K8sEBSRole \
    --assume-role-policy-document '{
        "Version": "2012-10-17",
        "Statement": [
            {
                "Effect": "Allow",
                "Principal": {
                    "Service": "ec2.amazonaws.com"
                },
                "Action": "sts:AssumeRole"
            }
        ]
    }'
aws iam attach-role-policy \
    --role-name K8sEBSRole \
    --policy-arn arn:aws:iam::aws:policy/service-role/AmazonEBSCSIDriverPolicy
aws iam create-instance-profile --instance-profile-name K8sEBSProfile
aws iam add-role-to-instance-profile --instance-profile-name K8sEBSProfile --role-name K8sEBSRole

Then, attach this instance profile to your EC2 instances

  1. Install the EBS CSI driver
helm repo add aws-ebs-csi-driver https://kubernetes-sigs.github.io/aws-ebs-csi-driver
helm repo update
helm upgrade --install aws-ebs-csi-driver \
    --namespace kube-system \
    aws-ebs-csi-driver/aws-ebs-csi-driver
  1. Create a StorageClass for EBS
# ebs-sc.yaml
apiVersion: storage.k8s.io/v1
kind: StorageClass
metadata:
  name: ebs-sc
provisioner: ebs.csi.aws.com
parameters:
  type: gp3
  encrypted: "true"
reclaimPolicy: Delete
allowVolumeExpansion: true
volumeBindingMode: WaitForFirstConsumer
kubectl apply -f ebs-sc.yaml
  1. Test the setup

Create a PersistentVolumeClaim (PVC) using the new StorageClass:

# ebs-claim.yaml
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  name: ebs-claim
spec:
  accessModes:
    - ReadWriteOnce
  storageClassName: ebs-sc
  resources:
    requests:
      storage: 4Gi

kubectl apply -f ebs-claim.yaml

Create a Pod that uses this PVC:

# ebs-app.yaml
apiVersion: v1
kind: Pod
metadata:
  name: app
spec:
  containers:
  - name: app
    image: ubuntu:20.04
    command: ["/bin/bash"]
    args: ["-c", "while true; do date -u >> /data/out.txt; sleep 5; done"]
    volumeMounts:
    - name: persistent-storage
      mountPath: /data
  volumes:
  - name: persistent-storage
    persistentVolumeClaim:
      claimName: ebs-claim
kubectl apply -f ebs-app.yaml

Check if the PVC is bound and the Pod is running:

kubectl get pvc
kubectl get pods

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top