You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Terraform配置AWS KMS Key遇反序列化错误求助

解决Terraform配置KMS密钥时的反序列化错误

错误原因

你遇到的cannot unmarshal string into Go value of type awspolicy.intermediatePolicyDocument错误,本质是生成的IAM策略JSON里存在大小写错误的条件变量:
在第二个statement的condition中,你写的kms:GrantIsForAWSresource是错误的,AWS官方定义的正确变量名是kms:GrantIsForAWSResource(末尾Resource首字母大写)。AWS的IAM条件变量严格区分大小写,错误的变量名导致KMS服务无法正确解析策略内容,触发反序列化失败。

修正后的配置

数据对象(aws_iam_policy_document)

data "aws_caller_identity" "me" {} # 获取当前连接的账户信息~(whoami)

data "aws_iam_policy_document" "example" {
    version = "2012-10-17"
    statement {
        sid = "Allow Route 53 DNSSEC Service"
        effect = "Allow"
        resources = ["*"]

        actions = [
            "kms:DescribeKey",
            "kms:GetPublicKey",
            "kms:Sign"
        ]

        principals {
            type        = "Service"
            identifiers = ["dnssec-route53.amazonaws.com"]
        }

        condition {
            test     = "ForAnyValue:StringEquals"
            variable = "aws:SourceAccount"
            values   = ["${data.aws_caller_identity.me.account_id}"]
        }

        condition {
            test     = "ForAnyValue:ArnLike"
            variable = "aws:SourceArn"
            values   = ["arn:aws:route53:::hostedzone/*"]
        }
    }
    statement {
        sid = "Allow Route 53 DNSSEC Service to CreateGrant"
        effect = "Allow"
        resources = ["*"]

        actions = [
            "kms:CreateGrant"
        ]

        principals {
            type        = "Service"
            identifiers = ["dnssec-route53.amazonaws.com"]
        }

        condition {
            test     = "Bool"
            variable = "kms:GrantIsForAWSResource" # 修正大小写错误
            values   = ["true"]
        }
    }
    statement {
        sid = "Enable IAM User Permissions"
        effect = "Allow"
        resources = ["*"]

        actions = [
            "kms:*"
        ]

        principals {
            type        = "AWS"
            identifiers = ["arn:aws:iam::${data.aws_caller_identity.me.account_id}:root"]
        }
    }
}

KMS密钥资源对象

保持原配置不变:

resource "aws_kms_key" "example" {
  customer_master_key_spec = "ECC_NIST_P256"
  deletion_window_in_days  = 7
  key_usage                = "SIGN_VERIFY"
  policy = data.aws_iam_policy_document.example.json
}

额外清理步骤(针对之前的残留密钥)

因为你之前手动禁用并计划删除了一个KMS密钥,但Terraform状态中可能还保留着该资源的记录,这会影响新资源的创建,执行以下命令清理状态:

terraform state rm aws_kms_key.example

补充解释

  • 反序列化(Unmarshal):简单来说就是把JSON字符串转换成程序可以识别的对象结构,这里AWS的KMS服务无法把你生成的策略JSON转换成它需要的内部对象,因为变量名错误导致结构不符合预期。
  • AWS条件变量大小写:所有AWS服务的IAM条件变量都是大小写敏感的,必须严格按照官方定义的拼写使用。

内容的提问来源于stack exchange,提问作者aRustyDev

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 15:27:23