Skip to content

Resource: awsEksCluster

Manages an EKS Cluster.

Hands-on: For an example of awsEksCluster in use, follow the Provision an EKS Cluster tutorial on HashiCorp Learn.

Example Usage

Basic Usage

import * as cdktf from "cdktf";
/*Provider bindings are generated by running cdktf get.
See https://cdk.tf/provider-generation for more details.*/
import * as aws from "./.gen/providers/aws";
const awsEksClusterExample = new aws.eksCluster.EksCluster(this, "example", {
  depends_on: [
    "${aws_iam_role_policy_attachment.example-AmazonEKSClusterPolicy}",
    "${aws_iam_role_policy_attachment.example-AmazonEKSVPCResourceController}",
  ],
  name: "example",
  roleArn: "${aws_iam_role.example.arn}",
  vpcConfig: {
    subnetIds: ["${aws_subnet.example1.id}", "${aws_subnet.example2.id}"],
  },
});
new cdktf.TerraformOutput(this, "endpoint", {
  value: awsEksClusterExample.endpoint,
});
new cdktf.TerraformOutput(this, "kubeconfig-certificate-authority-data", {
  value: `\${${awsEksClusterExample.certificateAuthority.fqn}[0].data}`,
});

Example IAM Role for EKS Cluster

/*Provider bindings are generated by running cdktf get.
See https://cdk.tf/provider-generation for more details.*/
import * as aws from "./.gen/providers/aws";
const dataAwsIamPolicyDocumentAssumeRole =
  new aws.dataAwsIamPolicyDocument.DataAwsIamPolicyDocument(
    this,
    "assume_role",
    {
      statement: [
        {
          actions: ["sts:AssumeRole"],
          effect: "Allow",
          principals: [
            {
              identifiers: ["eks.amazonaws.com"],
              type: "Service",
            },
          ],
        },
      ],
    }
  );
const awsIamRoleExample = new aws.iamRole.IamRole(this, "example", {
  assumeRolePolicy: dataAwsIamPolicyDocumentAssumeRole.json,
  name: "eks-cluster-example",
});
new aws.iamRolePolicyAttachment.IamRolePolicyAttachment(
  this,
  "example-AmazonEKSClusterPolicy",
  {
    policyArn: "arn:aws:iam::aws:policy/AmazonEKSClusterPolicy",
    role: awsIamRoleExample.name,
  }
);
new aws.iamRolePolicyAttachment.IamRolePolicyAttachment(
  this,
  "example-AmazonEKSVPCResourceController",
  {
    policyArn: "arn:aws:iam::aws:policy/AmazonEKSVPCResourceController",
    role: awsIamRoleExample.name,
  }
);

Enabling Control Plane Logging

EKS Control Plane Logging can be enabled via the enabledClusterLogTypes argument. To manage the CloudWatch Log Group retention period, the awsCloudwatchLogGroup resource can be used.

-> The below configuration uses dependsOn to prevent ordering issues with EKS automatically creating the log group first and a variable for naming consistency. Other ordering and naming methodologies may be more appropriate for your environment.

import * as cdktf from "cdktf";
/*Provider bindings are generated by running cdktf get.
See https://cdk.tf/provider-generation for more details.*/
import * as aws from "./.gen/providers/aws";
/*Terraform Variables are not always the best fit for getting inputs in the context of Terraform CDK.
You can read more about this at https://cdk.tf/variables*/
const clusterName = new cdktf.TerraformVariable(this, "cluster_name", {
  default: "example",
});
const awsCloudwatchLogGroupExample =
  new aws.cloudwatchLogGroup.CloudwatchLogGroup(this, "example", {
    name: `/aws/eks/\${${clusterName.value}}/cluster`,
    retentionInDays: 7,
  });
const awsEksClusterExample = new aws.eksCluster.EksCluster(this, "example_2", {
  depends_on: [`\${${awsCloudwatchLogGroupExample.fqn}}`],
  enabledClusterLogTypes: ["api", "audit"],
  name: clusterName.value,
});
/*This allows the Terraform resource name to match the original name. You can remove the call if you don't need them to match.*/
awsEksClusterExample.overrideLogicalId("example");

Enabling IAM Roles for Service Accounts

Only available on Kubernetes version 1.13 and 1.14 clusters created or upgraded on or after September 3, 2019. For more information about this feature, see the EKS User Guide.

/*Provider bindings are generated by running cdktf get.
See https://cdk.tf/provider-generation for more details.*/
import * as aws from "./.gen/providers/aws";
import * as tls from "./.gen/providers/tls";
/*The following providers are missing schema information and might need manual adjustments to synthesize correctly: tls.
For a more precise conversion please use the --provider flag in convert.*/
const awsEksClusterExample = new aws.eksCluster.EksCluster(this, "example", {});
const dataTlsCertificateExample = new tls.dataTlsCertificate.DataTlsCertificate(
  this,
  "example_1",
  {
    url: `\${${awsEksClusterExample.identity.fqn}[0].oidc[0].issuer}`,
  }
);
/*This allows the Terraform resource name to match the original name. You can remove the call if you don't need them to match.*/
dataTlsCertificateExample.overrideLogicalId("example");
const awsIamOpenidConnectProviderExample =
  new aws.iamOpenidConnectProvider.IamOpenidConnectProvider(this, "example_2", {
    clientIdList: ["sts.amazonaws.com"],
    thumbprintList: `\${${dataTlsCertificateExample.certificates.fqn}[*].sha1_fingerprint}`,
    url: dataTlsCertificateExample.url,
  });
/*This allows the Terraform resource name to match the original name. You can remove the call if you don't need them to match.*/
awsIamOpenidConnectProviderExample.overrideLogicalId("example");
const dataAwsIamPolicyDocumentExampleAssumeRolePolicy =
  new aws.dataAwsIamPolicyDocument.DataAwsIamPolicyDocument(
    this,
    "example_assume_role_policy",
    {
      statement: [
        {
          actions: ["sts:AssumeRoleWithWebIdentity"],
          condition: [
            {
              test: "StringEquals",
              values: ["system:serviceaccount:kube-system:aws-node"],
              variable: `\${replace(${awsIamOpenidConnectProviderExample.url}, "https://", "")}:sub`,
            },
          ],
          effect: "Allow",
          principals: [
            {
              identifiers: [awsIamOpenidConnectProviderExample.arn],
              type: "Federated",
            },
          ],
        },
      ],
    }
  );
const awsIamRoleExample = new aws.iamRole.IamRole(this, "example_4", {
  assumeRolePolicy: dataAwsIamPolicyDocumentExampleAssumeRolePolicy.json,
  name: "example",
});
/*This allows the Terraform resource name to match the original name. You can remove the call if you don't need them to match.*/
awsIamRoleExample.overrideLogicalId("example");

EKS Cluster on AWS Outpost

Creating a local Amazon EKS cluster on an AWS Outpost

/*Provider bindings are generated by running cdktf get.
See https://cdk.tf/provider-generation for more details.*/
import * as aws from "./.gen/providers/aws";
const awsIamRoleExample = new aws.iamRole.IamRole(this, "example", {
  assumeRolePolicy:
    "${data.aws_iam_policy_document.example_assume_role_policy.json}",
  name: "example",
});
const awsEksClusterExample = new aws.eksCluster.EksCluster(this, "example_1", {
  name: "example-cluster",
  outpostConfig: {
    controlPlaneInstanceType: "m5d.large",
    outpostArns: ["${data.aws_outposts_outpost.example.arn}"],
  },
  roleArn: awsIamRoleExample.arn,
  vpcConfig: {
    endpointPrivateAccess: true,
    endpointPublicAccess: false,
  },
});
/*This allows the Terraform resource name to match the original name. You can remove the call if you don't need them to match.*/
awsEksClusterExample.overrideLogicalId("example");

After adding inline IAM Policies (e.g., awsIamRolePolicy resource) or attaching IAM Policies (e.g., awsIamPolicy resource and awsIamRolePolicyAttachment resource) with the desired permissions to the IAM Role, annotate the Kubernetes service account (e.g., kubernetesServiceAccount resource) and recreate any pods.

Argument Reference

The following arguments are required:

  • name – (Required) Name of the cluster. Must be between 1-100 characters in length. Must begin with an alphanumeric character, and must only contain alphanumeric characters, dashes and underscores (^[09AZaZ][aZaZ09\_]+$).
  • roleArn - (Required) ARN of the IAM role that provides permissions for the Kubernetes control plane to make calls to AWS API operations on your behalf. Ensure the resource configuration includes explicit dependencies on the IAM Role permissions by adding dependsOn if using the awsIamRolePolicy resource or awsIamRolePolicyAttachment resource, otherwise EKS cannot delete EKS managed EC2 infrastructure such as Security Groups on EKS Cluster deletion.
  • vpcConfig - (Required) Configuration block for the VPC associated with your cluster. Amazon EKS VPC resources have specific requirements to work properly with Kubernetes. For more information, see Cluster VPC Considerations and Cluster Security Group Considerations in the Amazon EKS User Guide. Detailed below. Also contains attributes detailed in the Attributes section.

The following arguments are optional:

  • enabledClusterLogTypes - (Optional) List of the desired control plane logging to enable. For more information, see Amazon EKS Control Plane Logging.
  • encryptionConfig - (Optional) Configuration block with encryption configuration for the cluster. Only available on Kubernetes 1.13 and above clusters created after March 6, 2020. Detailed below.
  • kubernetesNetworkConfig - (Optional) Configuration block with kubernetes network configuration for the cluster. Detailed below. If removed, Terraform will only perform drift detection if a configuration value is provided.
  • outpostConfig - (Optional) Configuration block representing the configuration of your local Amazon EKS cluster on an AWS Outpost. This block isn't available for creating Amazon EKS clusters on the AWS cloud.
  • tags - (Optional) Key-value map of resource tags. If configured with a provider defaultTags configuration block present, tags with matching keys will overwrite those defined at the provider-level.
  • version – (Optional) Desired Kubernetes master version. If you do not specify a value, the latest available version at resource creation is used and no upgrades will occur except those automatically triggered by EKS. The value must be configured and increased to upgrade the version when desired. Downgrades are not supported by EKS.

encryptionConfig

The following arguments are supported in the encryptionConfig configuration block:

  • provider - (Required) Configuration block with provider for encryption. Detailed below.
  • resources - (Required) List of strings with resources to be encrypted. Valid values: secrets.

provider

The following arguments are supported in the provider configuration block:

vpc_config Arguments

  • endpointPrivateAccess - (Optional) Whether the Amazon EKS private API server endpoint is enabled. Default is false.
  • endpointPublicAccess - (Optional) Whether the Amazon EKS public API server endpoint is enabled. Default is true.
  • publicAccessCidrs - (Optional) List of CIDR blocks. Indicates which CIDR blocks can access the Amazon EKS public API server endpoint when enabled. EKS defaults this to a list with 0000/0. Terraform will only perform drift detection of its value when present in a configuration.
  • securityGroupIds – (Optional) List of security group IDs for the cross-account elastic network interfaces that Amazon EKS creates to use to allow communication between your worker nodes and the Kubernetes control plane.
  • subnetIds – (Required) List of subnet IDs. Must be in at least two different availability zones. Amazon EKS creates cross-account elastic network interfaces in these subnets to allow communication between your worker nodes and the Kubernetes control plane.

kubernetesNetworkConfig

The following arguments are supported in the kubernetesNetworkConfig configuration block:

  • serviceIpv4Cidr - (Optional) The CIDR block to assign Kubernetes pod and service IP addresses from. If you don't specify a block, Kubernetes assigns addresses from either the 10.100.0.0/16 or 172.20.0.0/16 CIDR blocks. We recommend that you specify a block that does not overlap with resources in other networks that are peered or connected to your VPC. You can only specify a custom CIDR block when you create a cluster, changing this value will force a new cluster to be created. The block must meet the following requirements:

    • Within one of the following private IP address blocks: 10.0.0.0/8, 172.16.0.0/12, or 192.168.0.0/16.

    • Doesn't overlap with any CIDR block assigned to the VPC that you selected for VPC.

    • Between /24 and /12.

    • ipFamily - (Optional) The IP family used to assign Kubernetes pod and service addresses. Valid values are ipv4 (default) and ipv6. You can only specify an IP family when you create a cluster, changing this value will force a new cluster to be created.

outpostConfig

The following arguments are supported in the outpostConfig configuration block:

  • controlPlaneInstanceType - (Required) The Amazon EC2 instance type that you want to use for your local Amazon EKS cluster on Outposts. The instance type that you specify is used for all Kubernetes control plane instances. The instance type can't be changed after cluster creation. Choose an instance type based on the number of nodes that your cluster will have. If your cluster will have:

    • 1–20 nodes, then we recommend specifying a large instance type.

    • 21–100 nodes, then we recommend specifying an xlarge instance type.

    • 101–250 nodes, then we recommend specifying a 2xlarge instance type.

    For a list of the available Amazon EC2 instance types, see Compute and storage in AWS Outposts rack features The control plane is not automatically scaled by Amazon EKS.

  • controlPlanePlacement - (Optional) An object representing the placement configuration for all the control plane instances of your local Amazon EKS cluster on AWS Outpost. The following arguments are supported in the controlPlanePlacement configuration block:

    • groupName - (Required) The name of the placement group for the Kubernetes control plane instances. This setting can't be changed after cluster creation.
  • outpostArns - (Required) The ARN of the Outpost that you want to use for your local Amazon EKS cluster on Outposts. This argument is a list of arns, but only a single Outpost ARN is supported currently.

Attributes Reference

In addition to all arguments above, the following attributes are exported:

  • arn - ARN of the cluster.
  • certificateAuthority - Attribute block containing certificateAuthorityData for your cluster. Detailed below.
  • clusterId - The ID of your local Amazon EKS cluster on the AWS Outpost. This attribute isn't available for an AWS EKS cluster on AWS cloud.
  • createdAt - Unix epoch timestamp in seconds for when the cluster was created.
  • endpoint - Endpoint for your Kubernetes API server.
  • id - Name of the cluster.
  • identity - Attribute block containing identity provider information for your cluster. Only available on Kubernetes version 1.13 and 1.14 clusters created or upgraded on or after September 3, 2019. Detailed below.
  • kubernetesNetworkConfigServiceIpv6Cidr - The CIDR block that Kubernetes pod and service IP addresses are assigned from if you specified ipv6 for ipFamily when you created the cluster. Kubernetes assigns service addresses from the unique local address range (fc00::/7) because you can't specify a custom IPv6 CIDR block when you create the cluster.
  • platformVersion - Platform version for the cluster.
  • status - Status of the EKS cluster. One of creating, active, deleting, failed.
  • tagsAll - Map of tags assigned to the resource, including those inherited from the provider defaultTags configuration block.
  • vpcConfig - Configuration block argument that also includes attributes for the VPC associated with your cluster. Detailed below.

certificateAuthority

  • data - Base64 encoded certificate data required to communicate with your cluster. Add this to the certificateAuthorityData section of the kubeconfig file for your cluster.

identity

  • oidc - Nested block containing OpenID Connect identity provider information for the cluster. Detailed below.

oidc

  • issuer - Issuer URL for the OpenID Connect identity provider.

vpc_config Attributes

  • clusterSecurityGroupId - Cluster security group that was created by Amazon EKS for the cluster. Managed node groups use this security group for control-plane-to-data-plane communication.
  • vpcId - ID of the VPC associated with your cluster.

Timeouts

Configuration options:

  • create - (Default 30M)
  • update - (Default 60M) Note that the update timeout is used separately for both version and vpcConfig update timeouts.
  • delete - (Default 15M)

Import

EKS Clusters can be imported using the name, e.g.,

$ terraform import aws_eks_cluster.my_cluster my_cluster