촬리의늘솔길

우여곡절2 Kubecost 설치기... 본문

☁️2024/Cloud

우여곡절2 Kubecost 설치기...

리촬리 2024. 2. 25. 17:48

후.. 어쩌다보니2 비용 최적화 방안에 대해서 공부하다가

아주 야무진 툴을 찾았다. 

 

한마디로 Kubernetes 최적화를 위한 다양한 정보를 제공하는 툴이다. (비용 중심)

단순히 Container 의 CPU, Memory Request 뿐만 아니라 PV, Network, Worker Node 등 거의 모든 Kubernetes Resource 비용 최적화 insight를 제공한다.

제공되는 주요 기능은 아래와 같다.

  • Cost Allocation: Workload, Namespace, 인프라 등 Kubernetes 비용 가시성 확보
  • Optimization Insight: 비용 최적화 Insight 제공
  • Alerts & Governance: 예산설정 및 알림 기능 제공

결론적으로 쿠버네티스는 Kubernetes 플랫폼을 이루는 Cluster는 항상 변화하는 가변적인 환경이다. kubernetes Cluster의 비용을 정산하기 위해서는 다양하게 변화하는 환경에 대응할 수 있어야 한다.또한 Kubernetes 환경은 다른 환경보다 더 정교하고 정확한 비용 정산 능력을 필요로 하며 가령 아래와 같은 기존 Cloud Billing 보고서로는 Kubernetes의 테넌트별 비용, Pod별 비용, 네트워크 비용을 산출하기 어렵다.

 

aws 의 다른 서비스인 CostExploer 에서도,

  • RI/SP 약정의 한계 : RI(예약 인스턴스)를 사용하는 경우 결제 방식에 따라 비용이 다르게 표현되고, 개발팀에서 필요로 하는 사용량 증감을 CostExplorer에서 확인하기란 쉽지 않다.
  • EKS의 한계 : EKS에서 운영하는 서비스별 비용을 보고 싶어도, CostExplorer에서 확인할 수 없다.

많은 조직이 Kubernetes 지출을 모니터링 하지 않고, 월별 추정치만 사용하고 있기 때문에 비용 최적화를 위한 세분화된 비용 파악이 어려울 수 있다.

그러나 Kubecost를 사용하면 pod, node, namespace, label 등을 포함한 Kubernetes 리소스별 세분화된 비용을 확인할 수 있으며, 무료로 제공된다!

 

 


그렇다면 kubecost.. 이눔을 깔면서 을매나 힘들었는지,, (쉽게 깔 수 있다고 누가 그랬슈!!)

일단 도움이 되었던 링크를 하단에 첨부하겠다.

 

1. EBS CSI Driver

kubecost 설치를 위해서는,

EBS CSI Driver 가 eks cluster에 있어야 하고,

addon service account 설정을 해줘야 한다.

eksctl create addon --name aws-ebs-csi-driver --cluster ub-cwave-cluster--service-account-role-arn arn:aws:iam::564131458637:role/AmazonEKS_EBS_CSI_DriverRole --force
eksctl update addon --name aws-ebs-csi-driver --version v1.27.0-eksbuild.1 --cluster ub-cwave-cluster \
  --service-account-role-arn arn:aws:iam::564131458637:role/AmazonEKS_EBS_CSI_DriverRole --force

 

이거 증말 중요하다.

EBS 드라이버가 클러스터에 없으면 안되고, addon 을 통해 역할을 연결해줘야한다.

이 명령어를 어디서 찾았는지는 기억이 안나서,, 구글링 하시길..

 

 

2. 권한 설정 

!! 권한 !! 설정이 중요하다.

노드 그룹 role 의 권한에 다음 사항들을 추가해줘야한다.

정말,, IAM 환멸날정도로 엄청 쳐다봤다. 

그만큼 권한이 중요하다. 

 

eksctl create iamserviceaccount   \
    --name ebs-csi-controller-sa   \
    --namespace kube-system   \
    --cluster $CLUSTER_NAME   \
    --attach-policy-arn arn:aws:iam::564131458637:role/AmazonEKS_EBS_CSI_DriverRole  \
    --approve \
    --role-only \
    --role-name AmazonEKS_EBS_CSI_DriverRole

자세한 설명 : 참고

{
	"Version": "2012-10-17",
	"Statement": [
		{
			"Sid": "VisualEditor0",
			"Effect": "Allow",
			"Action": [
				"ec2:CreateVolume",
				"ec2:CreateTags",
				"ec2:AttachVolume"
			],
			"Resource": "*"
		}
	]
}

 

 

안그러면 prometheus pod 가 volume attach mount 가 안된다.

 

2. Storage Class 

스토리지 클래스를 추가해줘야한다.

apiVersion: storage.k8s.io/v1
kind: StorageClass
metadata:
  name: ebs-sc
  namespace : kubecost
  annotations:
    storageclass.kubernetes.io/is-default-class: "true"
provisioner: ebs.csi.aws.com
volumeBindingMode: WaitForFirstConsumer

더불어, 해당 스토리지 클래스를 default 로 바꿔주어야 한다.

(안그러면 얘가 이걸 못찾는것같기도 하다)

default 로 바꾸는법 참고

3. Helm 으로 설치하기

https://github.com/kubecost/cost-analyzer-helm-chart/blob/develop/kubecost.yaml

자세한 설명 : 참고

현재 버전 확인 : https://gallery.ecr.aws/kubecost/cost-analyzer

 

일단 analyzer 를 service account 에 annotate 해준다.

kubectl annotate serviceaccount kubecost-cost-analyzer \
    -n kubecost \
    eks.amazonaws.com/role-arn=arn:aws:iam::564131458637:role/AmazonEKS_EBS_CSI_DriverRole

 

helm template kubecost \
  --repo https://kubecost.github.io/cost-analyzer/ cost-analyzer \
  --namespace kubecost --create-namespace \
  -f ~/k8s/.yaml > kubecost.yaml
kubectl apply -f kubecost.yaml
aws elbv2 create-load-balancer --name ub-kubecost-elb --subnets subnet-0bdb96d673394ae8c subnet-0428fe33a5c7ca120 subnet-05ef58028b05f0e9b subnet-01a37c4e7a9425169 subnet-0724726aaeebf8d7c subnet-05480edcc41831f41 --security-groups sg-12345678

 

서브넷과 시큐리티 그룹 이름은 본인의 것에 맞게 바꿔야 한다.

 

이제부터는 upgrade 인데,, 명령어를 똑같은듯 다른 두개를 갖고 했어서 둘중에 더 잘되는거 하면 될 것 같다.

방법1)

helm upgrade -i kubecost \
oci://public.ecr.aws/kubecost/cost-analyzer --version 2.0.2 \
--namespace kubecost --create-namespace \
-f https://tinyurl.com/kubecost-amazon-eks

방법2)

helm upgrade -i kubecost \
oci://public.ecr.aws/kubecost/cost-analyzer --version 2.0.2 \
--namespace kubecost --create-namespace \
-f https://raw.githubusercontent.com/kubecost/cost-analyzer-helm-chart/develop/cost-analyzer/values-eks-cost-monitoring.yaml

 

 

 

4. 트러블 슈팅 - PV 미생성 오류

고뇌의 흔적..

다시 보니 어질어질한 오류이다.

Normal   WaitForFirstConsumer  2m8s  persistentvolume-controller                                                               waiting for first consumer to be created before binding
  Warning  ProvisioningFailed    2m7s  ebs.csi.aws.com_ebs-csi-controller-7688d99c79-q2lvl_ab056219-a6a0-4014-b84a-1bf3022271c2  failed to provision volume with StorageClass "ebs-sc": rpc error: code = Internal desc = Could not create volume "pvc-1e4084c2-2210-4665-a081-94cdeef79475": could not create volume in EC2: WebIdentityErr: failed to retrieve credentials
caused by: AccessDenied: Not authorized to perform sts:AssumeRoleWithWebIdentity
           status code: 403, request id: cdb05516-2069-453e-a8fa-fbbadfa0b15d
  Warning  ProvisioningFailed  2m6s  ebs.csi.aws.com_ebs-csi-controller-7688d99c79-q2lvl_ab056219-a6a0-4014-b84a-1bf3022271c2  failed to provision volume with StorageClass "ebs-sc": rpc error: code = Internal desc = Could not create volume "pvc-1e4084c2-2210-4665-a081-94cdeef79475": could not create volume in EC2: WebIdentityErr: failed to retrieve credentials
caused by: AccessDenied: Not authorized to perform sts:AssumeRoleWithWebIdentity
           status code: 403, request id: 470a8ac1-cbd0-48c0-970d-1c997ac13182
  Warning  ProvisioningFailed  2m4s  ebs.csi.aws.com_ebs-csi-controller-7688d99c79-q2lvl_ab056219-a6a0-4014-b84a-1bf3022271c2  failed to provision volume with StorageClass "ebs-sc": rpc error: code = Internal desc = Could not create volume "pvc-1e4084c2-2210-4665-a081-94cdeef79475": could not create volume in EC2: WebIdentityErr: failed to retrieve credentials
caused by: AccessDenied: Not authorized to perform sts:AssumeRoleWithWebIdentity
           status code: 403, request id: 4da6392a-c1e8-45fd-8933-0c22001d70b5
  Warning  ProvisioningFailed  2m  ebs.csi.aws.com_ebs-csi-controller-7688d99c79-q2lvl_ab056219-a6a0-4014-b84a-1bf3022271c2  failed to provision volume with StorageClass "ebs-sc": rpc error: code = Internal desc = Could not create volume "pvc-1e4084c2-2210-4665-a081-94cdeef79475": could not create volume in EC2: WebIdentityErr: failed to retrieve credentials
caused by: AccessDenied: Not authorized to perform sts:AssumeRoleWithWebIdentity
           status code: 403, request id: 08731825-85a3-4f21-ac02-70d43e7f6b70
  Warning  ProvisioningFailed  112s  ebs.csi.aws.com_ebs-csi-controller-7688d99c79-q2lvl_ab056219-a6a0-4014-b84a-1bf3022271c2  failed to provision volume with StorageClass "ebs-sc": rpc error: code = Internal desc = Could not create volume "pvc-1e4084c2-2210-4665-a081-94cdeef79475": could not create volume in EC2: WebIdentityErr: failed to retrieve credentials
caused by: AccessDenied: Not authorized to perform sts:AssumeRoleWithWebIdentity
           status code: 403, request id: ac17bd79-80db-4da4-82df-5f139b907d9f
  Warning  ProvisioningFailed  96s  ebs.csi.aws.com_ebs-csi-controller-7688d99c79-q2lvl_ab056219-a6a0-4014-b84a-1bf3022271c2  failed to provision volume with StorageClass "ebs-sc": rpc error: code = Internal desc = Could not create volume "pvc-1e4084c2-2210-4665-a081-94cdeef79475": could not create volume in EC2: WebIdentityErr: failed to retrieve credentials
caused by: AccessDenied: Not authorized to perform sts:AssumeRoleWithWebIdentity
           status code: 403, request id: fa917622-896b-44be-9f29-96f3ac7a612b
  Normal   Provisioning        64s (x7 over 2m7s)  ebs.csi.aws.com_ebs-csi-controller-7688d99c79-q2lvl_ab056219-a6a0-4014-b84a-1bf3022271c2  External provisioner is provisioning volume for claim "kubecost/kubecost-cost-analyzer"
  Warning  ProvisioningFailed  64s                 ebs.csi.aws.com_ebs-csi-controller-7688d99c79-q2lvl_ab056219-a6a0-4014-b84a-1bf3022271c2  failed to provision volume with StorageClass "ebs-sc": rpc error: code = Internal desc = Could not create volume "pvc-1e4084c2-2210-4665-a081-94cdeef79475": could not create volume in EC2: WebIdentityErr: failed to retrieve credentials
caused by: AccessDenied: Not authorized to perform sts:AssumeRoleWithWebIdentity
          status code: 403, request id: ef214ff3-6948-4a04-8bf0-df340b175746
  Normal  ExternalProvisioning  1s (x10 over 2m7s)  persistentvolume-controller  Waiting for a volume to be created either by the external provisioner 'ebs.csi.aws.com' or manually by the system administrator. If volume creation is delayed, please verify that the provisioner is running and correctly registered.

 

누가봐도 권한문제이지 않나?

특히 저 sts:AssumeRoleWithWebIdentity 이친구는 이제와서 보면 신뢰관계라는게 딱 보인다.

 

해결 - OIDC 문제였다.

https://repost.aws/ko/knowledge-center/eks-troubleshoot-oidc-and-irsa

OIDC 를 아무리 다시 만들어도 왜 안되지 ? 싶었는데,

 

OIDC 확인 명령어 

aws eks describe-cluster --name cluster_name --query "cluster.identity.oidc.issuer" --output text

EBSCSIDriverRole 에 등록된 신뢰관계정책- oidc 가 내가 이미 만들고 사용중인 oidc 와 달라서였다.

 

 

눈물겨운.. kubecost 

 

나의 어여쁜 kubecost 대시보드..

 

벌써부터 성능대비 비용측정도 해준다...

유의 해야 할 점

1. ingress 를 띄운다. pod 만들기 전에 하는게 좋은 것 같다.

2. oidc 와 iam 권한을 잘 확인한다.

3. 볼륨 바인딩 오류를 해결하기 위해서는 권한문제를 해결해야 한다.


 

리소스 

https://catalog.workshops.aws/eks-cost-optimization/ko-KR/3-eks-network-cost/3-1-use-nlb-external-traffic-policy

https://medium.com/@devopsrockers/deployment-of-kubecost-with-ingress-in-eks-for-cost-optimization-using-helm-e4d209476e83

 

PV 관련 리소스

https://github.com/kubecost/cost-analyzer-helm-chart/blob/develop/README.md

https://stackoverflow.com/questions/75758115/persistentvolumeclaim-is-stuck-waiting-for-a-volume-to-be-created-either-by-ex

https://github.com/kubecost/cost-analyzer-helm-chart/blob/develop/cost-analyzer/values.yaml#L264

https://repost.aws/ko/knowledge-center/ec2-not-auth-launch

https://medium.com/contino-engineering/kubecost-getting-control-of-container-costs-aa932f571517

https://community.veeam.com/kasten-k10-support-92/failed-to-provision-volume-with-storageclass-efs-sc-exceeds-efs-limit-of-100-characters-6292

https://github.com/opencost/opencost/issues/761

728x90