Sunday, January 8, 2023

How to create an AWS EKS cluster using Terraform

Create an Amazon Elastic Kubernetes Service (EKS) cluster using Terraform, you can use the aws_eks_cluster resource and below is the an example of how you can create an EKS cluster with Terraform:

 

 # Create the EKS cluster
resource "aws_eks_cluster" "example" {
  name     = "example"
  role_arn = "${aws_iam_role.example.arn}"

  vpc_config {
    security_group_ids = [
      "${aws_security_group.example.id}",
    ]

    subnet_ids = [
      "${aws_subnet.example[0].id}",
      "${aws_subnet.example[1].id}",
      "${aws_subnet.example[2].id}",
    ]
  }
}

# Create the IAM role for the EKS cluster
resource "aws_iam_role" "example" {
  name = "example"

  assume_role_policy = <<EOF
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Action": "sts:AssumeRole",
      "Principal": {
        "Service": "eks.amazonaws.com"
      },
      "Effect": "Allow",
      "Sid": ""
    }
  ]
}
EOF
}

# Create a security group for the EKS cluster
resource "aws_security_group" "example" {
  name        = "example"
  description = "Security group for the EKS cluster"

  ingress {
    from_port   = 0
    to_port     = 0
    protocol    = "-1"
    cidr_blocks = ["0.0.0.0/0"]
  }

  egress {
    from_port   = 0
    to_port     = 0
    protocol    = "-1"
    cidr_blocks = ["0.0.0.0/0"]
  }

  tags = {
    Name = "example"
  }
}

# Create the subnets for the EKS cluster
resource "aws_subnet" "example" {
  count             = 3
  vpc_id            = "${aws_vpc.example.id}"
  cidr_block        = "${cidrsubnet(aws_vpc.example.cidr_block, 8, count.index)}"
  availability_zone = "${data.aws_availability_zones.all.names[count.index]}"

  tags = {
    Name = "example-${count.index}"
  }
}

# Create the VPC for the EKS cluster
resource "aws_vpc" "example" {
  cidr_block = "10.0.0.0/16"

  tags = {
    Name = "example"
  }
}


The above example syntax creates an EKS cluster named "example", an IAM role for the cluster, a security group for the cluster, and a VPC with three subnets for the cluster.

To use this example, you will need to replace the placeholder values (such as example and 0.0.0.0/0) with your data.

No comments:

Post a Comment