使用terraform在aws上创建一个eks集群
-
首先,需要安装terraform工具和AWS CLI,并配置好AWS CLI的访问密钥和密钥ID。
-
创建一个新的目录,用于存储terraform配置文件。
-
在该目录下创建一个名为“provider.tf”的文件,用于指定AWS作为terraform的提供者。文件内容如下:
provider "aws" {
region = "us-west-2"
}
- 在该目录下创建一个名为“eks.tf”的文件,用于定义EKS集群的资源。文件内容如下:
resource "aws_vpc" "eks_vpc" {
cidr_block = "10.0.0.0/16"
tags = {
Name = "eks-vpc"
}
}
resource "aws_internet_gateway" "eks_gateway" {
vpc_id = aws_vpc.eks_vpc.id
tags = {
Name = "eks-gateway"
}
}
resource "aws_subnet" "eks_subnet" {
vpc_id = aws_vpc.eks_vpc.id
cidr_block = "10.0.1.0/24"
availability_zone = "us-west-2a"
tags = {
Name = "eks-subnet"
}
}
resource "aws_eks_cluster" "eks_cluster" {
name = "eks-cluster"
role_arn = aws_iam_role.eks_role.arn
vpc_config {
subnet_ids = [aws_subnet.eks_subnet.id]
}
}
resource "aws_iam_role" "eks_role" {
name = "eks-role"
assume_role_policy = jsonencode({
Version = "2012-10-17"
Statement = [
{
Effect = "Allow"
Principal = {
Service = "eks.amazonaws.com"
}
Action = "sts:AssumeRole"
}
]
})
}
resource "aws_iam_role_policy_attachment" "eks_policy_attachment" {
policy_arn = "arn:aws:iam::aws:policy/AmazonEKSClusterPolicy"
role = aws_iam_role.eks_role.name
}
resource "aws_security_group" "eks_security_group" {
name = "eks-security-group"
vpc_id = aws_vpc.eks_vpc.id
ingress {
from_port = 0
to_port = 65535
protocol = "tcp"
cidr_blocks = ["0.0.0.0/0"]
}
egress {
from_port = 0
to_port = 65535
protocol = "tcp"
cidr_blocks = ["0.0.0.0/0"]
}
}
resource "aws_eks_node_group" "eks_node_group" {
cluster_name = aws_eks_cluster.eks_cluster.name
node_group_name = "eks-node-group"
node_role_arn = aws_iam_role.eks_role.arn
subnets = [aws_subnet.eks_subnet.id]
instance_types = ["t2.small"]
scaling_config {
desired_size = 2
max_size = 2
min_size = 1
}
remote_access {
ec2_ssh_key = "eks-ssh"
source_security_group_id = aws_security_group.eks_security_group.id
}
}
-
运行“terraform init”初始化terraform。
-
运行“terraform apply”创建EKS集群。
-
创建完毕后,可以使用AWS CLI获取集群的kubeconfig文件,然后使用kubectl命令连接到集群。
aws eks update-kubeconfig --name eks-cluster
kubectl get nodes
- 当不再需要该EKS集群时,可以运行“terraform destroy”删除所有相关的资源。
原文地址: https://www.cveoy.top/t/topic/knc 著作权归作者所有。请勿转载和采集!