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

使用Go调用AWS SDK v2创建KMS密钥时,如何生成密钥策略?

生成KMS密钥策略的可行方案

针对你的Go环境(从代码判断使用AWS SDK v2 for Go),以下几种方式可以避免手动编写JSON策略:

1. 使用GoFormation库构建策略

GoFormation是AWS官方维护的库,支持以代码方式构建IAM(包括KMS)策略,再序列化为JSON字符串,无需手动编写JSON语法。

示例代码:

import (
    "encoding/json"
    "github.com/awslabs/goformation/v7/cloudformation/iam"
)

// 构建KMS密钥策略结构
policyDocument := &iam.PolicyDocument{
    Version: "2012-10-17",
    Statement: []iam.PolicyStatement{
        {
            Effect: "Allow",
            Principal: map[string]interface{}{
                "AWS": "arn:aws:iam::123456789012:root",
            },
            Action: []string{"kms:*"},
            Resource: "*",
        },
        // 按需添加其他权限声明
        {
            Effect: "Allow",
            Principal: map[string]interface{}{
                "AWS": "arn:aws:iam::123456789012:user/your-service-user",
            },
            Action: []string{"kms:Sign", "kms:Verify"},
            Resource: "*",
        },
    },
}

// 序列化为格式化的JSON字符串
policyJson, err := json.MarshalIndent(policyDocument, "", "  ")
if err != nil {
    // 处理序列化错误
}

// 传入CreateKeyInput参数
input := kms.CreateKeyInput{
    KeySpec:     types.KeySpecEccNistP521,
    KeyUsage:    types.KeyUsageTypeSignVerify,
    MultiRegion: aws.Bool(true),
    Policy:      aws.String(string(policyJson)),
}

2. 自定义Go结构体构建策略

如果不想引入第三方库,可以自己定义对应IAM策略结构的Go结构体,通过代码组装后直接序列化:

type PolicyDocument struct {
    Version   string        `json:"Version"`
    Statement []Statement   `json:"Statement"`
}

type Statement struct {
    Effect    string                 `json:"Effect"`
    Principal map[string]interface{} `json:"Principal"`
    Action    []string               `json:"Action"`
    Resource  string                 `json:"Resource"`
}

// 组装策略内容
policy := PolicyDocument{
    Version: "2012-10-17",
    Statement: []Statement{
        {
            Effect: "Allow",
            Principal: map[string]interface{}{
                "AWS": "arn:aws:iam::123456789012:root",
            },
            Action: []string{"kms:*"},
            Resource: "*",
        },
    },
}

// 转换为JSON字符串
policyJson, err := json.Marshal(policy)
if err != nil {
    // 处理错误
}

// 赋值给CreateKeyInput的Policy字段
input.Policy = aws.String(string(policyJson))

3. 借助AWS CLI生成模板映射到代码

如果你熟悉AWS CLI,可以先执行aws kms create-key --generate-cli-skeleton input生成包含Policy字段的JSON模板,再将模板中的Policy结构映射到Go结构体中,避免手动编写JSON的语法错误。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 07:00:57