如何在CloudFormation运行时指定调用者身份配置KMS密钥策略?
解决CloudFormation部署KMS密钥时添加当前调用者身份的问题
在部署AWS KMS密钥的CloudFormation模板中,必须确保密钥策略包含当前部署者的身份,否则会收到"The new key policy will not allow you to update the key policy in the future"错误——这是因为KMS要求密钥策略必须授予当前创建者后续修改策略的权限。
CloudFormation没有内置函数直接获取当前调用者的ARN,你可以通过以下两种方式解决:
方法1:通过模板参数传递调用者ARN
- 先在本地执行命令获取当前身份ARN:
aws sts get-caller-identity --query Arn --output text
- 在CloudFormation模板中添加参数定义:
Parameters: CurrentCallerArn: Type: String Description: ARN of the current user/role deploying the stack
- 修改KMS密钥策略部分,引用该参数:
MyKey: Type: AWS::KMS::Key Properties: Description: "..." KeyPolicy: Version: "2012-10-17" Id: "MyId" Statement: - Sid: "Allow administration of the key" Effect: "Allow" Principal: AWS: - !Ref CurrentCallerArn - !Sub "arn:aws:iam::${AWS::AccountId}:root" Action: - "kms:*" Resource: "*"
- 部署时传入参数:
aws cloudformation deploy --stack-name MyKmsStack --template-file your-template.yaml --parameter-overrides CurrentCallerArn=$(aws sts get-caller-identity --query Arn --output text)
方法2:直接在部署命令中注入ARN(无需修改模板参数)
如果不想修改模板添加参数,可以通过命令行工具临时替换模板中的占位符,再部署:
- 先在模板的TODO位置留占位符,比如
CURRENT_CALLER_ARN:
Principal: AWS: - CURRENT_CALLER_ARN - !Sub "arn:aws:iam::${AWS::AccountId}:root"
- 执行部署命令时替换占位符:
CALLER_ARN=$(aws sts get-caller-identity --query Arn --output text) && sed "s/CURRENT_CALLER_ARN/$CALLER_ARN/g" your-template.yaml > temp-template.yaml && aws cloudformation deploy --stack-name MyKmsStack --template-file temp-template.yaml && rm temp-template.yaml
注意事项
- 无论是IAM用户ARN还是STS扮演角色的ARN(如
arn:aws:sts::ACCOUNTID:assumed-role/AWSReservedSSO_DevAdministratorAccess_7fa146e5b7abcaa3),都可以直接作为Principal的值使用。 - 确保密钥策略中的Action包含足够的权限(示例中用
kms:*授予全部管理权限,你可以根据需求缩小范围)。
内容的提问来源于stack exchange,提问作者Joey Yi Zhao
相关产品推荐
相关产品推荐

