Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 71

Deploying Kubernetes Manifests to EKS

This lesson is built with resources from youtube.com, blog.devgenius.io and 1 more site.

Hello and welcome back to the course!

In the last lesson, you successfully built a Continuous Integration (CI) pipeline. Your workflow now automatically validates, builds, and pushes a versioned Docker image of the auth-service to a secure AWS ECR repository every time you merge to the main branch. This is a huge step.

Today, we'll complete the automation loop by building the Continuous Deployment (CD) half of the pipeline. You will learn how to add a deployment stage that takes the newly built image and automatically deploys it to your EKS cluster, triggering a zero-downtime rolling update. This lesson bridges the gap between having a ready artifact in a registry and getting it live in production.

MERN Stack Analogy

In a traditional MERN deployment, you might SSH into a server, run git pull, and then pm2 restart app. This process is manual, error-prone, and usually involves a brief service interruption. What we are building today is the automated, cloud-native equivalent. We are instructing our system: "Upon a successful build, automatically tell Kubernetes to update our running application with this new container image, and do it without any downtime."



Understanding Rolling Updates

Before we write the code, let's visualize what we want to achieve. A rolling update is Kubernetes' default strategy for updating a running application. It ensures service availability by incrementally replacing old application instances (pods) with new ones.

Kubernetes Rolling Update Animation
This animation shows a rolling update in action. Kubernetes ensures that some pods are always available to serve traffic as it gradually replaces the V1 pods with V2 pods.

Our goal is to automate the trigger for this process within our GitHub Actions pipeline.



Extending the Pipeline for Deployment

Our CI/CD pipeline will now have three distinct jobs, executed in sequence:

  1. validate: Runs tests and linters.
  2. build-and-push: Builds and pushes the Docker image to ECR.
  3. deploy: Deploys the new image to EKS.

We will create the deploy job, which will need the build-and-push job to complete successfully.

Step 1: Granting EKS Permissions to Your IAM Role

Your OIDC IAM Role currently has permissions to interact with ECR. To allow GitHub Actions to interact with your EKS cluster, you need to grant it EKS permissions as well.

  1. Navigate to the IAM console in AWS.
  2. Find the role you created in the previous lesson (e.g., GitHubActionsEKSRole).
  3. Under the "Permissions" tab, click "Add permissions" -> "Attach policies".
  4. Search for and attach the AmazonEKSClusterPolicy. For a production environment, you would create a more fine-grained policy, but this is sufficient for our learning purposes.
  5. Additionally, you need to authorize this role to interact with your specific EKS cluster. Run the following AWS CLI command, replacing the placeholders with your values. This command tells EKS to recognize and grant permissions to your GitHub Actions role.
aws eks create-access-entry \
    --cluster-name your-eks-cluster-name \
    --principal-arn arn:aws:iam::YOUR_AWS_ACCOUNT_ID:role/YOUR_IAM_ROLE_NAME \
    --type STANDARD

Then, associate a policy with this new access entry that allows it to manage deployments.

aws eks associate-access-policy \
    --cluster-name your-eks-cluster-name \
    --principal-arn arn:aws:iam::YOUR_AWS_ACCOUNT_ID:role/YOUR_IAM_ROLE_NAME \
    --policy-arn arn:aws:eks::aws:policy/AmazonEKSAdminPolicy \
    --access-scope type=cluster

With these permissions in place, your pipeline is now authorized to perform deployments.

Step 2: Preparing Your Kubernetes Manifest for CD

A robust CD process should not require you to manually edit and commit your deployment.yaml file with a new image tag for every single deployment. Instead, we'll use a placeholder in the manifest and dynamically replace it during the pipeline run.

Update your auth-service/deployment.yaml file. Find the image field and change it to use a placeholder like this:




# auth-service/deployment.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: auth-service-deployment
spec:
  replicas: 2
  selector:
    matchLabels:
      app: auth-service
  template:
    metadata:
      labels:
        app: auth-service
    spec:
      containers:
      - name: auth-service
        image: DOCKER_IMAGE_PLACEHOLDER # 👈 Update this line
        ports:
        - containerPort: 8080

This placeholder, DOCKER_IMAGE_PLACEHOLDER, will be replaced with the actual ECR image URI by our pipeline.

Step 3: Building the Deployment Job

Now, let's add the deploy job to your .github/workflows/ci.yml file. This job will configure kubectl, dynamically update the manifest, and apply it.

Build a Secure CI/CD Pipeline for Amazon EKS Using GitHub ...

The article 'Build a Secure CI/CD Pipeline for Amazon EKS' provides an excellent example of a complete workflow that uses OIDC and dynamically deploys to EKS. We will focus on the final deployment steps.

Read the section 'EKS Deployment' within the article. Pay close attention to the last two steps in the YAML file: Update kube config: Notice the aws eks update-kubeconfig command. This configures the kubectl CLI inside the GitHub runner to communicate with your EKS cluster. Deploy to EKS: This is the core of our lesson. Observe how it uses the sed command to find and replace the DOCKER_IMAGE placeholder in the manifest file with the actual image URI, which is built from environment variables. After the replacement, it runs kubectl apply to trigger the deployment.

Based on that resource and our project structure, add the following deploy job to the end of your ci.yml file.




# .github/workflows/ci.yml




# ... (name, on, permissions, validate job, build-and-push job are unchanged)

  deploy:
    name: Deploy Auth Service to EKS
    runs-on: ubuntu-latest
    needs: build-and-push # This job depends on the previous one
    
    steps:
      - name: Checkout repository
        uses: actions/checkout@v4

      - name: Configure AWS Credentials
        uses: aws-actions/configure-aws-credentials@v4
        with:
          role-to-assume: arn:aws:iam::YOUR_AWS_ACCOUNT_ID:role/YOUR_IAM_ROLE_NAME # 👈 Replace with your IAM Role ARN
          aws-region: us-east-1 # 👈 Replace with your AWS region

      - name: Login to Amazon ECR
        id: login-ecr
        uses: aws-actions/amazon-ecr-login@v2
      
      - name: Update kubeconfig
        run: aws eks update-kubeconfig --name your-eks-cluster-name --region us-east-1 # 👈 Replace with your cluster name and region

      - name: Deploy to EKS
        env:
          ECR_REGISTRY: ${{ steps.login-ecr.outputs.registry }}
          ECR_REPOSITORY: your-ecr-repo-name # 👈 Replace with your ECR repository name
          IMAGE_TAG: ${{ github.sha }}
        run: |



          # Use sed to replace the placeholder with the actual image URI
          sed -i "s|DOCKER_IMAGE_PLACEHOLDER|$ECR_REGISTRY/$ECR_REPOSITORY:$IMAGE_TAG|g" auth-service/deployment.yaml
          



          # Apply the updated manifests to the cluster
          kubectl apply -f auth-service/deployment.yaml
          kubectl apply -f auth-service/service.yaml

Dissecting the Deploy to EKS step:

  • sed -i "s|...|...|g" ...: This is a powerful command-line utility for find-and-replace. We are telling it to find DOCKER_IMAGE_PLACEHOLDER in our deployment.yaml and replace it with the full image URI constructed from our environment variables ($ECR_REGISTRY/$ECR_REPOSITORY:$IMAGE_TAG).
  • kubectl apply -f ...: This is the command that tells Kubernetes to apply the configuration. Since the manifest now contains a new image tag, Kubernetes will detect the change and initiate a rolling update.


Runtime Observation & Your Debugging Task

Now it's time to see your full CI/CD pipeline in action.

  1. Make a Change: Make a small, visible change in the auth-service code. For instance, change a log message in one of the controllers.
  2. Commit and Push: Commit your changes (including the updated ci.yml and deployment.yaml) and push them to the main branch.
  3. Observe the Pipeline: Go to the "Actions" tab in your GitHub repository. You will see the full pipeline execute: validate -> build-and-push -> deploy.
  4. Watch the Rolling Update: While the deploy job is running, open a terminal and run kubectl get pods -n default -w. You will see the rolling update live: Kubernetes will show new auth-service pods being created (ContainerCreating) and old pods being shut down (Terminating).
  5. Verify the Deployment: Once the pipeline is green and the new pods are Running, check the logs of a new pod (kubectl logs <new-pod-name>). You should see your updated log message, confirming the deployment was successful.

Deploying applications to AWS EKS using GitHub actions

To get a better sense of what this process looks like from a user's perspective, watch this short segment from the 'Deploying applications to AWS EKS' video. It shows a code change triggering the pipeline and then verifies the update on the live application.

Watch from 57:40 to 01:01:24. The key takeaway is observing how a git push triggers the entire workflow, which results in a 'rolling update' on the cluster. The presenter checks the application URL and waits for the change to appear, demonstrating a zero-downtime update.

Your Debugging Task:
A classic CD failure is due to incorrect permissions.

  1. Introduce a Bug: Go back to your IAM Role in the AWS console. Detach the AmazonEKSClusterPolicy you added earlier.
  2. Trigger the Pipeline: In GitHub, go to your last successful workflow run, and on the top right, there is a "Re-run all jobs" button. Click it to trigger the pipeline again without a code change.
  3. Investigate the Failure: The deploy job will fail. Examine the logs for the Deploy to EKS step. You will see an authorization error from kubectl, something like error: You must be logged in to the server (Unauthorized). This is a classic sign that your CI/CD role lacks the necessary Kubernetes permissions.
  4. Fix and Re-run: Re-attach the policy to your IAM role and re-run the job to confirm the fix.


Conclusion

Excellent work! You have now constructed a complete, production-style CI/CD pipeline. Your system is now capable of automatically testing, packaging, and deploying your application from a single git push, all while ensuring zero downtime for your users.

Key Takeaways:

  • Continuous Deployment (CD) automates the release of validated code to a production environment.
  • The needs keyword in GitHub Actions is used to create dependencies between jobs, forming a sequential pipeline.
  • IAM Roles for CI/CD need permissions for all the services they interact with (ECR, EKS).
  • Production-grade CD pipelines do not store image tags in source control. They use placeholders in manifests and dynamically substitute them (e.g., with sed) during the deployment process.
  • kubectl apply is the declarative command that triggers Kubernetes' built-in rolling update strategy.

Preview of the Next Lesson:
We've now built a robust platform for deploying our services. The upcoming module, "Testing and Integrating the Full System," shifts our focus back to code quality. In the next lesson, you will learn to write unit tests for a service class using JUnit 5 and Mockito, and we'll compare Java's mocking patterns to those you're familiar with in the JavaScript world with Jest.