본문 바로가기

♻ Terraform(테라폼)/👉 Terraformer

Terraformer를 통해 EKS 리소스 가져오기 (클러스터, 노드그룹)

# EKS 클러스터에 Tag 정보를 추가 후 Terraformer를 통해 리소스를 Import 하기

1. EKS와 NodeGroup에 태그정보 추가하기

- EKS 클러스터에 Tag 정보를 보면 Name은 이미 다른 이름으로 태깅이 되어 있었다.

다른 키 값을 Name 값으로 입력을 해야하는데 뭐가 좋을까 고민하다가 re_seung 라는 유니크한 값으로 키값을 설정 하기로 했다.

- 태그 추가는 태그 관리 항목에서 할 수 있으며 별도로 설명은 하지 않겠다.

- 노드 그룹 같은 경우는 편집 → 태그를 추가 해야한다.

태그 결과는 아래와 같다. (클러스터 태깅)

태그 결과 (노드그룹 태깅)

2. Terraformer를 활용하여 위에서 설정한 태깅 정보를 기반으로 Import 하는 작업을 해보자.

마음 같아서는 잘~~~? 됐으면 좋겠는데...

terraformer 코드는 아래와 같다.

# 기본명령어
terraformer import aws \
--resources={resource_name} \
--regions=ap-northeast-2 \
--filter="Name=tags.{tags_name};Value={tags_value_name}"

# 적용명령어
terraformer import aws \
--resources=eks \
--regions=ap-northeast-2 \
--filter="Name=tags.re_seung;Value=terraformer-test-01"

결과는 아래와 같다.

2023/03/22 23:39:30 aws importing region ap-northeast-2
2023/03/22 23:39:31 aws importing... eks
2023/03/22 23:39:31 aws done importing eks
2023/03/22 23:39:31 Number of resources for service eks: 2
2023/03/22 23:39:31 Refreshing state... aws_eks_cluster.tfer--Cluster-DEV
2023/03/22 23:39:31 Refreshing state... aws_eks_node_group.tfer--nodegroup-DEV
2023/03/22 23:39:31 Filtered number of resources for service eks: 2
2023/03/22 23:39:31 aws Connecting....
2023/03/22 23:39:31 aws save eks
2023/03/22 23:39:31 aws save tfstate for eks

3. Generated된 코드 확인하기

- 리스트는 아래와 같다.

- 주요 파일을 열어보자

eks_cluster.tf

resource "aws_eks_cluster" "tfer--Cluster-DEV" {
  kubernetes_network_config {
    service_ipv4_cidr = "172.20.0.0/16"
  }

  name     = "Cluster-DEV"
  role_arn = "arn:aws:iam::222222222222:role/eksctl-Cluster-DEV-cluster-ServiceRole"

  tags = {
    Name                                          = "eksctl-Cluster-DEV-cluster/ControlPlane"
    "alpha.eksctl.io/cluster-name"                = "Cluster-DEV"
    "alpha.eksctl.io/cluster-oidc-enabled"        = "true"
    "alpha.eksctl.io/eksctl-version"              = "0.122.0"
    "eksctl.cluster.k8s.io/v1alpha1/cluster-name" = "Cluster-DEV"
    re_seung                                      = "terraformer-test-01"
  }

  version = "1.25"

  vpc_config {
    endpoint_private_access = "false"
    endpoint_public_access  = "true"
    public_access_cidrs     = ["0.0.0.0/0"]
    security_group_ids      = ["sg-00000000000000000"]
    subnet_ids              = ["subnet-000000000000000", "subnet-0000000000000000"]
  }
}

eks_node_group.tf

resource "aws_eks_node_group" "tfer--new-nodegroup-t3medium" {
  ami_type        = "AL2_x86_64"
  capacity_type   = "ON_DEMAND"
  cluster_name    = "${aws_eks_cluster.tfer--Cluster-DEV.name}"
  disk_size       = "20"
  instance_types  = ["t3.medium"]
  node_group_name = "new-nodegroup-t3medium"
  node_role_arn   = "arn:aws:iam::000000000000:role/EKS-Worker-Node-Role"
  release_version = "1.24.10-20230217"

  scaling_config {
    desired_size = "2"
    max_size     = "3"
    min_size     = "1"
  }

  subnet_ids = ["subnet-00000000000000000", "subnet-00000000000000000", "subnet-00000000000000000", "subnet-00000000000000000"]

  tags = {
    re_seung = "terraformer-test-01"
  }

  version = "1.24"
}

outputs.tf

output "aws_eks_cluster_tfer--Cluster-DEV_id" {
  value = "${aws_eks_cluster.tfer--Cluster-DEV.id}"
}

output "aws_eks_node_group_tfer--new-nodegroup-t3medium_id" {
  value = "${aws_eks_node_group.tfer--new-nodegroup-t3medium.id}"
}

provider.tf와 terraform.tfstate 파일의 내용은 생략한다.

4. Generated 된 코드를 로컬환경의 vs code로 열고 terraform init 및 plan 적용하기

(잘 되려나?)

- 버전 맞춰주는 작업

terraform state replace-provider -auto-approve "registry.terraform.io/-/aws" "hashicorp/aws"

- terraform init 까지는 잘됨, 왠지 plan 하면 에러날거 같은 느낌

Terraform has created a lock file .terraform.lock.hcl to record the provider
selections it made above. Include this file in your version control repository
so that Terraform can guarantee to make the same selections by default when
you run "terraform init" in the future.

Terraform has been successfully initialized!

- terraform plan - 오 에러 안남

$ terraform plan
aws_eks_cluster.tfer--Cluster-DEV: Refreshing state... [id=Cluster-DEV]
aws_eks_node_group.tfer--new-nodegroup-t3medium: Refreshing state... [id=Cluster-DEV:new-nodegroup-t3medium]

No changes. Your infrastructure matches the configuration.

5. 리소스 변경 후 validate / plan / apply 적용 후 console 에서 확인하기

일단 3가지 정보를 수정해 보도록 한다.

첫번째 scaling_config 정보를 수정해보자. 현재 아래와 같이 설정되어 있는 정보를 수정하고 적용해보자.

  # 수정 전
  scaling_config {
    desired_size = "2"
    max_size     = "3"
    min_size     = "1"
  }
  
  # 수정 후
    scaling_config {
    desired_size = "5"
    max_size     = "5"
    min_size     = "5"
  }

- terraform plan

친절하게도 아래와 같이 안내를 해준다.

      ~ scaling_config {
          ~ desired_size = 2 -> 5
          ~ max_size     = 3 -> 5
          ~ min_size     = 1 -> 5
        }

        # (1 unchanged block hidden)
    }

Plan: 0 to add, 1 to change, 0 to destroy.

 terraform apply

Apply complete! Resources: 0 added, 1 changed, 0 destroyed.

Outputs:

aws_eks_cluster_tfer--Cluster-DEV_id = "Cluster-DEV"
aws_eks_node_group_tfer--new-nodegroup-t3medium_id = "Cluster-DEV:new-nodegroup-t3medium"

콘솔에서 확인, 스케일 아웃 중... ㅋㅋㅋ

몇분 기다리면 아래와 같이 정상적으로 5개의 노드가 실행되고 있는것을 확인 할 수 있다.

eks는 node가 늘어나면 현재 실행중인 pod 리소스를 늘어난 노드와 현재의 노드에 재 배치 하기 때문에 준비 완료가 되기까지 몇분의 시간이 소요된다. (보통은 5분~10분 내에 정상화 되지만 케바케 이다.)

두번째는 노드그룹의 이름과 노드 타입을 변경하여 새로운 노드그룹을 생성해보자.

리소스 별칭은 변경하지 않고 instalce 타입하고 노드그룹 이름만 변경하고 apply 했는데

위의 모습처럼 노드그룹 자체를 삭제를 해버리네... 삭제하고 다시 만드나보다.

노드그룹을 지우고 있다. 새로운 노드그룹을 만들려면 별도의 노드그룹 생성 코드를 작성을 해야할거 같다.

다 지웠으면 새로 만듦

콘솔 확인, 새로 만드는중, 수분 후 완료됨

세번째는 tag 정보를 추가해보자.

클러스터.tf 파일에는 아래와 같이 정보를 추가하자. 마지막 줄에 tags_add 정보를 추가한다.

tags = {
    Name                                          = "eksctl-Cluster-DEV-cluster/ControlPlane"
    "alpha.eksctl.io/cluster-name"                = "Cluster-DEV"
    "alpha.eksctl.io/cluster-oidc-enabled"        = "true"
    "alpha.eksctl.io/eksctl-version"              = "0.122.0"
    "eksctl.cluster.k8s.io/v1alpha1/cluster-name" = "Cluster-DEV"
    re_seung                                      = "terraformer-test-01"
    tags_add                                      = "terraformer-test-02"
  }

노드그룹.tf 파일에도 아래와 같이 정보를 추가하자. 위와 같이 마지막 줄에 tags_add 정보를 추가한다.

  tags = {
    re_seung = "terraformer-test-01"
    tags_add = "terraformer-test-02"
  }

결과 : 2개의 정보가 수정 되었다.

Apply complete! Resources: 0 added, 2 changed, 0 destroyed.

콘솔 확인

클러스터 태그정보 확인

노드그룹 태그정보 확인

- 끝 -