ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • tfcloud 를 통한 EKS Terraform 설정
    k8s 2023. 12. 20. 14:44

    사전작업


    1. tfcloud 가입

    2. 초기 셋팅

     

    설정

    1. provider -> aws : aws cli 설치가 되어있어야 한다.

    2. aws configure 로 계정에 로그인이 되어있어야 한다.

    3. aws 에서 access_key , sevret_key 도 확인 해야한다.

    4. cluster name은 자동으로 설정 해주었다.

     

    혹시 임의로 설정하고 싶으면 아래 파일을 추가해주면 된다.

    #terraform.auto.tfvars
    vpc_name        = "test-vpc"
    vpc_cidr        = "192.168.0.0/16"
    cluster_name    = "test-cluster"
    cluster_version = "1.27"

     


    main.tf

    provider "aws" {
      region = "ap-northeast-2"
    }
    
    # Filter out local zones, which are not currently supported
    # with managed node groups
    data "aws_availability_zones" "available" {
      filter {
        name   = "opt-in-status"
        values = ["opt-in-not-required"]
      }
    }
    
    locals {
      cluster_name = "goorm-eks-${random_string.suffix.result}"
    }
    
    resource "random_string" "suffix" {
      length  = 8
      special = false
    }

     

    eks.tf

    1번 그륩은 최소 1개, 최대 3개의 인스턴스를 사용하며 원하는 크기가 2개이다.

    2번 그륩은 최소 1개, 최대 2개의 인스턴스를 사용하며 원하는 크기가 1개이다.

    ec2에 생성된 인스턴스는 총 3개이다.

    module "eks" {
      source  = "terraform-aws-modules/eks/aws"
      version = "19.15.3"
    
      cluster_name    = local.cluster_name
      cluster_version = "1.27"
    
      vpc_id                         = module.vpc.vpc_id
      subnet_ids                     = module.vpc.private_subnets
      cluster_endpoint_public_access = true
    
      eks_managed_node_group_defaults = {
        ami_type = "AL2_x86_64"
    
      }
    
      eks_managed_node_groups = {
        one = {
          name = "node-group-1"
    
          instance_types = ["t3.small"]
    
          min_size     = 1
          max_size     = 3
          desired_size = 2
        }
    
        two = {
          name = "node-group-2"
    
          instance_types = ["t3.small"]
    
          min_size     = 1
          max_size     = 2
          desired_size = 1
        }
      }
    }

    network.tf

    subnet 총 public, private  합쳐 6개 구성

    module "vpc" {
      source  = "terraform-aws-modules/vpc/aws"
      version = "5.0.0"
    
      name = "goorm-eks-vpc"
    
      cidr = "10.0.0.0/16"
      azs  = slice(data.aws_availability_zones.available.names, 0, 3)
    
      private_subnets = ["10.0.1.0/24", "10.0.2.0/24", "10.0.3.0/24"]
      public_subnets  = ["10.0.4.0/24", "10.0.5.0/24", "10.0.6.0/24"]
    
      enable_nat_gateway   = true
      single_nat_gateway   = true
      enable_dns_hostnames = true
    
      public_subnet_tags = {
        "kubernetes.io/cluster/${local.cluster_name}" = "shared"
        "kubernetes.io/role/elb"                      = 1
      }
    
      private_subnet_tags = {
        "kubernetes.io/cluster/${local.cluster_name}" = "shared"
        "kubernetes.io/role/internal-elb"             = 1
      }
    }

    policy.tf

    iam설정과 ebs 연결을 위해서 tf code 를 작성

    data "aws_iam_policy" "ebs_csi_policy" {
      arn = "arn:aws:iam::aws:policy/service-role/AmazonEBSCSIDriverPolicy"
    }
    
    module "irsa-ebs-csi" {
      source  = "terraform-aws-modules/iam/aws//modules/iam-assumable-role-with-oidc"
      version = "4.7.0"
    
      create_role                   = true
      role_name                     = "AmazonEKSTFEBSCSIRole-${module.eks.cluster_name}"
      provider_url                  = module.eks.oidc_provider
      role_policy_arns              = [data.aws_iam_policy.ebs_csi_policy.arn]
      oidc_fully_qualified_subjects = ["system:serviceaccount:kube-system:ebs-csi-controller-sa"]
    }
    
    resource "aws_eks_addon" "ebs-csi" {
      cluster_name             = module.eks.cluster_name
      addon_name               = "aws-ebs-csi-driver"
      addon_version            = "v1.20.0-eksbuild.1"
      service_account_role_arn = module.irsa-ebs-csi.iam_role_arn
      tags = {
        "eks_addon" = "ebs-csi"
        "terraform" = "true"
      }
    }

    variables.tf

    aws config와 일치시켜주고 추후 다른 설정이 필요하면 이 tf 파일에 추가 합니다.

    # Copyright (c) HashiCorp, Inc.
    # SPDX-License-Identifier: MPL-2.0
    
    variable "region" {
      description = "AWS region"
      type        = string
      default     = "ap-northeast-2"
    }

    terraform.tf

    terraform에 형성될 테라폼 워크스페이스를 설정 버전은 튜토리얼에 나온 것으로 설정

    # Copyright (c) HashiCorp, Inc.
    # SPDX-License-Identifier: MPL-2.0
    
    terraform {
      cloud {
        organization = "2jo"
        workspaces {
          name = "goorm"
        }
      }
    
      required_providers {
        aws = {
          source  = "hashicorp/aws"
          version = "~> 5.7.0"
        }
    
        random = {
          source  = "hashicorp/random"
          version = "~> 3.5.1"
        }
    
        tls = {
          source  = "hashicorp/tls"
          version = "~> 4.0.4"
        }
    
        cloudinit = {
          source  = "hashicorp/cloudinit"
          version = "~> 2.3.2"
        }
      }
    
      required_version = "~> 1.3"
    }

     

    outputs.tf

    # Copyright (c) HashiCorp, Inc.
    # SPDX-License-Identifier: MPL-2.0
    
    output "cluster_endpoint" {
      description = "Endpoint for EKS control plane"
      value       = module.eks.cluster_endpoint
    }
    
    output "cluster_security_group_id" {
      description = "Security group ids attached to the cluster control plane"
      value       = module.eks.cluster_security_group_id
    }
    
    output "region" {
      description = "AWS region"
      value       = "ap-northeast-2"
    }
    
    output "cluster_name" {
      description = "Kubernetes Cluster Name"
      value       = module.eks.cluster_name
    }

     

     

    terraform 실행


    1. 초기 설정 파일을 모두 생성했고 이제 terraform login으로 terraform cloud에 로그인 해줍니다.

    2. terraform init 으로 모듈을 세팅해주고

    3. terraform plan 명령어를 실행하면 에러가 발생할겁니다. 자격증명에 실패했다고

    이는 실행환경에서 aws credential을 찾을 수 없을 때 방생하며 각자의 실행환경에 aws credential을 추가해주면 해결됩니다.

     

    해결방법


    TF Cloud 에서 workspace -> variables에 다음과 같이 환경변수를 넣어줍니다.

    이때 Key 부분에 AWS_ACCESS_KEY_ID AWS_SECRET_ACCESS_KEY 무조껀 대문자로 작성 해야 됩니다.

    소문자로 작성했더니 자격증명 실패 에러가 다시 발생..

    참고로 위에서 설정한 AWS_ACCESS_KEY_ID ,AWS_SECRET_ACCESS_KEY 가 기억이 나질않는다면

    cat ~/.aws/credentials

    해당 명령어로 확인하시면 됩니다.

     

    이제 아래 명령어로 모듈을 실행해주고 모듈실행이 완료되면 apply해줍시다!

    terraform plan
    terraform apply

     

    Apply complete! Resources: 63 added, 0 changed, 0 destroyed.
    
    Outputs:
    cluster_name = "goorm-eks-1fTO4FOO"
    cluster_security_group_id = "sg-052162565dc7606fb"
    region = "ap-northeast-2"
    cluster_endpoint = "https://1D6D416F31509E22B7FECBED0BE59FC1.yl4.ap-northeast-2.eks.amazonaws.com"

    터미널에 위와 같이 complete 되었다고 나오고 cluster_name이 랜덤으로 부여가 됩니다.

     

    해당하는 name 과  region 으로 클러스터와 통신시켜주면 끝.

    aws eks update-kubeconfig --region ap-northeast-2 --name goorm-eks-1fTO4FOO

    정상적으로 연결되었습니다.

     kubectl get nodes
    NAME                                            STATUS   ROLES    AGE    VERSION
    ip-10-0-1-128.ap-northeast-2.compute.internal   Ready    <none>   118m   v1.27.7-eks-e71965b
    ip-10-0-2-242.ap-northeast-2.compute.internal   Ready    <none>   118m   v1.27.7-eks-e71965b
    ip-10-0-2-47.ap-northeast-2.compute.internal    Ready    <none>   118m   v1.27.7-eks-e71965b

     

    ebs csi driver 작동하는지 확인

    https://docs.aws.amazon.com/ko_kr/eks/latest/userguide/ebs-sample-app.html

    마무리


    추후에 테라폼을 다시 사용할 수도 있기도 하고 나중에 비교 해보면 재밌지 않을까 해서 또 기억에는 한계가 있기 때문에 기록!!

Designed by Tistory.