首页 > 解决方案 > EC2 insatnce 配置文件的 KMS 权限问题

问题描述

请帮助找出我的代码中的错误,因为现在当我运行它时,它运行良好,除了在 ASG 上创建部分 EC2 实例。他们因错误而终止,即 KMS 密钥没有足够的权限来加密/解密根设备。

resource "aws_launch_template" "this" {
  name        = local.name
  description = var.lt_description
  image_id      = var.image_id
  instance_type = var.instance_type
  key_name      = var.key_name
  iam_instance_profile {
    arn = aws_iam_instance_profile.this.arn
  }

  network_interfaces {
    associate_public_ip_address = var.associate_public_ip_address
    security_groups = var.security_groups
  }

  block_device_mappings {
    device_name = var.device_name
    ebs {
      volume_size = var.device_volume_size
      volume_type = var.device_volume_type
      delete_on_termination = var.device_delete_on_termiation
      encrypted = var.device_enable_encryption
      kms_key_id = var.device_enable_encryption ? var.device_encryption_key : null
    }
  }
}

resource "aws_autoscaling_group" "this" {
  availability_zones = var.availability_zones
  desired_capacity   = var.asg_desired_capacity
  max_size           = var.asg_max_size
  min_size           = var.asg_min_size

  launch_template {
    id      = aws_launch_template.this.id
    version = "$Latest"
  }
}

data "aws_iam_policy_document" "assume_policy" {
  statement {
    actions = ["sts:AssumeRole"]
    principals {
      type        = "Service"
      identifiers = ["ec2.amazonaws.com"]
    }
  }
}

data "aws_iam_policy_document" "instance_policy" {

  statement {
    actions   = [
      "ec2:*"
    ]
    resources = ["*"]
  }

  statement {
    actions = [
       "kms:Encrypt",
       "kms:Decrypt",
       "kms:ReEncrypt",
       "kms:GenerateDataKey",
       "kms:DescribeKey",
       "kms:GenerateDataKeyWithoutPlainText"
    ]
    resources = [var.device_encryption_key]
  }
}

resource aws_iam_role "this" {
   path                = "/terraform/instances/"
   name                = "${local.name}-asg-iam-role"
   description         = var.role_description
   assume_role_policy  = data.aws_iam_policy_document.assume_policy.json
}

resource aws_iam_policy "instance_policy" {
  path                = "/terraform/instances/"
  name                = "${local.name}-instance-policy"
  description         = "${local.name} IAM KMS policy"
  policy              = data.aws_iam_policy_document.instance_policy.json
}

resource aws_iam_role_policy_attachment "this" {
  role                = aws_iam_role.this.name
  policy_arn          = aws_iam_policy.instance_policy.arn
}

resource aws_iam_instance_profile "this" {
  path                = "/terraform/instances/"
  name                = "${local.name}-instances-profile"
  role                = aws_iam_role.this.name
} 

可以确认所有创建的元素都没有任何问题,并且 terraform 返回绿灯。仅与权限和 ASG 相关的问题,由于权限的运气而终止实例

错误终止:

Client.InternalError:启动时出现客户端错误

也可以确认没有加密它的工作

标签: amazon-web-servicesterraformterraform-provider-aws

解决方案


您需要授予 ASG 服务相关角色访问您的 KMS 密钥的权限。更多信息在这里


推荐阅读