Skip to content
ImagineWorld

Security Best Practices for Deploying Gen AI on Kubernetes

node_idnode-book_kubernetes-for-generative-ai-solutions_chapter-09-security-best-practices-for-deploying-gen-ai-on-kubernetes
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num9
chapter_titleSecurity Best Practices for Deploying Gen AI on Kubernetes
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

Chapter 9 — Security Best Practices for Deploying Gen AI on Kubernetes

Section titled “Chapter 9 — Security Best Practices for Deploying Gen AI on Kubernetes”

In this chapter, we will explore the security best practices for deploying GenAI applications on Kubernetes (K8s). We will begin by introducing the concept of “defense in depth” and then cover the key pillars of securing GenAI workloads – supply chain, host, network, and runtime security. Additionally, we will cover best practices for the management of secrets and the principle of least privilege to prevent unauthorized access to critical data and application credentials.

In this chapter, we’re going to cover the following main topics:

  • Defense in depth
  • K8s security considerations
  • Additional considerations for GenAI apps
  • Implementing security best practices in a chatbot app

In this chapter, we will be using the following, the first of which requires you to set up an account and create an access token:

The best way to protect an application in the cloud is by using the concept of defense in depth (https://csrc.nist.gov/glossary/term/defense_in_depth). This is a strategy that implements multiple layers of security to protect against threats across different attack vectors. Figure 9*.1* shows a conceptual view of defense in depth, where each concentric circle represents a layer or attack vector we would like to secure.

Let’s look over this concept for security best practices, and then we will dive deeper for every layer, specific to containers and K8s.

Figure 9.1 – Layered security model

The following are details about the layers depicted in the preceding figure:

  • User data: This is the innermost core of the system containing sensitive user data, such as user passwords, personally identifiable information (PII), and so on. To protect this layer, data encryption at rest and transit should be used.
  • Configuration: Sensitive configuration data for an application includes environment variables, application settings, secrets, and API keys required for the application to function. Lapses in configuration settings could lead to data leaks, privilege escalation, or compromised application behavior.
  • Application code: Vulnerabilities in application code can lead to exploits, such as SQL injection or remote code execution. To prevent this, users should conduct regular static and dynamic code analysis, promptly patch vulnerabilities, and update dependencies to the latest secure versions.
  • Dependencies: Code dependencies include libraries, frameworks, and external packages that the application relies on. Vulnerable or outdated dependencies are one of the most common entry points for attackers. To prevent this, users should regularly scan dependencies for vulnerabilities.
  • Containers: The container runtime and images could also create another threat vector, as misconfigured or untrusted containers can escalate privileges, attack the host, or expose sensitive information. To prevent this, users could use image signing to verify the authenticity of images and implement runtime security using tools such as Falco to watch out for malicious behavior.
  • Host: This is the underlying server or node where containers are deployed. The host kernel is shared among all containers, making it a critical security layer. If the host is compromised, all containers can be affected. To prevent this, it is recommended to harden the host operating system by disabling unused services, applying patches, and using container-optimized operating systems, such as Bottlerocket.

In this section, we learned about the concept of defense in depth, a strategy that implements multiple layers of security to protect against threats across different attack vectors. We also looked at a conceptual view of various attack vectors and best practices in each layer. In the next section, let’s look at key security considerations when deploying workloads in K8s.

Now that we have covered the concept of defense in depth at a high level, let’s discuss containers and K8s security best practices. Thinking about container security is critical in the cloud environment, as containers operate in a dynamic and shared environment.

Containers encapsulate software and dependencies making them highly portable; however, this portability also introduces a set of risks. A comprehensive security strategy should address vulnerabilities across the container lifecycle – from build pipelines to runtime environments.

Key areas of focus include securing the supply chain, protecting the host system, and monitoring runtime activity. Each layer of security adds resilience against potential threats, and by following the best practices, one can ensure the safe deployment and operation of containers.

The following are some of the key areas we will dive deeper into as part of this container security:

  • Supply chain security
  • Host security
  • Runtime security
  • Network security
  • Secrets management

The container supply chain encompasses all the stages from building an image to deploying and monitoring it in production, as shown in Figure 9*.2*.

Figure 9.2 – Container supply chain

Now, let’s discuss the first five phases and their corresponding security best practices.

During the build phase, malicious/vulnerable code can enter the container image through unverified dependencies or insecure configurations. To secure the build phase, one should only use trusted base images from verified sources. To minimize the attack surface and improve security, consider using lightweight parent images for your containers. Alpine Linux (https://hub.docker.com/_/alpine), distroless (https://www.docker.com/blog/is-your-container-image-really-distroless/), or scratch (https://hub.docker.com/_/scratch) images have fewer built-in packages, limiting the potential vulnerabilities, and are generally recommended.

DockerSlim (https://github.com/slimtoolkit/slim) is an open source tool that helps optimize container images by reducing their size, thus improving security by identifying only the parts that are required at runtime. This significantly reduces the attack surface and enhances performance without altering the functionality of the containerized application.

It is also recommended to enforce the immutability of container images by using declarative Dockerfiles and reproducible builds. An immutable tag refers to a container image tag that cannot be changed or updated once it is created and pushed to a container registry. This ensures that the image associated with the tag remains fixed and consistent over time, preventing unintentional or malicious changes. For example, the latest tag is mutable, meaning it can point to different images over time as new images are pushed, whereas a tag such as v1.0 is immutable, as it ensures that it always references the same image, regardless of future pushes. Immutability is particularly beneficial for GenAI applications to ensure the training/fine-tuning jobs and inference images are built against a consistent environment, maintain model integrity, and simplify troubleshooting efforts.

A multi-stage build (https://docs.docker.com/build/building/multi-stage/) is a technique used in the build phase that allows you to break down the build process into multiple discrete stages. Each stage can focus on a specific task using an appropriate parent image, such as compiling code or installing dependencies, and then selectively copy only the necessary artifacts into the final, minimal image.

For GenAI applications, multi-stage builds help ensure that large training frameworks, data preprocessing scripts, or model optimization steps can selectively be excluded from the final production image. This results in smaller, more secure, and efficient images that can be quickly deployed for inference.

Undetected vulnerabilities and misconfigurations in images can lead to issues downstream. To mitigate this, it is recommended to integrate automated security testing into CI/CD pipelines with tools such as Snyk (https://snyk.io/). You should perform static analysis on code and dynamic testing on built images to uncover vulnerabilities. Ensure that your testing process also covers compliance with internal security policies and relevant industry standards. Incorporate test cases to assess resource usage, verify adherence to least-privilege principles, and monitor runtime behaviors. By doing so, you can help maintain secure, compliant, and predictable operations throughout the software lifecycle.

During the image store phase in container registries, images can be tampered with or can contain outdated dependencies. To safely secure images, it is recommended to use secured container registries such as Amazon ECR (https://aws.amazon.com/ecr/).

You should also enable image signing and verification using tools such as Docker Content Trust or Cosign. AWS Signer (https://docs.aws.amazon.com/signer/latest/developerguide/Welcome.html) is a fully managed service that allows you to digitally sign code, applications, and containers to ensure the integrity and authenticity of your software.

To ensure that only signed container images are deployed in production, a policy-as-code solution such as Open Policy Agent (OPA) or its K8s-native implementation, OPA Gatekeeper (https://github.com/open-policy-agent/gatekeeper), is recommended. OPA Gatekeeper is an open source project that leverages OPA to enforce policies in K8s clusters. It enables administrators to implement fine-grained governance by validating and mutating K8s resources against predefined constraints. Gatekeeper uses custom resource definitions (CRDs) to define these policies and constraints, allowing users to tailor governance to their specific needs. It operates as an admission controller, ensuring that any resource not complying with the defined rules is denied during creation or updates. Additionally, it supports auditing capabilities, enabling users to identify and remediate policy violations in existing resources. Role-based access control (RBAC) is also recommended to restrict access to images, and users should regularly clean up unused or deprecated images to reduce potential attack surfaces.

Sensitive data in images should always be intercepted. One should avoid embedding secrets (e.g., API keys or passwords) directly in images to prevent leaks in case of a potentially compromised container image.

You can use secret management tools such as HashiCorp Vault (https://www.hashicorp.com/products/vault), Kubernetes Secrets (https://kubernetes.io/docs/concepts/configuration/secret/), or AWS Secrets Manager (https://docs.aws.amazon.com/secretsmanager/latest/userguide/intro.html) to store the secrets. For example, AWS Secrets Manager is a secure service for managing secrets, such as database credentials, API keys, and other sensitive configuration data. By encrypting secrets with AWS Key Management Service (AWS KMS) and enabling fine-grained access control through AWS Identity and Access Management (AWS IAM), Secrets Manager ensures that sensitive data is protected and accessible only to authorized users and applications. It also supports version control and the automatic rotation of secrets, reducing the risks of credential exposure and minimizing manual overhead.

To integrate external secret management solutions with K8s, you can use projects such as secrets-store-csi-driver (https://github.com/kubernetes-sigs/secrets-store-csi-driver), which allows K8s to mount multiple secrets, keys, and certificates stored in external secrets stores into K8s Pods as a volume. Once the volume is attached, the data in it is mounted into the container’s filesystem. Refer to the AWS documentation at https://docs.aws.amazon.com/secretsmanager/latest/userguide/integrating_csi_driver.html for an example walkthrough of using AWS Secrets Manager in an Amazon EKS cluster. In the case of GenAI applications, external API keys from Hugging Face and OpenAI can safely be stored in these solutions, and applications can securely access them during the runtime.

Vulnerabilities in images or dependencies can lead to exploitation by bad actors. To prevent this, images should be continuously scanned during the build and store phases. Most container registry solutions provide this capability out of the box, or open source tools such as Trivy (https://github.com/aquasecurity/trivy) can be used to scan container images for vulnerabilities. These tools identify potential risks by analyzing image layers against known vulnerability databases (e.g., CVE databases), providing early detection of issues.

In cloud environments, more advanced image scanning options are also available. For example, Amazon ECR supports advanced vulnerability scanning through Amazon Inspector (https://aws.amazon.com/inspector/), a managed service designed to automate security assessments. This integration provides enhanced, continuous scanning for container images in ECR, ensuring they remain secure throughout their lifecycle. Amazon Inspector can scan container images in ECR automatically, without requiring manual triggers, whenever a new image is pushed or updated. Refer to the Amazon ECR documentation at https://docs.aws.amazon.com/AmazonECR/latest/userguide/image-scanning.html to learn more about these options and how to enable them on your container repositories.

Securing the host environment for containers is critical, as multiple containers can share the host operating system and kernel. The following are some of the best practices and strategies for securing container hosts:

  • Deploy in private subnets: Deploying hosts/worker nodes in private subnets minimizes exposure to external threats by restricting direct access from the internet. To expose applications to the public internet, deploy load balancer resources in public subnets using K8s load balancer or Ingress resource types.
  • Disable SSH access: SSH access should be limited to minimizing the attack vector. Instead, session management tools such as AWS Systems Manager (SSM) (https://aws.amazon.com/systems-manager/) should be used for secure, auditable access to hosts without exposing SSH. If SSH is necessary, enforce key-based authentication and restrict access using security groups.
  • Block the Instance Metadata Service (IMDS): The IMDS provides data about your EC2 instance that can expose sensitive information (e.g., IAM credentials) to malicious actors if not properly secured. It is recommended to use IMDSv2 (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-metadata.html) instead, which requires session tokens for accessing instance metadata. To restrict IMDS access to containerized applications, you can set the hop limit to 1 and enforce the usage of IMDSv2, as shown in the following Terraform code:
    resource "aws_launch_template" "example" {
    name = "example"
    ...
    metadata_options {
    http_endpoint = "enabled"
    http_tokens = "required"
    http_put_response_hop_limit = 1
    instance_metadata_tags = "enabled"
    }
    ...
  • Encrypt all storage: Encrypting storage protects sensitive data on the host in case of physical or logical compromise. Use AWS KMS to encrypt Amazon Elastic Block Store (Amazon EBS) volumes attached to the host. If using EC2 instances with an NVMe instance store, all the data is encrypted using an XTS-AES-256 block cipher.
  • Harden the node Amazon Machine Image (AMI): A hardened AMI reduces vulnerabilities by including only the necessary software, configurations, and security settings. Use container-optimized operating systems such as Bottlerocket (https://aws.amazon.com/bottlerocket/), which are built from the ground up with containers in mind. They often include features such as a read-only root filesystem, atomic updates, and minimal tooling tailored to running containers efficiently and securely. You should disable and uninstall unused software to reduce the attack surface and configure the operating system according to CIS benchmarks for Docker, Kubernetes, and Linux. Use AppArmor (https://apparmor.net/), SELinux (https://www.redhat.com/en/topics/linux/what-is-selinux), or seccomp (https://kubernetes.io/docs/tutorials/security/seccomp/) to restrict container privileges.

Securing containers at runtime is critical to prevent privilege escalations and unauthorized access. This involves limiting resources, restricting privileges, enforcing security standards, and integrating monitoring and policy tools. The following are the core runtime security practices:

  • Provide only the resources required for normal operation: Unrestricted resource allocation can lead to denial-of-service (DoS) attacks and cluster instability, where some containers can consume entire node resources. To prevent this, you should define CPU and memory limits in K8s manifests reflecting the optimal resources a container might need.
  • Restrict root and privileged access: Containers running as root or in privileged mode can lead to host compromise. To prevent this, ensure containers are configured to run as a non-root user in securityContext, as
    securityContext:
    runAsUser: 1000
    runAsGroup: 1000
    allowPrivilegeEscalation: false
  • Drop all unnecessary Linux capabilities: Linux capabilities grant elevated permissions that can be exploited if unused capabilities are left enabled. So, it is recommended to drop unnecessary capabilities in securityContext, as
    securityContext:
    capabilities:
    drop:
    - ALL
    ...
  • Follow Pod Security Standards: Adherence to Pod Security Standards ensures that containers comply with best practices for security configurations. Use the K8s built-in Pod Security Admission to enforce standards such as restricted profiles. Also, isolate workloads using namespaces with different security levels (e.g., restricted or baseline). Pod Security Standards define three different policy levels (privileged, baseline, and restricted) to broadly cover the security spectrum. You can apply labels and annotations on namespaces to specify the desired level of security configuration, as
    $ kubectl label namespace test-ns \
    pod-security.kubernetes.io/enforce=restricted
  • Monitor the runtime: This provides active protection for containerized workloads while they are running. The goal is to detect and/or prevent malicious activity from occurring inside the containers and the worker nodes. Tools such as Falco (https://github.com/falcosecurity/falco) provide real-time monitoring and anomaly detection for container behavior. It can be deployed as a DaemonSet in a K8s cluster and can monitor containers for suspicious activity. It operates by hooking into the Linux kernel using either eBPF or traditional syscalls, allowing it to observe low-level system activity inside running containers and Pods without modifying the workload itself. This deep visibility enables Falco to monitor unexpected or suspicious behavior in real time. Common events that Falco watches for include actions such as shells being spawned inside containers, modifications to sensitive files such as /etc/passwd or /etc/shadow, and network connections to untrusted IP addresses. It can also detect when a Pod tries to access a K8s Service account token improperly, which may indicate a compromise or misconfiguration. When such behavior violates its defined security rules, Falco triggers alerts instantly. For example, alerts may look like this: Terminal shell detected in nginx container or Suspicious file access by unknown process. To make these alerts actionable, teams should implement clear response strategies, such as isolating the Pod, initiating incident response procedures, or alerting security teams. Combining these technical capabilities with practical workflows allows teams to confidently enforce runtime security and respond to threats in production-grade K8s environments. Some other third-party tools also offer advanced runtime protection, integration, and reporting capabilities. Use agents provided by solutions such as Prisma Cloud’s Container Security (https://www.paloaltonetworks.com/prisma/cloud/container-security), Aqua Security (https://www.aquasec.com/products/kubernetes-security/), or Wiz container security (https://www.wiz.io/solutions/container-and-kubernetes-security) to monitor and protect containers.

Network security in K8s is critical for securing data and applications in a containerized environment. The distributed nature of K8s presents unique challenges for securing network traffic. The following are some key considerations and best practices for ensuring network security in K8s:

  • Network segmentation and isolation: K8s namespaces provide a way to isolate resources and workloads within a cluster, acting as separate security boundaries. Network segmentation can be enforced using NetworkPolicy resources, discussed in Chapter 8, which define rules for controlling ingress (incoming) and egress (outgoing) traffic at the Pod level.
  • Securing Pod-to-Pod communication: By default, K8s allows communication between Pods, which can expose K8s clusters to security risks. Implementing zero-trust principles ensures that Pods communicate only with explicitly authorized peers. Service mesh technologies such as Istio or Linkerd provide mTLS for encryption and authentication, ensuring secure and authenticated Pod-to-Pod communication.
  • Ingress and egress security: Ingress security focuses on controlling and securing incoming traffic to the cluster, often using HTTPS with TLS certificates for encryption. Additional protection, such as web application firewalls (WAFs), help detect and block malicious traffic. Egress security involves restricting Pods’ outbound traffic to prevent unauthorized access to external resources, which can be enforced using egress policies.
  • API server protection: The K8s API server is a critical management point, requiring strong security measures. RBAC restricts user permissions based on roles, while authentication mechanisms such as OpenID Connect (OIDC) or AWS IAM ensure that only authorized users access the server. Network policies or firewalls should further limit access to the API server from trusted sources only.
  • DNS security: CoreDNS, the default DNS server in K8s, should be secured against spoofing and related attacks. While enabling encrypted DNS protocols such as DNS-over-TLS or DNS-over-HTTPS (https://www.cloudflare.com/learning/dns/dns-over-tls/) is technically possible, it is not commonly implemented by default in K8s. Instead, use network policies to restrict which Pods can query the CoreDNS server, thereby reducing the risk of unauthorized requests. Additionally, ensure CoreDNS points to trusted upstream resolvers, employing DNSSEC (https://www.internetsociety.org/deploy360/dnssec/basics/) for integrity.
  • Network monitoring: Monitoring network traffic is crucial for detecting and mitigating threats. Tools such as Cilium, Calico, Sysdig, service meshes, or Datadog provide visibility into cluster traffic, enabling cluster administrators to identify suspicious behavior.
  • Securing external connections: Connections to external services, such as cloud provider services or databases, should be encrypted and authenticated. K8s Secrets offer a secure way to manage credentials for external connections, ensuring that sensitive information (such as API keys and passwords) remains protected from unauthorized access.

Secrets management in K8s is a critical component for securing and managing sensitive information, such as API keys, passwords, certificates, and tokens. K8s provides built-in mechanisms to manage Secrets but securing them requires careful configuration and the following best practices to mitigate risks of unauthorized access or accidental exposure:

  • K8s Secrets resource: K8s provides a native resource called Secrets, which is used to store sensitive data in a Base64-encoded format. Secrets are mounted into Pods as environment variables or files, enabling applications to access them without embedding sensitive data directly in container images or configuration files. While convenient, the Base64 encoding is not encryption, so additional security measures are necessary.
  • Encrypting Secrets at rest: By default, K8s stores Secrets in etcd, the cluster’s key-value store. To protect this sensitive information, it is essential to enable encryption at rest for etcd. When using managed K8s services such as Amazon EKS, etcd volumes are encrypted by default using AWS managed encryption keys. As an additional security measure, you can also use techniques such as envelope encryption to encrypt the Secret values before writing to the etcd database. In Amazon EKS, you can utilize AWS KMS to enable envelope encryption; refer to the AWS documentation at https://docs.aws.amazon.com/eks/latest/userguide/envelope-encryption.html to learn more.
  • Access control with RBAC: RBAC is a fundamental part of securing Secrets in K8s. RBAC policies should enforce the principle of least privilege, granting users, Pods, and Services access only to the Secrets they need. Properly configured roles and role bindings help prevent unauthorized users or applications from accessing sensitive information.
  • Using external secret management tools: While K8s Secrets offer a convenient mechanism, many organizations opt for external secret management solutions for enhanced security. Tools such as HashiCorp Vault or AWS Secrets Manager provide centralized secret storage with advanced features such as encryption, auditing, and fine-grained access control. These tools can integrate with K8s through the secrets-store-csi-driver plugin or other operators, enabling seamless access to externally managed secrets.
  • Automating Secret rotation: Rotating Secrets regularly reduces the risk of long-term compromise. K8s secrets do not natively support automatic rotation, but external secret management tools often include this capability. Integrating such tools into K8s workflows allows you to periodically update secrets without disrupting applications, ensuring compliance with security best practices.
  • Protecting Secrets in transit: Sensitive data, including secrets, must be protected as it travels between clients, nodes, and the etcd store. Enable TLS encryption when exchanging sensitive credentials both with internal and external systems.
  • Auditing and monitoring access to Secrets: Audit logging is essential for monitoring access to secrets and detecting potential misuse. K8s can generate audit logs for API actions, including those involving secrets. Integrating these logs with centralized monitoring tools or security information and event management (SIEM) solutions helps administrators detect suspicious activity and respond promptly. Secret management tools also provide audit logs, which can be integrated into SIEM solutions.

In this section, we looked at various security considerations when running containerized workloads in K8s, including supply chain security, host security, network security, and the importance of securing sensitive information using K8s Secrets. In the next section, let’s explore additional security considerations specific to GenAI applications.

Deploying GenAI applications on K8s often involves proprietary model artifacts, large volumes of sensitive training data, and sophisticated inference requests that can originate from untrusted sources. Beyond the standard practices of K8s security, you must consider new attack vectors related to model integrity, data privacy, software supply chain vulnerabilities, and the isolation of high-value hardware resources such as GPUs. Let’s explore some of those considerations now:

GenAI models often rely on proprietary and sensitive datasets stored in data lakes, data hubs, and data warehouses for training and fine-tuning. In our walkthrough (Chapter 5), we used Amazon S3 buckets to store the datasets used during the fine-tuning process. Depending on the data classification and regulatory requirements, you must implement appropriate security controls such as data encryption at rest, strict access control policies, and auditing. When accessing these data repositories from GenAI applications running on K8s, ensure that all communications are encrypted using TLS and follow the principle of least privilege by leveraging K8s and related mechanisms. When running GenAI applications on Amazon EKS, you can leverage IAM Roles for Service Accounts (IRSA) (https://docs.aws.amazon.com/eks/latest/userguide/iam-roles-for-service-accounts.html) or EKS Pod Identity (https://docs.aws.amazon.com/eks/latest/userguide/pod-identities.html) features to obtain temporary IAM credentials and access data from other services such as Amazon S3.

IRSA was introduced in 2019 to associate fine-grained IAM roles with K8s service accounts. Applications running in K8s Pods can assume the role using their service account identity and access other AWS services based on the role permissions.

The following are the high-level steps involved in the process; refer to the Amazon EKS documentation at https://docs.aws.amazon.com/eks/latest/userguide/iam-roles-for-service-accounts.html for detailed guidance:

  1. Set up an OIDC provider in AWS IAM for the Amazon EKS cluster.
  2. Create fine-grained IAM policies to grant necessary permissions on AWS services. Refer to the security best practices documentation at https://docs.aws.amazon.com/IAM/latest/UserGuide/best-practices.html#grant-least-privilege for guidance on creating IAM policies.
  3. Create an IAM role with the permission policies from Step 2 and a trust policy for the K8s service account to the
    ...
    "Effect": "Allow",
    "Principal": {
    "Federated": "arn:aws:iam::<account_id>:oidc-provider/<oidc_provider>"
    },
    "Action": "sts:AssumeRoleWithWebIdentity",
    "Condition": {
    "StringEquals": {
    "<oidc_provider>:aud": "sts.amazonaws.com",
    "<oidc_provider>:sub": "system:serviceaccount:<namespace>:<service_account>"
    ...
  4. Create a K8s service account and annotate it with the IAM role from
    apiVersion: v1
    kind: ServiceAccount
    metadata:
    name: example-sa
    namespace: example-ns
    annotations:
    eks.amazonaws.com/role-arn: arn:aws:iam::<account_id>:role/<iam_role_name>
  5. Deploy the K8s application using the annotated
    apiVersion: apps/v1
    kind: Deployment
    metadata:
    name: example-app
    ...
    spec:
    serviceAccount: example-sa
    containers:
    - name: example-container
    ...
  6. When an application uses the AWS SDK to access other AWS resources, the SDK will invoke AssumeRoleWithWebIdentity, an AWS Security Token Service (STS) API operation that allows an application to assume an IAM role using a trusted web identity token, instead of long-lived access keys or IAM users, to fetch temporary IAM credentials. Figure 9*.3* summarizes these steps:

Figure 9.3 – Overview of IRSA

This illustrates how IAM roles are securely assumed by Pods in an Amazon EKS cluster using IRSA and the AssumeRoleWithWebIdentity (https://docs.aws.amazon.com/STS/latest/APIReference/API_AssumeRoleWithWebIdentity.html) mechanism. When a Pod associated with an annotated service account is created, the Pod Identity webhook running in the EKS control plane mutates the Pod specification to mount the projected service account token. The AWS SDK running in the Pod then uses that token to call AWS STS using the AssumeRoleWithWebIdentity API. STS verifies the token against the OIDC provider, checks the IAM role’s trust policy, and returns temporary AWS credentials, which the Pod uses to securely access other AWS resources.

Next, we will cover the recently introduced EKS Pod Identity feature, which further simplifies the IAM permission process.

In 2023, AWS introduced the EKS Pod Identity feature as an evolution to IRSA to streamline the experience of setting up IAM permissions for K8s applications. It removed a lot of underlying complexities of IRSA, such as setting up OIDC providers in IAM, complex trust policies, annotating service accounts, and so on. EKS Pod Identity introduced new APIs to create Pod Identity associations between K8s service accounts and IAM roles, thus eliminating the need for OIDC providers, service account annotations, and so on. The high-level steps involved are as follows:

  1. Install eks-pod-identity-agent deamonset on the EKS cluster.
  2. Create fine-grained IAM policies granting necessary permissions on AWS services.
  3. Create an IAM role with the permission policies from Step 2 and a trust policy for the EKS Pod Identity principal to the
    ...
    "Effect": "Allow",
    "Principal": {
    "Service": "pods.eks.amazonaws.com"
    },
    "Action": [
    "sts:AssumeRole",
    "sts:TagSession"
    ...
  4. Create a Pod Identity association between the IAM role and the K8s
    aws eks create-pod-identity-association --cluster-name my-cluster --role-arn arn:aws:iam::<account_id>:role/my-role --namespace <namespace> --service-account <service_account>
  5. Deploy the K8s application using the
    apiVersion: apps/v1
    kind: Deployment
    metadata:
    name: example-app
    ...
    spec:
    serviceAccount: example-sa
    containers:
    - name: example-container
    ...

EKS Pod Identity also introduced support for session tags to the temporary credentials assigned to each Pod, including attributes such as the cluster name, namespace, Pod UID, service account name, and so on. These tags allow administrators to configure a single IAM role that can be used across various service accounts, granting or restricting access to AWS resources based on matching tags. By incorporating role session tags, organizations can create more granular security boundaries between clusters and workloads, while continuing to leverage the same IAM roles and policies.

Before we talk about securing GenAI model endpoints, we should secure the fine-tuned model artifacts, model weights, and so on. After the fine-tuning process, you can securely store those model artifacts in object store services such as Amazon S3 using appropriate access controls, or package them along with the container image and push it to the container registry. You can securely source the credentials using one of the previously discussed approaches (IRSA or EKS Pod Identity) to access the respective AWS services.

Once the models are built, inference endpoints are created by deploying them as K8s deployments/Pods and exposing them via K8s Service or Ingress objects. Securing the model endpoints starts by implementing robust network and API-level protection. Enforce TLS for all communications to ensure data is encrypted in transit and verify the authenticity of clients and services using appropriate authentication methods. You can create the TLS endpoints by issuing or importing TLS certificates in the AWS Certificate Manager (ACM) (https://aws.amazon.com/certificate-manager/) service and deploying them on the AWS Application Load Balancer (ALB) or Network Load Balancer (NLB) resources. You can use annotations, as shown in the following code snippet, to create a secure port such as 443 and deploy TLS certificates from ACM on the K8s load balancer service:

apiVersion: v1
kind: Service
metadata:
name: example-service
annotations:
service.beta.kubernetes.io/aws-load-balancer-type: "external"
# Reference the ACM certificate ARN for TLS termination at the load balancer
service.beta.kubernetes.io/aws-load-balancer-ssl-cert: "arn:aws:acm:us-east-1:<account_id>:certificate/<certificate_id>"
# The port(s) that should use SSL/TLS
service.beta.kubernetes.io/aws-load-balancer-ssl-ports: "443"
spec:
type: LoadBalancer
...

Similarly, you can apply the annotations to a K8s Ingress resource backed by the AWS ALB to create an HTTPS listener secured with a TLS certificate from ACM, as shown in the following code snippet:

apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name: example-ingress
annotations:
# Define which ports the ALB should listen on; here we set HTTPS on port 443
alb.ingress.kubernetes.io/listen-ports: '[{"HTTPS":443}]'
# The ARN of the ACM certificate for TLS termination
alb.ingress.kubernetes.io/certificate-arn: "arn:aws:acm:us-east-1:<account_id>:certificate/<certificate_id>"
...

Additionally, you can attach AWS WAF (https://aws.amazon.com/waf/) to the AWS ALB (K8s Ingress resource) to protect the model endpoints against common attack vectors, including injection attacks, malicious content inputs, and so on. You can use the following annotation to attach AWS WAF with AWS ALB.

alb.ingress.kubernetes.io/wafv2-acl-arn: arn:aws:wafv2:us-west-2:xxxxx:regional/webacl/xxxxxxx/yyyyyyyyy

In this section, we explored best practices for deploying GenAI workloads in K8s. We looked at the IRSA and EKS Pod Identity features to securely provide temporary IAM credentials to K8s applications. This is particularly important for GenAI applications, as it ensures secure, least-privilege access to sensitive training data or model artifacts stored in Amazon S3. We also looked at techniques for protecting model endpoints, including enforcing TLS for encrypted communications and integrating a WAF to defend against common attack vectors. In the next section, we will implement these security best practices in our chatbot application.

Implementing security best practices in a chatbot app

Section titled “Implementing security best practices in a chatbot app”

In this section, we will implement the security best practices discussed in the previous sections in our e-commerce chatbot application. We already implemented some of these in previous chapters, such as IRSA in Chapter 5, and K8s network policies in Chapter 8. Let’s get started:

  • Container image encryption: Amazon ECR stores container images in Amazon S3 buckets that ECR manages and, by default, uses the server-side encryption feature of S3 to encrypt the data at rest. It uses the Advanced Encryption Standard (AES) encryption algorithm using encryption keys managed by the S3 service. We can verify this on the ECR repositories we created using the following AWS command:
    $ aws ecr describe-repositories --repository-names my-llama-finetuned --query 'repositories[0].encryptionConfiguration.encryptionType' --output text
    AES256
    Additionally, you can use AWS KMS to create customer-managed KMS keys and use them for encrypting the container images at rest. To achieve this, use the following Terraform code, which creates a new KMS customer-managed key with an alias of ecr-kms-key and configures the sample-app-repo ECR repository to use it for encryption:
    resource "aws_kms_key" "ecr_kms_key" {
    deletion_window_in_days = 7
    enable_key_rotation = true
    }
    resource "aws_kms_alias" "ecr_kms_alias" {
    name = "alias/ecr-kms-key"
    target_key_id = aws_kms_key.ecr_kms_key.key_id
    }
    resource "aws_ecr_repository" "sample-app-repo" {
    name = "sample-app-repo"
    encryption_configuration {
    encryption_type = "KMS"
    kms_key = aws_kms_key.ecr_kms_key.arn
    }
    }
  • Tag immutability: This ensures that once a container image is pushed to an ECR repository, its tag cannot be overwritten. This practice prevents accidental or malicious updates to your application images, ensuring consistency across deployments. You can enable this by setting the image_tag_mutability attribute to IMMUTABLE in the ecr.tf file, as shown in the following code snippet:
    resource "aws_ecr_repository" "my-llama-finetuned" {
    name = "my-llama-finetuned"
    image_tag_mutability = "IMMUTABLE"
    }
  • Container image scanning: Enable the enhanced image scanning feature of Amazon ECR to automatically detect vulnerabilities in the container images. Add the following code snippet to the ecr.tf file, which enables enhanced scanning on the my-llama-finetuned ECR repository in our AWS account. Alternatively, you can download the source code from the GitHub repository at https://github.com/PacktPublishing/Kubernetes-for-Generative-AI-Solutions/blob/main/ch9/ecr.tf This configuration ensures that images are scanned both when they are pushed and continuously thereafter for any new vulnerabilities:
    resource "aws_ecr_registry_scanning_configuration" "ecr_scanning_configuration" {
    scan_type = "ENHANCED"
    rule {
    scan_frequency = "CONTINUOUS_SCAN"
    repository_filter {
    filter = "my-llama-finetuned"
    filter_type = "WILDCARD"
    }
    }
    rule {
    scan_frequency = "SCAN_ON_PUSH"
    repository_filter {
    filter = "my-llama-finetuned"
    filter_type = "WILDCARD"
    }
    }
    }
    Run the following Terraform commands to apply this configuration in your AWS account:
    $ terraform plan
    $ terraform apply -auto-approve
    Once applied, Amazon ECR will continuously scan the container images pushed to the my-llama-finetuned repository and display the vulnerabilities in the AWS console.
  • Host security: Harden the security of the worker nodes by using a purpose-built operation system such as Bottlerocket. This includes only the essential software required to run containers and ensures that the underlying software is always secure. It also improves the node start-up time from ~1.5 minutes to 20 seconds, based on a customer case study (https://aws.amazon.com/bottlerocket/). Additionally, configure the worker nodes to use the latest version of IMDSv2 (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-metadata.html) to limit access to sensitive metadata. The following code snippet highlights the use of Bottlerocket EKS AMIs and IMDSv2; the complete source code is available in the GitHub repository at https://github.com/PacktPublishing/Kubernetes-for-Generative-AI-Solutions/blob/main/ch9/eks.tf:
    module "eks" {
    source = "terraform-aws-modules/eks/aws"
    ...
    eks_managed_node_groups = {
    eks-mng = {
    ami_type = "BOTTLEROCKET_x86_64"
    metadata_options {
    http_endpoint = "enabled"
    http_tokens = "required"
    http_put_response_hop_limit = 1
    }
    ...
    eks-gpu-mng = {
    ami_type = "BOTTLEROCKET_x86_64_NVIDIA"
    ...
  • K8s Pod Security Standards: Implementing K8s Pod Security Standards is critical to ensuring your workloads operate with the least privilege, thereby reducing the risk of privilege escalation and container escapes. Since our chatbot application is deployed in the default namespace, we can use the following command to enforce a baseline security policy while receiving warnings for more restrictive settings:
    $ kubectl label namespace default pod-security.kubernetes.io/enforce=baseline pod-security.kubernetes.io/warn=restricted pod-security.kubernetes.io/audit=restricted
    Test the enforced policy by attempting to run a pod with privileged settings using the following command:
    $ kubectl run pss-demo --image=nginx --privileged
    Error from server (Forbidden): pods "pss-demo" is forbidden: violates PodSecurity "baseline:latest": privileged (container "pss-demo" must not set securityContext.privileged=true)
    The preceding error confirms that the baseline policy is effectively preventing the creation of Pods with elevated privileges.
  • K8s Secrets management: A K8s Secret is an object that is designed to store sensitive data such as API Keys, passwords, TLS certificates, and so on. Using K8s Secrets means you don’t have to embed confidential information directly in your deployment manifests. In our setup, we included a Hugging Face access token in the K8s manifest when deploying the fine-tuning job and my-llama-finetuned inference endpoint. In this walkthrough, we’ll enhance security by storing the Hugging Face token in AWS Secrets Manager. We’ll then use secrets-store-csi-driver to dynamically retrieve and inject the secret into the K8s Pod during creation. Let’s
    1. Store the Hugging Face access token in AWS Secrets Manager and run the following command to create a secret in your AWS account. Replace the value with your access token created in the Hugging
      $ export HUGGING_FACE_TOKEN=<<Your Token goes here>>
      $ aws secretsmanager create-secret --name hugging-face-secret --secret-string "$HUGGING_FACE_TOKEN"
      1. Deploy the secrets-store-csi-driver and secrets-store-csi-provider-aws add-ons in the EKS cluster to integrate external secret stores with K8s via a Container Storage Interface (CSI) volume. These add-ons allow K8s to mount multiple secrets, keys, and certificates stored in enterprise-grade external secrets stores directly into your Pods. Specifically, secrets-store-csi-provider-aws integrates AWS Secrets Manager and AWS Systems Manager Parameter Store with Kubernetes. To set up these add-ons in your EKS cluster, download the addons.tf file from the GitHub repository at https://github.com/PacktPublishing/Kubernetes-for-Generative-AI-Solutions/blob/main/ch9/addons.tf and run the following commands:
      $ terraform init
      $ terraform plan
      $ terraform apply -auto-approve
      You can confirm the installation by listing the DaemonSets in the kube-system namespace using the following command; you will notice secrets-store-csi-driver and secrets-store-csi-driver-provider-aws in the output:
      $ kubectl get ds -n kube-system
      NAME
      secrets-store-csi-driver
      secrets-store-csi-driver-provider-aws
      1. Next, create an IAM role with permission policies based on least privilege access principles granting read access to only the Hugging Face secret. Once the role is created, associate it with the K8s service account so that the my-llama-finetuned K8s Pod can receive temporary IAM credentials using the EKS Pod Identity feature. To set up these resources, download the iam.tf file from the GitHub repository at https://github.com/PacktPublishing/Kubernetes-for-Generative-AI-Solutions/blob/main/ch9/iam.tf and run the following commands:
      $ terraform init
      $ terraform plan
      $ terraform apply -auto-approve
      You can verify the Pod Identity association using the following AWS command, which will return the association ID, service account, and namespace in the response:
      $ aws eks list-pod-identity-associations --cluster-name eks-demo --query "associations[?serviceAccount=='my-llama-sa']"
      1. To use secrets-store-csi-driver, we need to configure SecretProviderClass, a custom Kubernetes resource that defines how secrets-store-csi-driver should connect to and retrieve secrets from external providers such as AWS Secrets Manager. Let’s create one for our setup to retrieve hugging-face-secret from AWS Secrets Manager. To create this, download the secret-provider-class.yaml file from the GitHub repository at https://github.com/PacktPublishing/Kubernetes-for-Generative-AI-Solutions/blob/main/ch9/inference/secret-provider-class.yaml and run the following command:
      $ kubectl apply -f secret-provider-class.yaml
      1. Finally, redeploy the my-llama-finetuned application using the my-llama-sa service account. This approach securely injects the AWS Secrets Manager secret into your application container without exposing it in the Kubernetes manifest. To redeploy the app, download the finetuned-inf-deploy.yaml file from the GitHub repository at https://github.com/PacktPublishing/Kubernetes-for-Generative-AI-Solutions/blob/main/ch9/inference/finetuned-inf-deploy.yaml. Then, update the ECR image name with your own and execute the following command:
      $ kubectl apply -f finetuned-inf-deploy.yaml
      You can confirm that the secret is properly injected by checking the Pod status or by executing the env command inside the Pod using the following commands:
      $ kubectl get pods -l app.kubernetes.io/name=my-llama-finetuned
      $ kubectl exec -it $(kubectl get pods -l app.kubernetes.io/name=my-llama-finetuned -o jsonpath="{.items[0].metadata.name}") -- env | grep HUGGING_FACE

In this section, we implemented multiple security best practices in our chatbot application running on EKS. We ensured ECR image immutability to prevent image tag overwrites, hardened host security using Bottlerocket AMIs, enabled IMDSv2, and applied Pod Security Standards to enforce least privilege execution. Additionally, we implemented encryption at rest, integrated vulnerability scanning to our container images in Amazon ECR, and enhanced Kubernetes secrets management through encrypted secrets and external solutions such as AWS Secrets Manager via secrets-store-csi-driver.

In this chapter, we covered the security best practices for deploying applications on K8s, with a focus on defense in depth and securing key aspects of the container ecosystem, including supply chain, host, network, runtime, and secret management.

Defense in depth is a concept that involves multiple layers of security to safeguard against different attack vectors.

Containers, being portable, introduce unique risks that require proactive measures at every lifecycle stage, from build to runtime. Supply chain security emphasizes securing container images during the build, test, and storage phases. Host security focuses on safeguarding the underlying server hosting containers. Runtime security ensures secure container operation by limiting privileges, enforcing resource limits, and using tools such as Falco for anomaly detection. Network security leverages namespaces, network policies, and service meshes such as Istio for segmentation and encryption. Secret management is essential for securely handling sensitive information. IRSA and EKS Pod Identity features can be used to securely provide temporary IAM credentials to K8s applications. GenAI workloads can leverage these features to securely access sensitive training data or export model artifacts in Amazon S3. GenAI model endpoints can be protected against common vectors using WAF solutions and enforcing TLS for encrypted communications. By integrating these best practices, K8s deployments can achieve robust security against evolving threats.

This chapter focused on K8s security best practices; in the next chapter, we will start diving into GPU resource optimization for K8s, which is one of the most expensive resources for GenAI applications.

Get This Book's PDF Version and Exclusive Extras