AWSCDK::EKS

106 types

Amazon EKS Construct Library

This construct library allows you to define Amazon Elastic Container Service for Kubernetes (EKS) clusters. In addition, the library also supports defining Kubernetes resource manifests within EKS clusters.

Table Of Contents

Quick Start

This example defines an Amazon EKS cluster with the following configuration:

require 'aws-cdk-lambda-layer-kubectl-v35'


# provisioning a cluster
cluster = AWSCDK::EKS::Cluster.new(self, "hello-eks", {
    version: AWSCDK::EKS::KubernetesVersion.V1_35,
    kubectl_layer: AWSCDK::LambdaLayerKubectlV35::KubectlV35Layer.new(self, "kubectl"),
})

# apply a kubernetes manifest to the cluster
cluster.add_manifest("mypod", {
    api_version: "v1",
    kind: "Pod",
    metadata: {name: "mypod"},
    spec: {
        containers: [
            {
                name: "hello",
                image: "paulbouwer/hello-kubernetes:1.5",
                ports: [{container_port: 8080}],
            },
        ],
    },
})

Architectural Overview

The following is a qualitative diagram of the various possible components involved in the cluster deployment.

 +-----------------------------------------------+               +-----------------+
 | EKS Cluster | kubectl |  |
 | ----------- |<-------------+| Kubectl Handler |
 |                                               |               |                 |
 |                                               |               +-----------------+
 | +--------------------+    +-----------------+ |
 | |                    |    |                 | |
 | | Managed Node Group |    | Fargate Profile | |               +-----------------+
 | |                    |    |                 | |               |                 |
 | +--------------------+    +-----------------+ |               | Cluster Handler |
 |                                               |               |                 |
 +-----------------------------------------------+               +-----------------+
    ^                                   ^                          +
    |                                   |                          |
    | connect self managed capacity     |                          | aws-sdk
    |                                   | create/update/delete     |
    +                                   |                          v
 +--------------------+                 +              +-------------------+
 |                    |                 --------------+| eks.amazonaws.com |
 | Auto Scaling Group |                                +-------------------+
 |                    |
 +--------------------+

In a nutshell:

A more detailed breakdown of each is provided further down this README.

Provisioning clusters

Creating a new cluster is done using the Cluster or FargateCluster constructs. The only required properties are the kubernetes version and kubectl_layer.

require 'aws-cdk-lambda-layer-kubectl-v35'


AWSCDK::EKS::Cluster.new(self, "HelloEKS", {
    version: AWSCDK::EKS::KubernetesVersion.V1_35,
    kubectl_layer: AWSCDK::LambdaLayerKubectlV35::KubectlV35Layer.new(self, "kubectl"),
})

You can control what happens to the resources created by the cluster construct when they are no longer managed by CloudFormation by specifying a removal_policy.

This can happen in one of three situations:

This affects the EKS cluster itself, the custom resource that created the cluster, associated IAM roles, node groups, security groups, VPC and any other CloudFormation resources managed by this construct.

require 'aws-cdk-lambda-layer-kubectl-v35'
require 'aws-cdk-lib'


AWSCDK::EKS::Cluster.new(self, "HelloEKS", {
    version: AWSCDK::EKS::KubernetesVersion.V1_35,
    kubectl_layer: AWSCDK::LambdaLayerKubectlV35::KubectlV35Layer.new(self, "kubectl"),
    removal_policy: AWSCDK::RemovalPolicy::RETAIN,
})

You can also use FargateCluster to provision a cluster that uses only fargate workers.

require 'aws-cdk-lambda-layer-kubectl-v35'


AWSCDK::EKS::FargateCluster.new(self, "HelloEKS", {
    version: AWSCDK::EKS::KubernetesVersion.V1_35,
    kubectl_layer: AWSCDK::LambdaLayerKubectlV35::KubectlV35Layer.new(self, "kubectl"),
})

You can enable deletion protection for your cluster to prevent accidental deletion. When deletion protection is enabled, the cluster cannot be deleted until protection is disabled. This setting only applies to clusters in an active state.

For more details visit Deletion protection.

require 'aws-cdk-lambda-layer-kubectl-v35'


AWSCDK::EKS::Cluster.new(self, "HelloEKS", {
    version: AWSCDK::EKS::KubernetesVersion.V1_35,
    kubectl_layer: AWSCDK::LambdaLayerKubectlV35::KubectlV35Layer.new(self, "kubectl"),
    deletion_protection: true,
})

NOTE: Only 1 cluster per stack is supported. If you have a use-case for multiple clusters per stack, or would like to understand more about this limitation, see https://github.com/aws/aws-cdk/issues/10073.

Below you'll find a few important cluster configuration options. First of which is Capacity. Capacity is the amount and the type of worker nodes that are available to the cluster for deploying resources. Amazon EKS offers 3 ways of configuring capacity, which you can combine as you like:

Managed node groups

Amazon EKS managed node groups automate the provisioning and lifecycle management of nodes (Amazon EC2 instances) for Amazon EKS Kubernetes clusters. With Amazon EKS managed node groups, you don't need to separately provision or register the Amazon EC2 instances that provide compute capacity to run your Kubernetes applications. You can create, update, or terminate nodes for your cluster with a single operation. Nodes run using the latest Amazon EKS optimized AMIs in your AWS account while node updates and terminations gracefully drain nodes to ensure that your applications stay available.

For more details visit Amazon EKS Managed Node Groups.

Managed Node Groups are the recommended way to allocate cluster capacity.

By default, this library will allocate a managed node group with 2 m5.large instances (this instance type suits most common use-cases, and is good value for money).

At cluster instantiation time, you can customize the number of instances and their type:

require 'aws-cdk-lambda-layer-kubectl-v35'


AWSCDK::EKS::Cluster.new(self, "HelloEKS", {
    version: AWSCDK::EKS::KubernetesVersion.V1_35,
    default_capacity: 5,
    default_capacity_instance: AWSCDK::EC2::InstanceType.of(AWSCDK::EC2::InstanceClass::M5, AWSCDK::EC2::InstanceSize::SMALL),
    kubectl_layer: AWSCDK::LambdaLayerKubectlV35::KubectlV35Layer.new(self, "kubectl"),
})

To access the node group that was created on your behalf, you can use cluster.defaultNodegroup.

Additional customizations are available post instantiation. To apply them, set the default capacity to 0, and use the cluster.addNodegroupCapacity method:

require 'aws-cdk-lambda-layer-kubectl-v35'


cluster = AWSCDK::EKS::Cluster.new(self, "HelloEKS", {
    version: AWSCDK::EKS::KubernetesVersion.V1_35,
    default_capacity: 0,
    kubectl_layer: AWSCDK::LambdaLayerKubectlV35::KubectlV35Layer.new(self, "kubectl"),
})

cluster.add_nodegroup_capacity("custom-node-group", {
    instance_types: [AWSCDK::EC2::InstanceType.new("m5.large")],
    min_size: 4,
    disk_size: 100,
})

To set node taints, you can set taints option.

cluster = nil # AWSCDK::EKS::Cluster

cluster.add_nodegroup_capacity("custom-node-group", {
    instance_types: [AWSCDK::EC2::InstanceType.new("m5.large")],
    taints: [
        {
            effect: AWSCDK::EKS::TaintEffect::NO_SCHEDULE,
            key: "foo",
            value: "bar",
        },
    ],
})

To define the type of the AMI for the node group, you may explicitly define ami_type according to your requirements, supported amiType could be found HERE.

cluster = nil # AWSCDK::EKS::Cluster


# X86_64 based AMI managed node group
cluster.add_nodegroup_capacity("custom-node-group", {
    instance_types: [AWSCDK::EC2::InstanceType.new("m5.large")],
     # NOTE: if amiType is x86_64-based image, the instance types here must be x86_64-based.
    ami_type: AWSCDK::EKS::NodegroupAmiType::AL2023_X86_64_STANDARD,
})

# ARM_64 based AMI managed node group
cluster.add_nodegroup_capacity("custom-node-group", {
    instance_types: [AWSCDK::EC2::InstanceType.new("m6g.medium")],
     # NOTE: if amiType is ARM-based image, the instance types here must be ARM-based.
    ami_type: AWSCDK::EKS::NodegroupAmiType::AL2023_ARM_64_STANDARD,
})

To define the maximum number of instances which can be simultaneously replaced in a node group during a version update you can set max_unavailable or max_unavailable_percentage options.

For more details visit Updating a managed node group

cluster = nil # AWSCDK::EKS::Cluster

cluster.add_nodegroup_capacity("custom-node-group", {
    instance_types: [AWSCDK::EC2::InstanceType.new("m5.large")],
    max_size: 5,
    max_unavailable: 2,
})
cluster = nil # AWSCDK::EKS::Cluster

cluster.add_nodegroup_capacity("custom-node-group", {
    instance_types: [AWSCDK::EC2::InstanceType.new("m5.large")],
    max_unavailable_percentage: 33,
})

NOTE: If you add instances with the inferentia class (inf1 or inf2) or trainium class (trn1, trn1n, or trn2) the neuron plugin will be automatically installed in the kubernetes cluster.

Default AMI type (under feature flag)

By default, managed node groups that do not set ami_type use AL2_X86_64 (or AL2_ARM_64 for ARM instances). Amazon Linux 2 EKS-optimized AMIs reached end of support on November 26, 2025. AL2023 is the AWS-recommended default.

New applications should enable the @aws-cdk/aws-eks:defaultToAL2023 feature flag in cdk.json:

{
  "context": {
    "@aws-cdk/aws-eks:defaultToAL2023": true
  }
}

When the flag is enabled, the default AMI type for x86_64 instances becomes AL2023_X86_64_STANDARD, and for ARM instances it becomes AL2023_ARM_64_STANDARD. GPU instances continue to default to AL2_X86_64_GPU because AL2023 splits GPU support into separate NVIDIA and Neuron AMI variants โ€” GPU users must pick a variant explicitly.

Migration for existing applications. Enabling this flag on an existing app will cause managed node groups that previously defaulted to AL2 to be replaced with AL2023 on the next deploy, which terminates running pods. To roll out safely, pin every existing node group to its current AMI type first, and only then enable the flag as shown below. Then gradually unpin the AMI for the nodes you want to upgrade.

cluster = nil # AWSCDK::EKS::Cluster


# Pin existing node groups to AL2 explicitly before enabling the flag.
cluster.add_nodegroup_capacity("workers", {
    instance_types: [AWSCDK::EC2::InstanceType.new("m5.large")],
    ami_type: AWSCDK::EKS::NodegroupAmiType::AL2_X86_64,
})

Explicitly setting ami_type will pin it โ€” it is not affected by the feature flag.

Node Groups with IPv6 Support

Node groups are available with IPv6 configured networks. For custom roles assigned to node groups additional permissions are necessary in order for pods to obtain an IPv6 address. The default node role will include these permissions.

For more details visit Configuring the Amazon VPC CNI plugin for Kubernetes to use IAM roles for service accounts

require 'aws-cdk-lambda-layer-kubectl-v35'


ipv6_management = AWSCDK::IAM::PolicyDocument.new({
    statements: [
        AWSCDK::IAM::PolicyStatement.new({
            resources: ["arn:aws:ec2:*:*:network-interface/*"],
            actions: [
                "ec2:AssignIpv6Addresses",
                "ec2:UnassignIpv6Addresses",
            ],
        }),
    ],
})

eks_cluster_node_group_role = AWSCDK::IAM::Role.new(self, "eksClusterNodeGroupRole", {
    role_name: "eksClusterNodeGroupRole",
    assumed_by: AWSCDK::IAM::ServicePrincipal.new("ec2.amazonaws.com"),
    managed_policies: [
        AWSCDK::IAM::ManagedPolicy.from_aws_managed_policy_name("AmazonEKSWorkerNodePolicy"),
        AWSCDK::IAM::ManagedPolicy.from_aws_managed_policy_name("AmazonEC2ContainerRegistryReadOnly"),
        AWSCDK::IAM::ManagedPolicy.from_aws_managed_policy_name("AmazonEKS_CNI_Policy"),
    ],
    inline_policies: {
        ipv6_management: ipv6_management,
    },
})

cluster = AWSCDK::EKS::Cluster.new(self, "HelloEKS", {
    version: AWSCDK::EKS::KubernetesVersion.V1_35,
    default_capacity: 0,
    kubectl_layer: AWSCDK::LambdaLayerKubectlV35::KubectlV35Layer.new(self, "kubectl"),
})

cluster.add_nodegroup_capacity("custom-node-group", {
    instance_types: [AWSCDK::EC2::InstanceType.new("m5.large")],
    min_size: 2,
    disk_size: 100,
    node_role: eks_cluster_node_group_role,
})

Spot Instances Support

Use capacity_type to create managed node groups comprised of spot instances. To maximize the availability of your applications while using Spot Instances, we recommend that you configure a Spot managed node group to use multiple instance types with the instance_types property.

For more details visit Managed node group capacity types.

cluster = nil # AWSCDK::EKS::Cluster

cluster.add_nodegroup_capacity("extra-ng-spot", {
    instance_types: [
        AWSCDK::EC2::InstanceType.new("c5.large"),
        AWSCDK::EC2::InstanceType.new("c5a.large"),
        AWSCDK::EC2::InstanceType.new("c5d.large"),
    ],
    min_size: 3,
    capacity_type: AWSCDK::EKS::CapacityType::SPOT,
})

Launch Template Support

You can specify a launch template that the node group will use. For example, this can be useful if you want to use a custom AMI or add custom user data.

When supplying a custom user data script, it must be encoded in the MIME multi-part archive format, since Amazon EKS merges with its own user data. Visit the Launch Template Docs for mode details.

cluster = nil # AWSCDK::EKS::Cluster


user_data = <<-'HERE'
MIME-Version: 1.0
Content-Type: multipart/mixed; boundary="==MYBOUNDARY=="

--==MYBOUNDARY==
Content-Type: text/x-shellscript; charset="us-ascii"

#!/bin/bash
echo "Running custom user data script"

--==MYBOUNDARY==--\

HERE
lt = AWSCDK::EC2::CfnLaunchTemplate.new(self, "LaunchTemplate", {
    launch_template_data: {
        instance_type: "t3.small",
        user_data: AWSCDK::Fn.base64(user_data),
    },
})

cluster.add_nodegroup_capacity("extra-ng", {
    launch_template_spec: {
        id: lt.ref,
        version: lt.attr_latest_version_number,
    },
})

Note that when using a custom AMI, Amazon EKS doesn't merge any user data. Which means you do not need the multi-part encoding. and are responsible for supplying the required bootstrap commands for nodes to join the cluster. In the following example, /ect/eks/bootstrap.sh from the AMI will be used to bootstrap the node.

cluster = nil # AWSCDK::EKS::Cluster

user_data = AWSCDK::EC2::UserData.for_linux
user_data.add_commands("set -o xtrace", "/etc/eks/bootstrap.sh #{cluster.cluster_name}")
lt = AWSCDK::EC2::CfnLaunchTemplate.new(self, "LaunchTemplate", {
    launch_template_data: {
        image_id: "some-ami-id",
         # custom AMI
        instance_type: "t3.small",
        user_data: AWSCDK::Fn.base64(user_data.render),
    },
})
cluster.add_nodegroup_capacity("extra-ng", {
    launch_template_spec: {
        id: lt.ref,
        version: lt.attr_latest_version_number,
    },
})

You may specify one instance_type in the launch template or multiple instance_types in the node group, but not both.

For more details visit Launch Template Support.

Graviton 2 instance types are supported including c6g, m6g, r6g and t4g. Graviton 3 instance types are supported including c7g.

Update clusters

When you rename the cluster name and redeploy the stack, the cluster replacement will be triggered and the existing one will be deleted after the new one is provisioned. As the cluster resource ARN has been changed, the cluster resource handler would not be able to delete the old one as the resource ARN in the IAM policy has been changed. As a workaround, you need to add a temporary policy to the cluster admin role for successful replacement. Consider this example if you are renaming the cluster from foo to bar:

require 'aws-cdk-lambda-layer-kubectl-v35'


cluster = AWSCDK::EKS::Cluster.new(self, "cluster-to-rename", {
    cluster_name: "foo",
     # rename this to 'bar'
    kubectl_layer: AWSCDK::LambdaLayerKubectlV35::KubectlV35Layer.new(self, "kubectl"),
    version: AWSCDK::EKS::KubernetesVersion.V1_35,
})

# allow the cluster admin role to delete the cluster 'foo'
cluster.admin_role.add_to_policy(AWSCDK::IAM::PolicyStatement.new({
    actions: [
        "eks:DeleteCluster",
        "eks:DescribeCluster",
    ],
    resources: [
        AWSCDK::Stack.of(self).format_arn({service: "eks", resource: "cluster", resource_name: "foo"}),
    ],
}))

Fargate profiles

AWS Fargate is a technology that provides on-demand, right-sized compute capacity for containers. With AWS Fargate, you no longer have to provision, configure, or scale groups of virtual machines to run containers. This removes the need to choose server types, decide when to scale your node groups, or optimize cluster packing.

You can control which pods start on Fargate and how they run with Fargate Profiles, which are defined as part of your Amazon EKS cluster.

See Fargate Considerations in the AWS EKS User Guide.

You can add Fargate Profiles to any EKS cluster defined in your CDK app through the add_fargate_profile() method. The following example adds a profile that will match all pods from the "default" namespace:

cluster = nil # AWSCDK::EKS::Cluster

cluster.add_fargate_profile("MyProfile", {
    selectors: [{namespace: "default"}],
})

You can also directly use the FargateProfile construct to create profiles under different scopes:

cluster = nil # AWSCDK::EKS::Cluster

AWSCDK::EKS::FargateProfile.new(self, "MyProfile", {
    cluster: cluster,
    selectors: [{namespace: "default"}],
})

To create an EKS cluster that only uses Fargate capacity, you can use FargateCluster. The following code defines an Amazon EKS cluster with a default Fargate Profile that matches all pods from the "kube-system" and "default" namespaces. It is also configured to run CoreDNS on Fargate.

require 'aws-cdk-lambda-layer-kubectl-v35'


cluster = AWSCDK::EKS::FargateCluster.new(self, "MyCluster", {
    version: AWSCDK::EKS::KubernetesVersion.V1_35,
    kubectl_layer: AWSCDK::LambdaLayerKubectlV35::KubectlV35Layer.new(self, "kubectl"),
})

FargateCluster will create a default FargateProfile which can be accessed via the cluster's default_profile property. The created profile can also be customized by passing options as with add_fargate_profile.

NOTE: Classic Load Balancers and Network Load Balancers are not supported on pods running on Fargate. For ingress, we recommend that you use the ALB Ingress Controller on Amazon EKS (minimum version v1.1.4).

Self-managed nodes

Another way of allocating capacity to an EKS cluster is by using self-managed nodes. EC2 instances that are part of the auto-scaling group will serve as worker nodes for the cluster. This type of capacity is also commonly referred to as EC2 Capacity* or EC2 Nodes.

For a detailed overview please visit Self Managed Nodes.

Creating an auto-scaling group and connecting it to the cluster is done using the cluster.addAutoScalingGroupCapacity method:

cluster = nil # AWSCDK::EKS::Cluster

cluster.add_auto_scaling_group_capacity("frontend-nodes", {
    instance_type: AWSCDK::EC2::InstanceType.new("t2.medium"),
    min_capacity: 3,
    vpc_subnets: {subnet_type: AWSCDK::EC2::SubnetType::PUBLIC},
})

To connect an already initialized auto-scaling group, use the cluster.connectAutoScalingGroupCapacity() method:

cluster = nil # AWSCDK::EKS::Cluster
asg = nil # AWSCDK::Autoscaling::AutoScalingGroup

cluster.connect_auto_scaling_group_capacity(asg, {})

To connect a self-managed node group to an imported cluster, use the cluster.connectAutoScalingGroupCapacity() method:

cluster = nil # AWSCDK::EKS::Cluster
asg = nil # AWSCDK::Autoscaling::AutoScalingGroup

imported_cluster = AWSCDK::EKS::Cluster.from_cluster_attributes(self, "ImportedCluster", {
    cluster_name: cluster.cluster_name,
    cluster_security_group_id: cluster.cluster_security_group_id,
})

imported_cluster.connect_auto_scaling_group_capacity(asg, {})

In both cases, the cluster security group will be automatically attached to the auto-scaling group, allowing for traffic to flow freely between managed and self-managed nodes.

Note: The default update_type for auto-scaling groups does not replace existing nodes. Since security groups are determined at launch time, self-managed nodes that were provisioned with version 1.78.0 or lower, will not be updated. To apply the new configuration on all your self-managed nodes, you'll need to replace the nodes using the UpdateType.REPLACING_UPDATE policy for the update_type property.

You can customize the /etc/eks/boostrap.sh script, which is responsible for bootstrapping the node to the EKS cluster. For example, you can use kubelet_extra_args to add custom node labels or taints.

cluster = nil # AWSCDK::EKS::Cluster

cluster.add_auto_scaling_group_capacity("spot", {
    instance_type: AWSCDK::EC2::InstanceType.new("t3.large"),
    min_capacity: 2,
    bootstrap_options: {
        kubelet_extra_args: "--node-labels foo=bar,goo=far",
        aws_api_retry_attempts: 5,
    },
})

To disable bootstrapping altogether (i.e. to fully customize user-data), set bootstrap_enabled to false. You can also configure the cluster to use an auto-scaling group as the default capacity:

require 'aws-cdk-lambda-layer-kubectl-v35'


cluster = AWSCDK::EKS::Cluster.new(self, "HelloEKS", {
    version: AWSCDK::EKS::KubernetesVersion.V1_35,
    default_capacity_type: AWSCDK::EKS::DefaultCapacityType::EC2,
    kubectl_layer: AWSCDK::LambdaLayerKubectlV35::KubectlV35Layer.new(self, "kubectl"),
})

This will allocate an auto-scaling group with 2 m5.large instances (this instance type suits most common use-cases, and is good value for money). To access the AutoScalingGroup that was created on your behalf, you can use cluster.defaultCapacity. You can also independently create an AutoScalingGroup and connect it to the cluster using the cluster.connectAutoScalingGroupCapacity method:

cluster = nil # AWSCDK::EKS::Cluster
asg = nil # AWSCDK::Autoscaling::AutoScalingGroup

cluster.connect_auto_scaling_group_capacity(asg, {})

This will add the necessary user-data to access the apiserver and configure all connections, roles, and tags needed for the instances in the auto-scaling group to properly join the cluster.

Spot Instances

When using self-managed nodes, you can configure the capacity to use spot instances, greatly reducing capacity cost. To enable spot capacity, use the spot_price property:

cluster = nil # AWSCDK::EKS::Cluster

cluster.add_auto_scaling_group_capacity("spot", {
    spot_price: "0.1094",
    instance_type: AWSCDK::EC2::InstanceType.new("t3.large"),
    max_capacity: 10,
})

Spot instance nodes will be labeled with lifecycle=Ec2Spot and tainted with PreferNoSchedule.

The AWS Node Termination Handler DaemonSet will be installed from Amazon EKS Helm chart repository on these nodes. The termination handler ensures that the Kubernetes control plane responds appropriately to events that can cause your EC2 instance to become unavailable, such as EC2 maintenance events and EC2 Spot interruptions and helps gracefully stop all pods running on spot nodes that are about to be terminated.

Handler Version: 1.7.0

Chart Version: 0.9.5

To disable the installation of the termination handler, set the spot_interrupt_handler property to false. This applies both to add_auto_scaling_group_capacity and connect_auto_scaling_group_capacity.

Bottlerocket

Bottlerocket is a Linux-based open-source operating system that is purpose-built by Amazon Web Services for running containers on virtual machines or bare metal hosts.

Bottlerocket is supported when using managed nodegroups or self-managed auto-scaling groups.

To create a Bottlerocket managed nodegroup:

cluster = nil # AWSCDK::EKS::Cluster

cluster.add_nodegroup_capacity("BottlerocketNG", {
    ami_type: AWSCDK::EKS::NodegroupAmiType::BOTTLEROCKET_X86_64,
})

The following example will create an auto-scaling group of 2 t3.small Linux instances running with the Bottlerocket AMI.

cluster = nil # AWSCDK::EKS::Cluster

cluster.add_auto_scaling_group_capacity("BottlerocketNodes", {
    instance_type: AWSCDK::EC2::InstanceType.new("t3.small"),
    min_capacity: 2,
    machine_image_type: AWSCDK::EKS::MachineImageType::BOTTLEROCKET,
})

The specific Bottlerocket AMI variant will be auto selected according to the k8s version for the x86_64 architecture. For example, if the Amazon EKS cluster version is 1.17, the Bottlerocket AMI variant will be auto selected as aws-k8s-1.17 behind the scene.

See Variants for more details.

Please note Bottlerocket does not allow to customize bootstrap options and bootstrap_options properties is not supported when you create the Bottlerocket capacity.

To create a Bottlerocket managed nodegroup with Nvidia-based EC2 instance types use the BOTTLEROCKET_X86_64_NVIDIA or BOTTLEROCKET_ARM_64_NVIDIA AMIs:

cluster = nil # AWSCDK::EKS::Cluster

cluster.add_nodegroup_capacity("BottlerocketNvidiaNG", {
    ami_type: AWSCDK::EKS::NodegroupAmiType::BOTTLEROCKET_X86_64_NVIDIA,
    instance_types: [AWSCDK::EC2::InstanceType.new("g4dn.xlarge")],
})

For more details about Bottlerocket, see Bottlerocket FAQs and Bottlerocket Open Source Blog.

Endpoint Access

When you create a new cluster, Amazon EKS creates an endpoint for the managed Kubernetes API server that you use to communicate with your cluster (using Kubernetes management tools such as kubectl)

By default, this API server endpoint is public to the internet, and access to the API server is secured using a combination of AWS Identity and Access Management (IAM) and native Kubernetes Role Based Access Control (RBAC).

You can configure the cluster endpoint access by using the endpoint_access property:

require 'aws-cdk-lambda-layer-kubectl-v35'


cluster = AWSCDK::EKS::Cluster.new(self, "hello-eks", {
    version: AWSCDK::EKS::KubernetesVersion.V1_35,
    endpoint_access: AWSCDK::EKS::EndpointAccess.PRIVATE,
     # No access outside of your VPC.
    kubectl_layer: AWSCDK::LambdaLayerKubectlV35::KubectlV35Layer.new(self, "kubectl"),
})

The default value is eks.EndpointAccess.PUBLIC_AND_PRIVATE. Which means the cluster endpoint is accessible from outside of your VPC, but worker node traffic and kubectl commands issued by this library stay within your VPC.

Alb Controller

Some Kubernetes resources are commonly implemented on AWS with the help of the ALB Controller.

From the docs:

AWS Load Balancer Controller is a controller to help manage Elastic Load Balancers for a Kubernetes cluster.

  • It satisfies Kubernetes Ingress resources by provisioning Application Load Balancers.
  • It satisfies Kubernetes Service resources by provisioning Network Load Balancers.

To deploy the controller on your EKS cluster, configure the alb_controller property:

require 'aws-cdk-lambda-layer-kubectl-v35'


AWSCDK::EKS::Cluster.new(self, "HelloEKS", {
    version: AWSCDK::EKS::KubernetesVersion.V1_35,
    alb_controller: {
        version: AWSCDK::EKS::ALBControllerVersion.V3_2_2,
    },
    kubectl_layer: AWSCDK::LambdaLayerKubectlV35::KubectlV35Layer.new(self, "kubectl"),
})

To provide additional Helm chart values supported by alb_controller in CDK, use the additional_helm_chart_values property. For example, the following code snippet shows how to set the enable_waf_v2 flag:

require 'aws-cdk-lambda-layer-kubectl-v35'


AWSCDK::EKS::Cluster.new(self, "HelloEKS", {
    version: AWSCDK::EKS::KubernetesVersion.V1_35,
    alb_controller: {
        version: AWSCDK::EKS::ALBControllerVersion.V3_2_2,
        additional_helm_chart_values: {
            enable_wafv2: false,
        },
    },
    kubectl_layer: AWSCDK::LambdaLayerKubectlV35::KubectlV35Layer.new(self, "kubectl"),
})

To overwrite an existing ALB controller service account, use the overwrite_service_account property:

require 'aws-cdk-lambda-layer-kubectl-v35'


AWSCDK::EKS::Cluster.new(self, "HelloEKS", {
    version: AWSCDK::EKS::KubernetesVersion.V1_35,
    alb_controller: {
        version: AWSCDK::EKS::ALBControllerVersion.V3_2_2,
        overwrite_service_account: true,
    },
    kubectl_layer: AWSCDK::LambdaLayerKubectlV35::KubectlV35Layer.new(self, "kubectl"),
})

The alb_controller requires default_capacity or at least one nodegroup. If there's no default_capacity or available nodegroup for the cluster, the alb_controller deployment would fail.

Querying the controller pods should look something like this:

โฏ kubectl get pods -n kube-system
NAME                                            READY   STATUS    RESTARTS   AGE
aws-load-balancer-controller-76bd6c7586-d929p   1/1     Running   0          109m
aws-load-balancer-controller-76bd6c7586-fqxph   1/1     Running   0          109m
...
...

Every Kubernetes manifest that utilizes the ALB Controller is effectively dependent on the controller. If the controller is deleted before the manifest, it might result in dangling ELB/ALB resources. Currently, the EKS construct library does not detect such dependencies, and they should be done explicitly.

For example:

cluster = nil # AWSCDK::EKS::Cluster

manifest = cluster.add_manifest("manifest", {})
if cluster.alb_controller
  manifest.node.add_dependency(cluster.alb_controller)
end

VPC Support

You can specify the VPC of the cluster using the vpc and vpc_subnets properties:

require 'aws-cdk-lambda-layer-kubectl-v35'

vpc = nil # AWSCDK::EC2::VPC


AWSCDK::EKS::Cluster.new(self, "HelloEKS", {
    version: AWSCDK::EKS::KubernetesVersion.V1_35,
    vpc: vpc,
    vpc_subnets: [{subnet_type: AWSCDK::EC2::SubnetType::PRIVATE_WITH_EGRESS}],
    kubectl_layer: AWSCDK::LambdaLayerKubectlV35::KubectlV35Layer.new(self, "kubectl"),
})

Note: Isolated VPCs (i.e with no internet access) are not fully supported. See https://github.com/aws/aws-cdk/issues/12171. Check out this aws-cdk-example for reference.

If you do not specify a VPC, one will be created on your behalf, which you can then access via cluster.vpc. The cluster VPC will be associated to any EKS managed capacity (i.e Managed Node Groups and Fargate Profiles).

Please note that the vpc_subnets property defines the subnets where EKS will place the control plane ENIs. To choose the subnets where EKS will place the worker nodes, please refer to the Provisioning clusters section above.

If you allocate self managed capacity, you can specify which subnets should the auto-scaling group use:

vpc = nil # AWSCDK::EC2::VPC
cluster = nil # AWSCDK::EKS::Cluster

cluster.add_auto_scaling_group_capacity("nodes", {
    vpc_subnets: {subnets: vpc.private_subnets},
    instance_type: AWSCDK::EC2::InstanceType.new("t2.medium"),
})

There are two additional components you might want to provision within the VPC.

Kubectl Handler

The KubectlHandler is a Lambda function responsible to issuing kubectl and helm commands against the cluster when you add resource manifests to the cluster.

The handler association to the VPC is derived from the endpoint_access configuration. The rule of thumb is: If the cluster VPC can be associated, it will be.

Breaking this down, it means that if the endpoint exposes private access (via EndpointAccess.PRIVATE or EndpointAccess.PUBLIC_AND_PRIVATE), and the VPC contains private subnets, the Lambda function will be provisioned inside the VPC and use the private subnets to interact with the cluster. This is the common use-case.

If the endpoint does not expose private access (via EndpointAccess.PUBLIC) or the VPC does not contain private subnets, the function will not be provisioned within the VPC.

If your use-case requires control over the IAM role that the KubeCtl Handler assumes, a custom role can be passed through the ClusterProps (as kubectl_lambda_role) of the EKS Cluster construct.

Cluster Handler

The ClusterHandler is a set of Lambda functions (on_event_handler, is_complete_handler) responsible for interacting with the EKS API in order to control the cluster lifecycle. To provision these functions inside the VPC, set the place_cluster_handler_in_vpc property to true. This will place the functions inside the private subnets of the VPC based on the selection strategy specified in the vpc_subnets property.

You can configure the environment of the Cluster Handler functions by specifying it at cluster instantiation. For example, this can be useful in order to configure an http proxy:

require 'aws-cdk-lambda-layer-kubectl-v35'

proxy_instance_security_group = nil # AWSCDK::EC2::SecurityGroup

cluster = AWSCDK::EKS::Cluster.new(self, "hello-eks", {
    version: AWSCDK::EKS::KubernetesVersion.V1_35,
    cluster_handler_environment: {
        https_proxy: "http://proxy.myproxy.com",
    },
    #
    # If the proxy is not open publicly, you can pass a security group to the
    # Cluster Handler Lambdas so that it can reach the proxy.
    #
    cluster_handler_security_group: proxy_instance_security_group,
    kubectl_layer: AWSCDK::LambdaLayerKubectlV35::KubectlV35Layer.new(self, "kubectl"),
})

IPv6 Support

You can optionally choose to configure your cluster to use IPv6 using the ip_family definition for your cluster. Note that this will require the underlying subnets to have an associated IPv6 CIDR.

require 'aws-cdk-lambda-layer-kubectl-v35'
vpc = nil # AWSCDK::EC2::VPC


def associate_subnet_with_v6_cidr(vpc, count, subnet)
  cfn_subnet = subnet.node.default_child
  cfn_subnet.ipv6_cidr_block = AWSCDK::Fn.select(count, AWSCDK::Fn.cidr(AWSCDK::Fn.select(0, vpc.vpc_ipv6_cidr_blocks), 256, (128 - 64).to_string))
  cfn_subnet.assign_ipv6_address_on_creation = true
end

# make an ipv6 cidr
ipv6cidr = AWSCDK::EC2::CfnVPCCIDRBlock.new(self, "CIDR6", {
    vpc_id: vpc.vpc_id,
    amazon_provided_ipv6_cidr_block: true,
})

# connect the ipv6 cidr to all vpc subnets
subnetcount = 0
subnets = vpc.public_subnets.concat(vpc.private_subnets)
subnets.each do |subnet|
  # Wait for the ipv6 cidr to complete
  subnet.node.add_dependency(ipv6cidr)
  associate_subnet_with_v6_cidr(vpc, subnetcount, subnet)
  subnetcount = subnetcount + 1
end

cluster = AWSCDK::EKS::Cluster.new(self, "hello-eks", {
    version: AWSCDK::EKS::KubernetesVersion.V1_35,
    vpc: vpc,
    ip_family: AWSCDK::EKS::IPFamily::IP_V6,
    vpc_subnets: [{subnets: vpc.public_subnets}],
    kubectl_layer: AWSCDK::LambdaLayerKubectlV35::KubectlV35Layer.new(self, "kubectl"),
})

Kubectl Support

The resources are created in the cluster by running kubectl apply from a python lambda function.

By default, CDK will create a new python lambda function to apply your k8s manifests. If you want to use an existing kubectl provider function, for example with tight trusted entities on your IAM Roles - you can import the existing provider and then use the imported provider when importing the cluster:

handler_role = AWSCDK::IAM::Role.from_role_arn(self, "HandlerRole", "arn:aws:iam::123456789012:role/lambda-role")
# get the serviceToken from the custom resource provider
function_arn = AWSCDK::Lambda::Function.from_function_name(self, "ProviderOnEventFunc", "ProviderframeworkonEvent-XXX").function_arn
kubectl_provider = AWSCDK::EKS::KubectlProvider.from_kubectl_provider_attributes(self, "KubectlProvider", {
    function_arn: function_arn,
    kubectl_role_arn: "arn:aws:iam::123456789012:role/kubectl-role",
    handler_role: handler_role,
})

cluster = AWSCDK::EKS::Cluster.from_cluster_attributes(self, "Cluster", {
    cluster_name: "cluster",
    kubectl_provider: kubectl_provider,
})

Environment

You can configure the environment of this function by specifying it at cluster instantiation. For example, this can be useful in order to configure an http proxy:

require 'aws-cdk-lambda-layer-kubectl-v35'


cluster = AWSCDK::EKS::Cluster.new(self, "hello-eks", {
    version: AWSCDK::EKS::KubernetesVersion.V1_35,
    kubectl_environment: {
        "http_proxy" => "http://proxy.myproxy.com",
    },
    kubectl_layer: AWSCDK::LambdaLayerKubectlV35::KubectlV35Layer.new(self, "kubectl"),
})

Runtime

The kubectl handler uses kubectl, helm and the aws CLI in order to interact with the cluster. These are bundled into AWS Lambda layers included in the @aws-cdk/lambda-layer-awscli and @aws-cdk/lambda-layer-kubectl modules.

The version of kubectl used must be compatible with the Kubernetes version of the cluster. kubectl is supported within one minor version (older or newer) of Kubernetes (see Kubernetes version skew policy). Depending on which version of kubernetes you're targeting, you will need to use one of the @aws-cdk/lambda-layer-kubectl-vXY packages.

require 'aws-cdk-lambda-layer-kubectl-v35'


cluster = AWSCDK::EKS::Cluster.new(self, "hello-eks", {
    version: AWSCDK::EKS::KubernetesVersion.V1_35,
    kubectl_layer: AWSCDK::LambdaLayerKubectlV35::KubectlV35Layer.new(self, "kubectl"),
})

You can also specify a custom lambda.LayerVersion if you wish to use a different version of these tools, or a version not available in any of the @aws-cdk/lambda-layer-kubectl-vXY packages. The handler expects the layer to include the following two executables:

helm/helm
kubectl/kubectl

See more information in the Dockerfile for @aws-cdk/lambda-layer-awscli and the Dockerfile for @aws-cdk/lambda-layer-kubectl.

layer = AWSCDK::Lambda::LayerVersion.new(self, "KubectlLayer", {
    code: AWSCDK::Lambda::Code.from_asset("layer.zip"),
})

Now specify when the cluster is defined:

layer = nil # AWSCDK::Lambda::LayerVersion
vpc = nil # AWSCDK::EC2::VPC


cluster1 = AWSCDK::EKS::Cluster.new(self, "MyCluster", {
    kubectl_layer: layer,
    vpc: vpc,
    cluster_name: "cluster-name",
    version: AWSCDK::EKS::KubernetesVersion.V1_35,
})

# or
cluster2 = AWSCDK::EKS::Cluster.from_cluster_attributes(self, "MyCluster", {
    kubectl_layer: layer,
    vpc: vpc,
    cluster_name: "cluster-name",
})

Memory

By default, the kubectl provider is configured with 1024MiB of memory. You can use the kubectl_memory option to specify the memory size for the AWS Lambda function:

require 'aws-cdk-lambda-layer-kubectl-v35'

# or
vpc = nil # AWSCDK::EC2::VPC


AWSCDK::EKS::Cluster.new(self, "MyCluster", {
    kubectl_memory: AWSCDK::Size.gibibytes(4),
    version: AWSCDK::EKS::KubernetesVersion.V1_35,
    kubectl_layer: AWSCDK::LambdaLayerKubectlV35::KubectlV35Layer.new(self, "kubectl"),
})
AWSCDK::EKS::Cluster.from_cluster_attributes(self, "MyCluster", {
    kubectl_memory: AWSCDK::Size.gibibytes(4),
    vpc: vpc,
    cluster_name: "cluster-name",
})

ARM64 Support

Instance types with ARM64 architecture are supported in both managed nodegroup and self-managed capacity. Simply specify an ARM64 instance_type (such as m6g.medium), and the latest Amazon Linux 2 AMI for ARM64 will be automatically selected.

cluster = nil # AWSCDK::EKS::Cluster

# add a managed ARM64 nodegroup
cluster.add_nodegroup_capacity("extra-ng-arm", {
    instance_types: [AWSCDK::EC2::InstanceType.new("m6g.medium")],
    min_size: 2,
})

# add a self-managed ARM64 nodegroup
cluster.add_auto_scaling_group_capacity("self-ng-arm", {
    instance_type: AWSCDK::EC2::InstanceType.new("m6g.medium"),
    min_capacity: 2,
})

Masters Role

When you create a cluster, you can specify a masters_role. The Cluster construct will associate this role with the system:masters RBAC group, giving it super-user access to the cluster.

require 'aws-cdk-lambda-layer-kubectl-v35'

role = nil # AWSCDK::IAM::Role

AWSCDK::EKS::Cluster.new(self, "HelloEKS", {
    version: AWSCDK::EKS::KubernetesVersion.V1_35,
    masters_role: role,
    kubectl_layer: AWSCDK::LambdaLayerKubectlV35::KubectlV35Layer.new(self, "kubectl"),
})

In order to interact with your cluster through kubectl, you can use the aws eks update-kubeconfig AWS CLI command to configure your local kubeconfig. The EKS module will define a CloudFormation output in your stack which contains the command to run. For example:

Outputs:
ClusterConfigCommand43AAE40F = aws eks update-kubeconfig --name cluster-xxxxx --role-arn arn:aws:iam::112233445566:role/yyyyy

Execute the aws eks update-kubeconfig ... command in your terminal to create or update a local kubeconfig context:

$ aws eks update-kubeconfig --name cluster-xxxxx --role-arn arn:aws:iam::112233445566:role/yyyyy
Added new context arn:aws:eks:rrrrr:112233445566:cluster/cluster-xxxxx to /home/boom/.kube/config

And now you can simply use kubectl:

$ kubectl get all -n kube-system
NAME                           READY   STATUS    RESTARTS   AGE
pod/aws-node-fpmwv             1/1     Running   0          21m
pod/aws-node-m9htf             1/1     Running   0          21m
pod/coredns-5cb4fb54c7-q222j   1/1     Running   0          23m
pod/coredns-5cb4fb54c7-v9nxx   1/1     Running   0          23m
...

If you do not specify it, you won't have access to the cluster from outside of the CDK application.

Note that cluster.addManifest and new KubernetesManifest will still work.

Encryption

When you create an Amazon EKS cluster, envelope encryption of Kubernetes secrets using the AWS Key Management Service (AWS KMS) can be enabled. The documentation on creating a cluster can provide more details about the customer master key (CMK) that can be used for the encryption.

You can use the secrets_encryption_key to configure which key the cluster will use to encrypt Kubernetes secrets. By default, an AWS Managed key will be used.

This setting can only be specified when the cluster is created and cannot be updated.

require 'aws-cdk-lambda-layer-kubectl-v35'


secrets_key = AWSCDK::KMS::Key.new(self, "SecretsKey")
cluster = AWSCDK::EKS::Cluster.new(self, "MyCluster", {
    secrets_encryption_key: secrets_key,
    version: AWSCDK::EKS::KubernetesVersion.V1_35,
    kubectl_layer: AWSCDK::LambdaLayerKubectlV35::KubectlV35Layer.new(self, "kubectl"),
})

You can also use a similar configuration for running a cluster built using the FargateCluster construct.

require 'aws-cdk-lambda-layer-kubectl-v35'


secrets_key = AWSCDK::KMS::Key.new(self, "SecretsKey")
cluster = AWSCDK::EKS::FargateCluster.new(self, "MyFargateCluster", {
    secrets_encryption_key: secrets_key,
    version: AWSCDK::EKS::KubernetesVersion.V1_35,
    kubectl_layer: AWSCDK::LambdaLayerKubectlV35::KubectlV35Layer.new(self, "kubectl"),
})

The Amazon Resource Name (ARN) for that CMK can be retrieved.

cluster = nil # AWSCDK::EKS::Cluster

cluster_encryption_config_key_arn = cluster.cluster_encryption_config_key_arn

Hybrid Nodes

When you create an Amazon EKS cluster, you can configure it to leverage the EKS Hybrid Nodes feature, allowing you to use your on-premises and edge infrastructure as nodes in your EKS cluster. Refer to the Hyrid Nodes networking documentation to configure your on-premises network, node and pod CIDRs, access control, etc before creating your EKS Cluster.

Once you have identified the on-premises node and pod (optional) CIDRs you will use for your hybrid nodes and the workloads running on them, you can specify them during cluster creation using the remote_node_networks and remote_pod_networks (optional) properties:

require 'aws-cdk-lambda-layer-kubectl-v35'


AWSCDK::EKS::Cluster.new(self, "Cluster", {
    version: AWSCDK::EKS::KubernetesVersion.V1_35,
    kubectl_layer: AWSCDK::LambdaLayerKubectlV35::KubectlV35Layer.new(self, "KubectlLayer"),
    remote_node_networks: [
        {
            cidrs: ["10.0.0.0/16"],
        },
    ],
    remote_pod_networks: [
        {
            cidrs: ["192.168.0.0/16"],
        },
    ],
})

Self-Managed Add-ons

Amazon EKS automatically installs self-managed add-ons such as the Amazon VPC CNI plugin for Kubernetes, kube-proxy, and CoreDNS for every cluster. You can change the default configuration of the add-ons and update them when desired. If you wish to create a cluster without the default add-ons, set bootstrap_self_managed_addons as false. When this is set to false, make sure to install the necessary alternatives which provide functionality that enables pod and service operations for your EKS cluster.

Changing the value of bootstrap_self_managed_addons after the EKS cluster creation will result in a replacement of the cluster.

Permissions and Security

Amazon EKS provides several mechanism of securing the cluster and granting permissions to specific IAM users and roles.

AWS IAM Mapping

As described in the Amazon EKS User Guide, you can map AWS IAM users and roles to Kubernetes Role-based access control (RBAC).

The Amazon EKS construct manages the aws-auth ConfigMap Kubernetes resource on your behalf and exposes an API through the cluster.awsAuth for mapping users, roles and accounts.

Furthermore, when auto-scaling group capacity is added to the cluster, the IAM instance role of the auto-scaling group will be automatically mapped to RBAC so nodes can connect to the cluster. No manual mapping is required.

For example, let's say you want to grant an IAM user administrative privileges on your cluster:

cluster = nil # AWSCDK::EKS::Cluster

admin_user = AWSCDK::IAM::User.new(self, "Admin")
cluster.aws_auth.add_user_mapping(admin_user, {groups: ["system:masters"]})

A convenience method for mapping a role to the system:masters group is also available:

cluster = nil # AWSCDK::EKS::Cluster
role = nil # AWSCDK::IAM::Role

cluster.aws_auth.add_masters_role(role)

To access the Kubernetes resources from the console, make sure your viewing principal is defined in the aws-auth ConfigMap. Some options to consider:

require 'aws-cdk-lambda-layer-kubectl-v35'
cluster = nil # AWSCDK::EKS::Cluster
your_current_role = nil # AWSCDK::IAM::Role
vpc = nil # AWSCDK::EC2::VPC


# Option 1: Add your current assumed IAM role to system:masters. Make sure to add relevant policies.
cluster.aws_auth.add_masters_role(your_current_role)

your_current_role.add_to_policy(AWSCDK::IAM::PolicyStatement.new({
    actions: [
        "eks:AccessKubernetesApi",
        "eks:Describe*",
        "eks:List*",
    ],
    resources: [cluster.cluster_arn],
}))
# Option 2: create your custom mastersRole with scoped assumeBy arn as the Cluster prop. Switch to this role from the AWS console.
require 'aws-cdk-lambda-layer-kubectl-v35'
vpc = nil # AWSCDK::EC2::VPC


masters_role = AWSCDK::IAM::Role.new(self, "MastersRole", {
    assumed_by: AWSCDK::IAM::ARNPrincipal.new("arn_for_trusted_principal"),
})

cluster = AWSCDK::EKS::Cluster.new(self, "EksCluster", {
    vpc: vpc,
    version: AWSCDK::EKS::KubernetesVersion.V1_35,
    kubectl_layer: AWSCDK::LambdaLayerKubectlV35::KubectlV35Layer.new(self, "KubectlLayer"),
    masters_role: masters_role,
})

masters_role.add_to_policy(AWSCDK::IAM::PolicyStatement.new({
    actions: [
        "eks:AccessKubernetesApi",
        "eks:Describe*",
        "eks:List*",
    ],
    resources: [cluster.cluster_arn],
}))
# Option 3: Create a new role that allows the account root principal to assume. Add this role in the `system:masters` and witch to this role from the AWS console.
cluster = nil # AWSCDK::EKS::Cluster


console_read_only_role = AWSCDK::IAM::Role.new(self, "ConsoleReadOnlyRole", {
    assumed_by: AWSCDK::IAM::ARNPrincipal.new("arn_for_trusted_principal"),
})
console_read_only_role.add_to_policy(AWSCDK::IAM::PolicyStatement.new({
    actions: [
        "eks:AccessKubernetesApi",
        "eks:Describe*",
        "eks:List*",
    ],
    resources: [cluster.cluster_arn],
}))

# Add this role to system:masters RBAC group
cluster.aws_auth.add_masters_role(console_read_only_role)

Access Config

Amazon EKS supports three modes of authentication: CONFIG_MAP, API_AND_CONFIG_MAP, and API. You can enable cluster to use access entry APIs by using authenticationMode API or API_AND_CONFIG_MAP. Use authenticationMode CONFIG_MAP to continue using aws-auth configMap exclusively. When API_AND_CONFIG_MAP is enabled, the cluster will source authenticated AWS IAM principals from both Amazon EKS access entry APIs and the aws-auth configMap, with priority given to the access entry API.

To specify the authentication_mode:

require 'aws-cdk-lambda-layer-kubectl-v35'
vpc = nil # AWSCDK::EC2::VPC


AWSCDK::EKS::Cluster.new(self, "Cluster", {
    vpc: vpc,
    version: AWSCDK::EKS::KubernetesVersion.V1_35,
    kubectl_layer: AWSCDK::LambdaLayerKubectlV35::KubectlV35Layer.new(self, "KubectlLayer"),
    authentication_mode: AWSCDK::EKS::AuthenticationMode::API_AND_CONFIG_MAP,
})

Note - Switching authentication modes on an existing cluster is a one-way operation. You can switch from CONFIG_MAP to API_AND_CONFIG_MAP. You can then switch from API_AND_CONFIG_MAP to API. You cannot revert these operations in the opposite direction. Meaning you cannot switch back to CONFIG_MAP or API_AND_CONFIG_MAP from API. And you cannot switch back to CONFIG_MAP from API_AND_CONFIG_MAP.

Read A deep dive into simplified Amazon EKS access management controls for more details.

You can disable granting the cluster admin permissions to the cluster creator role on bootstrapping by setting bootstrap_cluster_creator_admin_permissions to false.

Note - Switching bootstrap_cluster_creator_admin_permissions on an existing cluster would cause cluster replacement and should be avoided in production.

Access Entry

An access entry is a cluster identityโ€”directly linked to an AWS IAM principal user or role that is used to authenticate to an Amazon EKS cluster. An Amazon EKS access policy authorizes an access entry to perform specific cluster actions.

Access policies are Amazon EKS-specific policies that assign Kubernetes permissions to access entries. Amazon EKS supports only predefined and AWS managed policies. Access policies are not AWS IAM entities and are defined and managed by Amazon EKS. Amazon EKS access policies include permission sets that support common use cases of administration, editing, or read-only access to Kubernetes resources. See Access Policy Permissions for more details.

Use AccessPolicy to include predefined AWS managed policies:

# AmazonEKSClusterAdminPolicy with `cluster` scope
AWSCDK::EKS::AccessPolicy.from_access_policy_name("AmazonEKSClusterAdminPolicy", {
    access_scope_type: AWSCDK::EKS::AccessScopeType::CLUSTER,
})
# AmazonEKSAdminPolicy with `namespace` scope
AWSCDK::EKS::AccessPolicy.from_access_policy_name("AmazonEKSAdminPolicy", {
    access_scope_type: AWSCDK::EKS::AccessScopeType::NAMESPACE,
    namespaces: ["foo", "bar"],
})

Use grant_access() to grant the AccessPolicy to an IAM principal:

require 'aws-cdk-lambda-layer-kubectl-v35'
vpc = nil # AWSCDK::EC2::VPC


cluster_admin_role = AWSCDK::IAM::Role.new(self, "ClusterAdminRole", {
    assumed_by: AWSCDK::IAM::ARNPrincipal.new("arn_for_trusted_principal"),
})

eks_admin_role = AWSCDK::IAM::Role.new(self, "EKSAdminRole", {
    assumed_by: AWSCDK::IAM::ARNPrincipal.new("arn_for_trusted_principal"),
})

eks_admin_view_role = AWSCDK::IAM::Role.new(self, "EKSAdminViewRole", {
    assumed_by: AWSCDK::IAM::ARNPrincipal.new("arn_for_trusted_principal"),
})

cluster = AWSCDK::EKS::Cluster.new(self, "Cluster", {
    vpc: vpc,
    masters_role: cluster_admin_role,
    version: AWSCDK::EKS::KubernetesVersion.V1_35,
    kubectl_layer: AWSCDK::LambdaLayerKubectlV35::KubectlV35Layer.new(self, "KubectlLayer"),
    authentication_mode: AWSCDK::EKS::AuthenticationMode::API_AND_CONFIG_MAP,
})

# Cluster Admin role for this cluster
cluster.grant_access("clusterAdminAccess", cluster_admin_role.role_arn, [
    AWSCDK::EKS::AccessPolicy.from_access_policy_name("AmazonEKSClusterAdminPolicy", {
        access_scope_type: AWSCDK::EKS::AccessScopeType::CLUSTER,
    }),
])

# EKS Admin role for specified namespaces of this cluster
cluster.grant_access("eksAdminRoleAccess", eks_admin_role.role_arn, [
    AWSCDK::EKS::AccessPolicy.from_access_policy_name("AmazonEKSAdminPolicy", {
        access_scope_type: AWSCDK::EKS::AccessScopeType::NAMESPACE,
        namespaces: ["foo", "bar"],
    }),
])

# EKS Admin Viewer role for specified namespaces of this cluster
cluster.grant_access("eksAdminViewRoleAccess", eks_admin_view_role.role_arn, [
    AWSCDK::EKS::AccessPolicy.from_access_policy_name("AmazonEKSAdminViewPolicy", {
        access_scope_type: AWSCDK::EKS::AccessScopeType::NAMESPACE,
        namespaces: ["foo", "bar"],
    }),
])

You can optionally specify an access entry type when granting access:

cluster = nil # AWSCDK::EKS::Cluster
node_role = nil # AWSCDK::IAM::Role


# For EKS Auto Mode node roles
cluster.grant_access("NodeAccess", node_role.role_arn, [], {access_entry_type: AWSCDK::EKS::AccessEntryType::EC2})

Supported types: STANDARD (default), FARGATE_LINUX, EC2_LINUX, EC2_WINDOWS, EC2, HYBRID_LINUX, HYPERPOD_LINUX.

Note: EC2, HYBRID_LINUX, and HYPERPOD_LINUX types cannot have access policies attached.

Migrating from ConfigMap to Access Entry

If the cluster is created with the authentication_mode property left undefined, it will default to CONFIG_MAP.

The update path is:

undefined(CONFIG_MAP) -> API_AND_CONFIG_MAP -> API

If you have explicitly declared AwsAuth resources and then try to switch to the API mode, which no longer supports the ConfigMap, AWS CDK will throw an error as a protective measure to prevent you from losing all the access entries in the ConfigMap. In this case, you will need to remove all the declared AwsAuth resources explicitly and define the access entries before you are allowed to transition to the API mode.

Note - This is a one-way transition. Once you switch to the API mode, you will not be able to switch back. Therefore, it is crucial to ensure that you have defined all the necessary access entries before making the switch to the API mode.

Cluster Security Group

When you create an Amazon EKS cluster, a cluster security group is automatically created as well. This security group is designed to allow all traffic from the control plane and managed node groups to flow freely between each other.

The ID for that security group can be retrieved after creating the cluster.

cluster = nil # AWSCDK::EKS::Cluster

cluster_security_group_id = cluster.cluster_security_group_id

Node SSH Access

If you want to be able to SSH into your worker nodes, you must already have an SSH key in the region you're connecting to and pass it when you add capacity to the cluster. You must also be able to connect to the hosts (meaning they must have a public IP and you should be allowed to connect to them on port 22):

See SSH into nodes for a code example.

If you want to SSH into nodes in a private subnet, you should set up a bastion host in a public subnet. That setup is recommended, but is unfortunately beyond the scope of this documentation.

Service Accounts

With services account you can provide Kubernetes Pods access to AWS resources.

cluster = nil # AWSCDK::EKS::Cluster

# add service account
 = cluster.("MyServiceAccount")

bucket = AWSCDK::S3::Bucket.new(self, "Bucket")
bucket.grant_read_write()

mypod = cluster.add_manifest("mypod", {
    api_version: "v1",
    kind: "Pod",
    metadata: {name: "mypod"},
    spec: {
        service_account_name: .,
        containers: [
            {
                name: "hello",
                image: "paulbouwer/hello-kubernetes:1.5",
                ports: [{container_port: 8080}],
            },
        ],
    },
})

# create the resource after the service account.
mypod.node.add_dependency()

# print the IAM role arn for this service account
AWSCDK::CfnOutput.new(self, "ServiceAccountIamRole", {value: .role.role_arn})

Note that using serviceAccount.serviceAccountName above does not translate into a resource dependency. This is why an explicit dependency is needed. See https://github.com/aws/aws-cdk/issues/9910 for more details.

It is possible to pass annotations and labels to the service account.

cluster = nil # AWSCDK::EKS::Cluster

# add service account with annotations and labels
 = cluster.("MyServiceAccount", {
    annotations: {
        "eks.amazonaws.com/sts-regional-endpoints" => "false",
    },
    labels: {
        "some-label" => "with-some-value",
    },
})

To overwrite an existing service account, use the overwrite_service_account property:

cluster = nil # AWSCDK::EKS::Cluster

# overwrite existing service account
 = cluster.("MyServiceAccount", {
    overwrite_service_account: true,
})

You can also add service accounts to existing clusters. To do so, pass the open_id_connect_provider property when you import the cluster into the application.

# or create a new one using an existing issuer url
issuer_url = nil
# you can import an existing provider
provider = AWSCDK::EKS::OidcProviderNative.from_oidc_provider_arn(self, "Provider", "arn:aws:iam::123456:oidc-provider/oidc.eks.eu-west-1.amazonaws.com/id/AB123456ABC")
provider2 = AWSCDK::EKS::OidcProviderNative.new(self, "Provider", {
    url: issuer_url,
})

cluster = AWSCDK::EKS::Cluster.from_cluster_attributes(self, "MyCluster", {
    cluster_name: "Cluster",
    open_id_connect_provider: provider,
    kubectl_role_arn: "arn:aws:iam::123456:role/service-role/k8sservicerole",
})

 = cluster.("MyServiceAccount")

bucket = AWSCDK::S3::Bucket.new(self, "Bucket")
bucket.grant_read_write()

Note that adding service accounts requires running kubectl commands against the cluster. This means you must also pass the kubectl_role_arn when importing the cluster. See Using existing Clusters.

Migrating from eks.OpenIdConnectProvider to eks.OidcProviderNative

eks.OpenIdConnectProvider creates an IAM OIDC (OpenId Connect) provider using a custom resource while eks.OidcProviderNative uses the CFN L1 (AWS::IAM::OidcProvider) to create the provider. It is recommended for new and existing projects to use eks.OidcProviderNative. Migrating from the eks.OpenIdConnectProvider is not as trivial as switching out the property since the property controls the creation of a resource whose type is changing. Due to the potential complexlity of the migration and the requirement of a manual step (cdk import) we are not deprecating the eks.OpenIdConnectProvider construct but encourge you to migrate.

To migrate without temporarily removing the OIDCProvider, follow these steps:

  1. Set the removal_policy of cluster.openIdConnectProvider to RETAIN.
   require 'aws-cdk-lib'
   cluster = nil # AWSCDK::EKS::Cluster


   AWSCDK::RemovalPolicies.of(cluster.open_id_connect_provider).apply(AWSCDK::RemovalPolicy::RETAIN)
  1. Run cdk diff to verify the changes are expected then cdk deploy.
  2. Add the following to the context field of your cdk.json to enable the feature flag that creates the native oidc provider.
   "@aws-cdk/aws-eks:useNativeOidcProvider": true,
  1. Run cdk diff and ensure the changes are expected. Example of an expected diff:
   Resources
   [-] Custom::AWSCDKOpenIdConnectProvider TestCluster/OpenIdConnectProvider/Resource TestClusterOpenIdConnectProviderE18F0FD0 orphan
   [-] AWS::IAM::Role Custom::AWSCDKOpenIdConnectProviderCustomResourceProvider/Role CustomAWSCDKOpenIdConnectProviderCustomResourceProviderRole517FED65 destroy
   [-] AWS::Lambda::Function Custom::AWSCDKOpenIdConnectProviderCustomResourceProvider/Handler CustomAWSCDKOpenIdConnectProviderCustomResourceProviderHandlerF2C543E0 destroy
   [+] AWS::IAM::OIDCProvider TestCluster/OidcProviderNative TestClusterOidcProviderNative0BE3F155
  1. Run cdk import --force and provide the ARN of the existing OpenIdConnectProvider when prompted. You will get a warning about pending changes to existing resources which is expected.
  2. Run cdk deploy to apply any pending changes. This will apply the destroy/orphan changes in the above example.

If you are creating the OpenIdConnectProvider manually via new eks.OpenIdConnectProvider, follow these steps:

  1. Set the removal_policy of the existing OpenIdConnectProvider to RemovalPolicy.RETAIN.
   require 'aws-cdk-lib'

   # Step 1: Add retain policy to existing provider
   existing_provider = AWSCDK::EKS::OpenIdConnectProvider.new(self, "Provider", {
       url: "https://oidc.eks.us-west-2.amazonaws.com/id/EXAMPLE",
       removal_policy: AWSCDK::RemovalPolicy::RETAIN,
   })
  1. Deploy with the retain policy to avoid deletion of the underlying resource.
   cdk deploy
  1. Replace OpenIdConnectProvider with OidcProviderNative in your code.
   # Step 3: Replace with native provider
   native_provider = AWSCDK::EKS::OidcProviderNative.new(self, "Provider", {
       url: "https://oidc.eks.us-west-2.amazonaws.com/id/EXAMPLE",
   })
  1. Run cdk diff and verify the changes are expected. Example of an expected diff:
   Resources
   [-] Custom::AWSCDKOpenIdConnectProvider TestCluster/OpenIdConnectProvider/Resource TestClusterOpenIdConnectProviderE18F0FD0 orphan
   [-] AWS::IAM::Role Custom::AWSCDKOpenIdConnectProviderCustomResourceProvider/Role CustomAWSCDKOpenIdConnectProviderCustomResourceProviderRole517FED65 destroy
   [-] AWS::Lambda::Function Custom::AWSCDKOpenIdConnectProviderCustomResourceProvider/Handler CustomAWSCDKOpenIdConnectProviderCustomResourceProviderHandlerF2C543E0 destroy
   [+] AWS::IAM::OIDCProvider TestCluster/OidcProviderNative TestClusterOidcProviderNative0BE3F155
  1. Run cdk import --force to import the existing OIDC provider resource by providing the existing ARN.
  2. Run cdk deploy to apply any pending changes. This will apply the destroy/orphan operations in the example diff above.

Pod Identities

Amazon EKS Pod Identities is a feature that simplifies how Kubernetes applications running on Amazon EKS can obtain AWS IAM credentials. It provides a way to associate an IAM role with a Kubernetes service account, allowing pods to retrieve temporary AWS credentials without the need to manage IAM roles and policies directly.

By default, ServiceAccount creates an OpenIdConnectProvider for IRSA(IAM roles for service accounts) if identity_type is undefined or IdentityType.IRSA.

You may opt in Amaozn EKS Pod Identities as below:

cluster = nil # AWSCDK::EKS::Cluster


AWSCDK::EKS::ServiceAccount.new(self, "ServiceAccount", {
    cluster: cluster,
    name: "test-sa",
    namespace: "default",
    identity_type: AWSCDK::EKS::IdentityType::POD_IDENTITY,
})

When you create the ServiceAccount with the identity_type set to POD_IDENTITY, ServiceAccount contruct will perform the following actions behind the scenes:

  1. It will create an IAM role with the necessary trust policy to allow the "pods.eks.amazonaws.com" principal to assume the role. This trust policy grants the EKS service the permission to retrieve temporary AWS credentials on behalf of the pods using this service account.
  2. It will enable the "Amazon EKS Pod Identity Agent" add-on on the EKS cluster. This add-on is responsible for managing the temporary AWS credentials and making them available to the pods.
  3. It will create an association between the IAM role and the Kubernetes service account. This association allows the pods using this service account to obtain the temporary AWS credentials from the associated IAM role.

This simplifies the process of configuring IAM permissions for your Kubernetes applications running on Amazon EKS. It handles the creation of the IAM role, the installation of the Pod Identity Agent add-on, and the association between the role and the service account, making it easier to manage AWS credentials for your applications.

Applying Kubernetes Resources

The library supports several popular resource deployment mechanisms, among which are:

Kubernetes Manifests

The KubernetesManifest construct or cluster.addManifest method can be used to apply Kubernetes resource manifests to this cluster.

When using cluster.addManifest, the manifest construct is defined within the cluster's stack scope. If the manifest contains attributes from a different stack which depend on the cluster stack, a circular dependency will be created and you will get a synth time error. To avoid this, directly use new KubernetesManifest to create the manifest in the scope of the other stack.

The following examples will deploy the paulbouwer/hello-kubernetes service on the cluster:

cluster = nil # AWSCDK::EKS::Cluster

app_label = {app: "hello-kubernetes"}

deployment = {
    api_version: "apps/v1",
    kind: "Deployment",
    metadata: {name: "hello-kubernetes"},
    spec: {
        replicas: 3,
        selector: {match_labels: app_label},
        template: {
            metadata: {labels: app_label},
            spec: {
                containers: [
                    {
                        name: "hello-kubernetes",
                        image: "paulbouwer/hello-kubernetes:1.5",
                        ports: [{container_port: 8080}],
                    },
                ],
            },
        },
    },
}

service = {
    api_version: "v1",
    kind: "Service",
    metadata: {name: "hello-kubernetes"},
    spec: {
        type: "LoadBalancer",
        ports: [{port: 80, target_port: 8080}],
        selector: app_label,
    },
}

# option 1: use a construct
AWSCDK::EKS::KubernetesManifest.new(self, "hello-kub", {
    cluster: cluster,
    manifest: [deployment, service],
})

# or, option2: use `addManifest`
cluster.add_manifest("hello-kub", service, deployment)

ALB Controller Integration

The KubernetesManifest construct can detect ingress resources inside your manifest and automatically add the necessary annotations so they are picked up by the ALB Controller.

See Alb Controller

To that end, it offers the following properties:

Adding resources from a URL

The following example will deploy the resource manifest hosting on remote server:

// This example is only available in TypeScript

import * as yaml from 'js-yaml';
import * as request from 'sync-request';

declare const cluster: eks.Cluster;
const manifestUrl = 'https://url/of/manifest.yaml';
const manifest = yaml.safeLoadAll(request('GET', manifestUrl).getBody());
cluster.addManifest('my-resource', manifest);

Dependencies

There are cases where Kubernetes resources must be deployed in a specific order. For example, you cannot define a resource in a Kubernetes namespace before the namespace was created.

You can represent dependencies between KubernetesManifests using resource.node.addDependency():

cluster = nil # AWSCDK::EKS::Cluster

namespace = cluster.add_manifest("my-namespace", {
    api_version: "v1",
    kind: "Namespace",
    metadata: {name: "my-app"},
})

service = cluster.add_manifest("my-service", {
    metadata: {
        name: "myservice",
        namespace: "my-app",
    },
    spec: {},
})

service.node.add_dependency(namespace)

NOTE: when a KubernetesManifest includes multiple resources (either directly or through cluster.addManifest()) (e.g. cluster.addManifest('foo', r1, r2, r3,...)), these resources will be applied as a single manifest via kubectl and will be applied sequentially (the standard behavior in kubectl).


Since Kubernetes manifests are implemented as CloudFormation resources in the CDK. This means that if the manifest is deleted from your code (or the stack is deleted), the next cdk deploy will issue a kubectl delete command and the Kubernetes resources in that manifest will be deleted.

Resource Pruning

When a resource is deleted from a Kubernetes manifest, the EKS module will automatically delete these resources by injecting a prune label to all manifest resources. This label is then passed to kubectl apply --prune.

Pruning is enabled by default but can be disabled through the prune option when a cluster is defined:

require 'aws-cdk-lambda-layer-kubectl-v35'


AWSCDK::EKS::Cluster.new(self, "MyCluster", {
    version: AWSCDK::EKS::KubernetesVersion.V1_35,
    prune: false,
    kubectl_layer: AWSCDK::LambdaLayerKubectlV35::KubectlV35Layer.new(self, "kubectl"),
})

Manifests Validation

The kubectl CLI supports applying a manifest by skipping the validation. This can be accomplished by setting the skip_validation flag to true in the KubernetesManifest props.

cluster = nil # AWSCDK::EKS::Cluster

AWSCDK::EKS::KubernetesManifest.new(self, "HelloAppWithoutValidation", {
    cluster: cluster,
    manifest: [{foo: "bar"}],
    skip_validation: true,
})

Helm Charts

The HelmChart construct or cluster.addHelmChart method can be used to add Kubernetes resources to this cluster using Helm.

When using cluster.addHelmChart, the manifest construct is defined within the cluster's stack scope. If the manifest contains attributes from a different stack which depend on the cluster stack, a circular dependency will be created and you will get a synth time error. To avoid this, directly use new HelmChart to create the chart in the scope of the other stack.

The following example will install the NGINX Ingress Controller to your cluster using Helm.

cluster = nil # AWSCDK::EKS::Cluster

# option 1: use a construct
AWSCDK::EKS::HelmChart.new(self, "NginxIngress", {
    cluster: cluster,
    chart: "nginx-ingress",
    repository: "https://helm.nginx.com/stable",
    namespace: "kube-system",
})

# or, option2: use `addHelmChart`
cluster.add_helm_chart("NginxIngress", {
    chart: "nginx-ingress",
    repository: "https://helm.nginx.com/stable",
    namespace: "kube-system",
})

Helm charts will be installed and updated using helm upgrade --install, where a few parameters are being passed down (such as repo, values, version, namespace, wait, timeout, etc). This means that if the chart is added to CDK with the same release name, it will try to update the chart in the cluster.

Additionally, the chart_asset property can be an aws-s3-assets.Asset. This allows the use of local, private helm charts.

require 'aws-cdk-lib'

cluster = nil # AWSCDK::EKS::Cluster

chart_asset = AWSCDK::S3Assets::Asset.new(self, "ChartAsset", {
    path: "/path/to/asset",
})

cluster.add_helm_chart("test-chart", {
    chart_asset: chart_asset,
})

Nested values passed to the values parameter should be provided as a nested dictionary:

cluster = nil # AWSCDK::EKS::Cluster


cluster.add_helm_chart("ExternalSecretsOperator", {
    chart: "external-secrets",
    release: "external-secrets",
    repository: "https://charts.external-secrets.io",
    namespace: "external-secrets",
    values: {
        install_cr_ds: true,
        webhook: {
            port: 9443,
        },
    },
})

Helm chart can come with Custom Resource Definitions (CRDs) defined that by default will be installed by helm as well. However in special cases it might be needed to skip the installation of CRDs, for that the property skip_crds can be used.

cluster = nil # AWSCDK::EKS::Cluster

# option 1: use a construct
AWSCDK::EKS::HelmChart.new(self, "NginxIngress", {
    cluster: cluster,
    chart: "nginx-ingress",
    repository: "https://helm.nginx.com/stable",
    namespace: "kube-system",
    skip_crds: true,
})

OCI Charts

OCI charts are also supported. Also replace the ${VARS} with appropriate values.

cluster = nil # AWSCDK::EKS::Cluster

# option 1: use a construct
AWSCDK::EKS::HelmChart.new(self, "MyOCIChart", {
    cluster: cluster,
    chart: "some-chart",
    repository: "oci://${ACCOUNT_ID}.dkr.ecr.${ACCOUNT_REGION}.amazonaws.com/${REPO_NAME}",
    namespace: "oci",
    version: "0.0.1",
})

Helm charts are implemented as CloudFormation resources in CDK. This means that if the chart is deleted from your code (or the stack is deleted), the next cdk deploy will issue a helm uninstall command and the Helm chart will be deleted.

When there is no release defined, a unique ID will be allocated for the release based on the construct path.

By default, all Helm charts will be installed concurrently. In some cases, this could cause race conditions where two Helm charts attempt to deploy the same resource or if Helm charts depend on each other. You can use chart.node.addDependency() in order to declare a dependency order between charts:

cluster = nil # AWSCDK::EKS::Cluster

chart1 = cluster.add_helm_chart("MyChart", {
    chart: "foo",
})
chart2 = cluster.add_helm_chart("MyChart", {
    chart: "bar",
})

chart2.node.add_dependency(chart1)

CDK8s Charts

CDK8s is an open-source library that enables Kubernetes manifest authoring using familiar programming languages. It is founded on the same technologies as the AWS CDK, such as constructs and jsii.

To learn more about cdk8s, visit the Getting Started tutorials.

The EKS module natively integrates with cdk8s and allows you to apply cdk8s charts on AWS EKS clusters via the cluster.addCdk8sChart method.

In addition to cdk8s, you can also use cdk8s+, which provides higher level abstraction for the core kubernetes api objects. You can think of it like the L2 constructs for Kubernetes. Any other cdk8s based libraries are also supported, for example cdk8s-debore.

To get started, add the following dependencies to your package.json file:

"dependencies": {
  "cdk8s": "^2.0.0",
  "cdk8s-plus-25": "^2.0.0",
  "constructs": "^10.5.0"
}

Note that here we are using cdk8s-plus-25 as we are targeting Kubernetes version 1.25.0. If you operate a different kubernetes version, you should use the corresponding cdk8s-plus-XX library. See Select the appropriate cdk8s+ library for more details.

Similarly to how you would create a stack by extending aws-cdk-lib.Stack, we recommend you create a chart of your own that extends cdk8s.Chart, and add your kubernetes resources to it. You can use aws-cdk construct attributes and properties inside your cdk8s construct freely.

In this example we create a chart that accepts an s3.Bucket and passes its name to a kubernetes pod as an environment variable.

+ my-chart.ts

require 'aws-cdk-lib'
require 'constructs'
require 'cdk8s'
require 'cdk8s-plus-25'

class MyChart < CDK8s::Chart
  def initialize(scope, id, props)
    super(scope, id)

    CDK8sPlus25::Pod.new(self, "Pod", {
        containers: [
            {
                image: "my-image",
                env_variables: {
                    BUCKET_NAME: CDK8sPlus25::EnvValue.from_value(props[:bucket].bucket_name),
                },
            },
        ],
    })
  end
end

Then, in your AWS CDK app:

cluster = nil # AWSCDK::EKS::Cluster


# some bucket..
bucket = AWSCDK::S3::Bucket.new(self, "Bucket")

# create a cdk8s chart and use `cdk8s.App` as the scope.
my_chart = MyChart.new(CDK8s::App.new, "MyChart", {bucket: bucket})

# add the cdk8s chart to the cluster
cluster.add_cdk8s_chart("my-chart", my_chart)

Custom CDK8s Constructs

You can also compose a few stock cdk8s+ constructs into your own custom construct. However, since mixing scopes between aws-cdk and cdk8s is currently not supported, the Construct class you'll need to use is the one from the constructs module, and not from aws-cdk-lib like you normally would. This is why we used new cdk8s.App() as the scope of the chart above.

require 'constructs'
require 'cdk8s'
require 'cdk8s-plus-25'

app = CDK8s::App.new
chart = CDK8s::Chart.new(app, "my-chart")

class LoadBalancedWebService < Constructs::Construct
  def initialize(scope, id, props)
    super(scope, id)

    deployment = CDK8sPlus25::Deployment.new(chart, "Deployment", {
        replicas: props.replicas,
        containers: [CDK8sPlus25::Container.new({image: props.image})],
    })

    deployment.expose_via_service({
        ports: [
            {port: props.port},
        ],
        service_type: CDK8sPlus25::ServiceType::LOAD_BALANCER,
    })
  end
end

Manually importing k8s specs and CRD's

If you find yourself unable to use cdk8s+, or just like to directly use the k8s native objects or CRD's, you can do so by manually importing them using the cdk8s-cli.

See Importing kubernetes objects for detailed instructions.

Patching Kubernetes Resources

The KubernetesPatch construct can be used to update existing kubernetes resources. The following example can be used to patch the hello-kubernetes deployment from the example above with 5 replicas.

cluster = nil # AWSCDK::EKS::Cluster

AWSCDK::EKS::KubernetesPatch.new(self, "hello-kub-deployment-label", {
    cluster: cluster,
    resource_name: "deployment/hello-kubernetes",
    apply_patch: {spec: {replicas: 5}},
    restore_patch: {spec: {replicas: 3}},
})

Querying Kubernetes Resources

The KubernetesObjectValue construct can be used to query for information about kubernetes objects, and use that as part of your CDK application.

For example, you can fetch the address of a LoadBalancer type service:

cluster = nil # AWSCDK::EKS::Cluster

# query the load balancer address
my_service_address = AWSCDK::EKS::KubernetesObjectValue.new(self, "LoadBalancerAttribute", {
    cluster: cluster,
    object_type: "service",
    object_name: "my-service",
    json_path: ".status.loadBalancer.ingress[0].hostname",
})

# pass the address to a lambda function
proxy_function = AWSCDK::Lambda::Function.new(self, "ProxyFunction", {
    handler: "index.handler",
    code: AWSCDK::Lambda::Code.from_inline("my-code"),
    runtime: AWSCDK::Lambda::Runtime.NODEJS_LATEST,
    environment: {
        my_service_address: my_service_address.value,
    },
})

Specifically, since the above use-case is quite common, there is an easier way to access that information:

cluster = nil # AWSCDK::EKS::Cluster

load_balancer_address = cluster.get_service_load_balancer_address("my-service")

Add-ons

Add-ons is a software that provides supporting operational capabilities to Kubernetes applications. The EKS module supports adding add-ons to your cluster using the eks.Addon class.

cluster = nil # AWSCDK::EKS::Cluster


AWSCDK::EKS::Addon.new(self, "Addon", {
    cluster: cluster,
    addon_name: "coredns",
    addon_version: "v1.11.4-eksbuild.2",
    # whether to preserve the add-on software on your cluster but Amazon EKS stops managing any settings for the add-on.
    preserve_on_delete: false,
    configuration_values: {
        replica_count: 2,
    },
})

Using existing clusters

The Amazon EKS library allows defining Kubernetes resources such as Kubernetes manifests and Helm charts on clusters that are not defined as part of your CDK app.

First, you'll need to "import" a cluster to your CDK app. To do that, use the eks.Cluster.fromClusterAttributes() static method:

cluster = AWSCDK::EKS::Cluster.from_cluster_attributes(self, "MyCluster", {
    cluster_name: "my-cluster-name",
    kubectl_role_arn: "arn:aws:iam::1111111:role/iam-role-that-has-masters-access",
})

Then, you can use add_manifest or add_helm_chart to define resources inside your Kubernetes cluster. For example:

cluster = nil # AWSCDK::EKS::Cluster

cluster.add_manifest("Test", {
    api_version: "v1",
    kind: "ConfigMap",
    metadata: {
        name: "myconfigmap",
    },
    data: {
        Key: "value",
        Another: "123454",
    },
})

At the minimum, when importing clusters for kubectl management, you will need to specify:

If the cluster is configured with private-only or private and restricted public Kubernetes endpoint access, you must also specify:

Logging

EKS supports cluster logging for 5 different types of events:

You can enable logging for each one separately using the cluster_logging property. For example:

require 'aws-cdk-lambda-layer-kubectl-v35'


cluster = AWSCDK::EKS::Cluster.new(self, "Cluster", {
    # ...
    version: AWSCDK::EKS::KubernetesVersion.V1_35,
    cluster_logging: [
        AWSCDK::EKS::ClusterLoggingTypes::API,
        AWSCDK::EKS::ClusterLoggingTypes::AUTHENTICATOR,
        AWSCDK::EKS::ClusterLoggingTypes::SCHEDULER,
    ],
    kubectl_layer: AWSCDK::LambdaLayerKubectlV35::KubectlV35Layer.new(self, "kubectl"),
})

NodeGroup Repair Config

You can enable Managed Node Group auto-repair config using enable_node_auto_repair property. For example:

cluster = nil # AWSCDK::EKS::Cluster


cluster.add_nodegroup_capacity("NodeGroup", {
    enable_node_auto_repair: true,
})

Known Issues and Limitations

API Reference

Classes 30

AccessEntryRepresents an access entry in an Amazon EKS cluster. AccessPolicyRepresents an Amazon EKS Access Policy that implements the IAccessPolicy interface. AccessPolicyARNRepresents an Amazon EKS Access Policy ARN. AddonRepresents an Amazon EKS Add-On. ALBControllerConstruct for installing the AWS ALB Contoller on EKS clusters. ALBControllerVersionController version. AWSAuthManages mapping between IAM users and roles to Kubernetes RBAC configuration. CfnAccessEntryCreates an access entry. CfnAddonCreates an Amazon EKS add-on. CfnCapabilityAn object representing a managed capability in an Amazon EKS cluster. CfnClusterCreates an Amazon EKS control plane. CfnFargateProfileCreates an AWS Fargate profile for your Amazon EKS cluster. CfnIdentityProviderConfigAssociates an identity provider configuration to a cluster. CfnNodegroupCreates a managed node group for an Amazon EKS cluster. CfnPodIdentityAssociationAmazon EKS Pod Identity associations provide the ability to manage credentials for your ap ClusterA Cluster represents a managed Kubernetes Service (EKS). EKSOptimizedImageConstruct an Amazon Linux 2 image from the latest EKS Optimized AMI published in SSM. EndpointAccessEndpoint access characteristics. FargateClusterDefines an EKS cluster that runs entirely on AWS Fargate. FargateProfileFargate profiles allows an administrator to declare which pods run on Fargate. HelmChartRepresents a helm chart within the Kubernetes system. KubectlProviderImplementation of Kubectl Lambda. KubernetesManifestRepresents a manifest within the Kubernetes system. KubernetesObjectValueRepresents a value of a specific object deployed in the cluster. KubernetesPatchA CloudFormation resource which applies/restores a JSON patch into a Kubernetes resource. KubernetesVersionKubernetes cluster version. NodegroupThe Nodegroup resource class. OidcProviderNativeIAM OIDC identity providers are entities in IAM that describe an external identity provide OpenIdConnectProviderIAM OIDC identity providers are entities in IAM that describe an external identity provide ServiceAccountService Account.

Interfaces 60

AccessEntryAttributesRepresents the attributes of an access entry. AccessEntryPropsRepresents the properties required to create an Amazon EKS access entry. AccessPolicyNameOptionsRepresents the options required to create an Amazon EKS Access Policy using the `fromAcces AccessPolicyPropsProperties for configuring an Amazon EKS Access Policy. AccessScopeRepresents the scope of an access policy. AddonAttributesRepresents the attributes of an addon for an Amazon EKS cluster. AddonPropsProperties for creating an Amazon EKS Add-On. ALBControllerHelmChartOptionsHelm chart options that can be set for AlbControllerChart To add any new supported values ALBControllerOptionsOptions for `AlbController`. ALBControllerPropsProperties for `AlbController`. AutoScalingGroupCapacityOptionsOptions for adding worker nodes. AutoScalingGroupOptionsOptions for adding an AutoScalingGroup as capacity. AWSAuthMappingAwsAuth mapping. AWSAuthPropsConfiguration props for the AwsAuth construct. BootstrapOptionsEKS node bootstrapping options. CfnAccessEntryPropsProperties for defining a `CfnAccessEntry`. CfnAddonPropsProperties for defining a `CfnAddon`. CfnCapabilityPropsProperties for defining a `CfnCapability`. CfnClusterPropsProperties for defining a `CfnCluster`. CfnFargateProfilePropsProperties for defining a `CfnFargateProfile`. CfnIdentityProviderConfigPropsProperties for defining a `CfnIdentityProviderConfig`. CfnNodegroupPropsProperties for defining a `CfnNodegroup`. CfnPodIdentityAssociationPropsProperties for defining a `CfnPodIdentityAssociation`. ClusterAttributesAttributes for EKS clusters. ClusterOptionsOptions for EKS clusters. ClusterPropsCommon configuration props for EKS clusters. CommonClusterOptionsOptions for configuring an EKS cluster. EKSOptimizedImagePropsProperties for EksOptimizedImage. FargateClusterPropsConfiguration props for EKS Fargate. FargateProfileOptionsOptions for defining EKS Fargate Profiles. FargateProfilePropsConfiguration props for EKS Fargate Profiles. GrantAccessOptionsOptions for granting access to a cluster. HelmChartOptionsHelm Chart options. HelmChartPropsHelm Chart properties. IAccessEntryRepresents an access entry in an Amazon EKS cluster. IAccessPolicyRepresents an access policy that defines the permissions and scope for a user or role to a IAddonRepresents an Amazon EKS Add-On. IClusterAn EKS cluster. IKubectlProviderImported KubectlProvider that can be used in place of the default one created by CDK. IngressLoadBalancerAddressOptionsOptions for fetching an IngressLoadBalancerAddress. INodegroupNodeGroup interface. KubectlProviderAttributesKubectl Provider Attributes. KubectlProviderPropsProperties for a KubectlProvider. KubernetesManifestOptionsOptions for `KubernetesManifest`. KubernetesManifestPropsProperties for KubernetesManifest. KubernetesObjectValuePropsProperties for KubernetesObjectValue. KubernetesPatchPropsProperties for KubernetesPatch. LaunchTemplateSpecLaunch template property specification. NodegroupOptionsThe Nodegroup Options for addNodeGroup() method. NodegroupPropsNodeGroup properties interface. NodegroupRemoteAccessThe remote access (SSH) configuration to use with your node group. OidcProviderNativePropsInitialization properties for `OidcProviderNative`. OpenIdConnectProviderPropsInitialization properties for `OpenIdConnectProvider`. RemoteNodeNetworkNetwork configuration of nodes run on-premises with EKS Hybrid Nodes. RemotePodNetworkNetwork configuration of pods run on-premises with EKS Hybrid Nodes. SelectorFargate profile selector. ServiceAccountOptionsOptions for `ServiceAccount`. ServiceAccountPropsProperties for defining service accounts. ServiceLoadBalancerAddressOptionsOptions for fetching a ServiceLoadBalancerAddress. TaintSpecTaint interface.

Enums 16

AccessEntryTypeRepresents the different types of access entries that can be used in an Amazon EKS cluster AccessScopeTypeRepresents the scope type of an access policy. ALBSchemeALB Scheme. AuthenticationModeRepresents the authentication mode for an Amazon EKS cluster. CapacityTypeCapacity type of the managed node group. ClusterLoggingTypesEKS cluster logging types. CoreDNSComputeTypeThe type of compute resources to use for CoreDNS. CpuArchCPU architecture. DefaultCapacityTypeThe default capacity type for the cluster. IdentityTypeEnum representing the different identity types that can be used for a Kubernetes service a IPFamilyEKS cluster IP family. MachineImageTypeThe machine image type. NodegroupAmiTypeThe AMI type for your node group. NodeTypeWhether the worker nodes should support GPU or just standard instances. PatchTypeValues for `kubectl patch` --type argument. TaintEffectEffect types of kubernetes node taint.