如何添加EC2实例在EKS群集中扮演的角色的策略?

时间:2019-12-28 03:17:29

标签: amazon-iam amazon-eks aws-eks

我正在使用Terraform创建EKS集群。工作节点具有如下定义的IAM角色:

resource "aws_iam_role" "eks-node" {
  name = "${local.resource_prefix}-eks-node"

  assume_role_policy = <<POLICY
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Principal": {
        "Service": "ec2.amazonaws.com"
      },
      "Action": "sts:AssumeRole"
    }
  ]
}
POLICY
}

resource "aws_iam_role_policy_attachment" "eks-node-AmazonEKSWorkerNodePolicy" {
  policy_arn = "arn:aws:iam::aws:policy/AmazonEKSWorkerNodePolicy"
  role       = "${aws_iam_role.eks-node.name}"
}

resource "aws_iam_role_policy_attachment" "eks-node-AmazonEKS_CNI_Policy" {
  policy_arn = "arn:aws:iam::aws:policy/AmazonEKS_CNI_Policy"
  role       = "${aws_iam_role.eks-node.name}"
}

resource "aws_iam_role_policy_attachment" "eks-node-AmazonEC2ContainerRegistryReadOnly" {
  policy_arn = "arn:aws:iam::aws:policy/AmazonEC2ContainerRegistryReadOnly"
  role       = "${aws_iam_role.eks-node.name}"
}

resource "aws_iam_instance_profile" "eks-node" {
  name = "${local.resource_prefix}-eks-node"
  role = "${aws_iam_role.eks-node.name}"
}

一切正常,我可以将容器启动到集群中。现在,我想尝试允许容器访问AWS SSM以便检索敏感信息(例如DB密码)。通过将一个简单的阿尔卑斯实例启动到集群中,安装了AWS CLI并运行,我进行了快速测试

aws ssm get-parameters --name /tmp/test-001 --region ...

(/ tmp / test-001参数确实存在于同一区域中)。这会吐出可预测的错误:

An error occurred (AccessDeniedException) when calling the GetParameters operation: User: arn:aws:sts::(account-id):assumed-role/(resource-prefix)-eks-node/i-(EC2-instance-id) is not authorized to perform: ssm:GetParameters on resource: arn:aws:ssm:(region):(account-id):parameter/tmp/test-001

实际上很好-我希望在我授予该用户许可之前将其拒绝。但是请注意,用户是assumed-role/(resource-prefix)-eks-node/i-(EC2-instance-id),而不仅仅是assumed-role/(resource-prefix)-eks-node-我怀疑这与我的实际问题有关……

所以我回到Terraform并将以下Policy添加到worker节点:

resource "aws_iam_role_policy" "eks_node_allow_ssm_access" {
  name = "${local.resource_prefix}-eks-node-ssm-access"
  role = "${aws_iam_role.eks-node.name}"

  policy = <<EOF
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Action": [
        "ssm:GetParameters"
      ],
      "Effect": "Allow",
      "Resource": "arn:aws:ssm:${local.aws_region}:${data.aws_caller_identity.current.account_id}:parameter/tmp/test-001"
    }
  ]
}
EOF
}

这会产生我所期望的-arn:aws:iam::(account-id):role/(resource-prefix)-eks-node上的内联策略,允许访问ssm:GetParameters。但是,当我重新启动容器并重试时,仍然出现AccessDeniedException错误。

我怀疑assumed-role(prefix)-eks-node/i-0...............e的一部分,而不是Terraform实际创建的角色是(prefix)-eks-node。但是,由于该EC2实例是通过自动缩放动态创建的,所以我不知道如何使用策略来定位它。

所有使我回到问题...我如何允许EKS辅助节点中EC2实例的假定用户角色访问另一个资源(在本例中为SSM)?

0 个答案:

没有答案