1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

EKSのIAM Roles for Service Accountsをterraformで設定する

Last updated at Posted at 2021-03-01

terraformだけでIAM Roles for Service Accountsを設定する際のメモ

AWSの設定(IAM Role)

data "aws_eks_cluster" "this" {
  name = "my_cluster"
}

data "tls_certificate" "this" {
  url = data.aws_eks_cluster.this.identity[0].oidc[0].issuer
}

resource "aws_iam_openid_connect_provider" "this" {
  client_id_list  = ["sts.amazonaws.com"]
  thumbprint_list = [data.tls_certificate.this.certificates[0].sha1_fingerprint]
  url             = data.aws_eks_cluster.this.identity[0].oidc[0].issuer
}

data "aws_iam_policy_document" "eks_pod" {
  statement {
    effect = "Allow"
    principals {
      identifiers = [aws_iam_openid_connect_provider.this.arn]
      type        = "Federated"
    }
    actions = ["sts:AssumeRoleWithWebIdentity"]
    condition {
      test     = "StringEquals"
      variable = "${aws_iam_openid_connect_provider.this.url}:aud"
      values   = ["sts.amazonaws.com"]
    }
  }
}

resource "aws_iam_role" "this" {
  name               = "iam-roles-for-service-accounts-role"
  assume_role_policy = data.aws_iam_policy_document.eks_pod.json
}

resource "aws_iam_role_policy_attachment" "this" {
  role       = aws_iam_role.this.name
  policy_arn = "arn:aws:iam::xxxxxxxxx:policy/policy-name-with-path"
}

K8Sの設定(service account)

resource "kubernetes_service_account" "default" {
  metadata {
    name      = "my_service_account"
    namespace = "default"
    annotations = {
      "eks.amazonaws.com/role-arn" = aws_iam_role.this.arn
    }
  }

  automount_service_account_token = true
}

podからservice accountを指定

apiVersion: v1
kind: Pod
metadata:
  name: my-pod
spec:
  serviceAccountName: my_service_account
  automountServiceAccountToken: false
...
1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?