設定 k8s service account 的 annotation,指定要使用上一個步驟建立的 IAM Role(要使用 Role ARN);如此一來,有設定 annotation 的 k8s service account 就會擁有 IAM Role 的權限來存取 AWS resource 了
AWS 如何認證來自 k8s 的請求?
到這裡就差一個問題,設定了 k8s service account annotation 之後,要怎麼讓 k8s service account 可以 assume 成指定的 IAM Role 呢?
這個就需要透過 Assume Role With WebIdentity 的方式,而這方式就會依賴 EKS cluster 提供的 OpenID Connect provider 來達成,而 Assume Role 的設定則是在 IAM Role 中的 Trust Entity 中設定,以下是個簡單的範例:
# 建立 IAM Policy $ aws iam create-policy \ --policy-name AWSLoadBalancerControllerIAMPolicy \ --policy-document file://iam_policy.json
# 若是原本在 eksctl 管理下存在 IAM service account,那就先移除 # 因為第二次重裝的 EKS cluster 不會有該 service account 的資訊 $ eksctl delete iamserviceaccount --name aws-load-balancer-controller --namespace kube-system --cluster eks-test
# 新增一個 IAM Role,並加入指定的 IAM Policy # 並指定 service account "aws-load-balancer-controller" 使用此 IAM Role $ eksctl create iamserviceaccount \ --cluster=eks-test \ --namespace=kube-system \ --name=aws-load-balancer-controller \ --attach-policy-arn=arn:aws:iam::777777777777:policy/AWSLoadBalancerControllerIAMPolicy \ --override-existing-serviceaccounts \ --approve [ℹ] eksctl version 0.34.0 [ℹ] using region ap-northeast-1 [ℹ] 1 existing iamserviceaccount(s) (kube-system/aws-node) will be excluded [ℹ] 1 iamserviceaccount (kube-system/aws-load-balancer-controller) was included (based on the include/exclude rules) [ℹ] 1 iamserviceaccount (kube-system/aws-node) was excluded (based on the include/exclude rules) [!] metadata of serviceaccounts that exist in Kubernetes will be updated, as --override-existing-serviceaccounts was set [ℹ] 1 task: { 2 sequential sub-tasks: { create IAM role for serviceaccount "kube-system/aws-load-balancer-controller", create serviceaccount "kube-system/aws-load-balancer-controller" } } [ℹ] building iamserviceaccount stack "eksctl-eks-test-addon-iamserviceaccount-kube-system-aws-load-balancer-controller" [ℹ] deploying stack "eksctl-eks-test-addon-iamserviceaccount-kube-system-aws-load-balancer-controller" [ℹ] created serviceaccount "kube-system/aws-load-balancer-controller"
# 檢視 Service Account 的內容 # 可看到 aws-load-balancer-controller service account 所對應到的 IAM Role 是那一個 # 進 AWS Console 檢查一下,可以看到此 IAM Role 繫結的就是上面建立的 IAM Policy $ kubectl -n kube-system describe sa/aws-load-balancer-controller Name: aws-load-balancer-controller Namespace: kube-system Labels: <none> Annotations: eks.amazonaws.com/role-arn: arn:aws:iam::777777777777:role/eksctl-eks-test-addon-iamserviceaccount-kube-Role1-1MNNDI4RVIZFF Image pull secrets: <none> Mountable secrets: aws-load-balancer-controller-token-z2xg9 Tokens: aws-load-balancer-controller-token-z2xg9 Events: <none>
其實上面有提到權限設定的說明部份,因此即使不透過 eksctl,要自行完成設定 IAM service account 也不是太困難的事情,大概就是以下流程: