如何在CDK的AssumeRolePolicyDocument中添加sts:SetSourceIdentity
在AWS CDK中为IAM角色的AssumeRolePolicyDocument添加sts:SetSourceIdentity操作
不需要切换到L1构造,用L2构造就能实现,有两种常用方式:
方式一:手动构建信任策略文档(推荐)
直接创建自定义的PolicyDocument,包含sts:AssumeRole和sts:SetSourceIdentity两个操作,然后传给Role的assumeRolePolicy参数,替代默认的assumedBy配置:
import { Role, PolicyDocument, PolicyStatement, Effect, AccountPrincipal, Stack } from 'aws-cdk-lib/aws-iam'; // 构建自定义信任策略 const assumeRolePolicy = new PolicyDocument({ statements: [ new PolicyStatement({ effect: Effect.ALLOW, principals: [new AccountPrincipal(Stack.of(this).account)], actions: ['sts:AssumeRole', 'sts:SetSourceIdentity'], }), ], }); // 创建角色并传入自定义策略 new Role(this, 'MyRole', { assumeRolePolicy: assumeRolePolicy, // 其他角色配置(比如managedPolicies、inlinePolicies等)... });
这种方式保留了L2构造的类型安全和便捷性,同时实现了自定义信任策略的需求。
方式二:使用L1构造(CfnRole)
如果需要完全手动控制策略的JSON结构,可以直接用L1的CfnRole构造:
import { CfnRole, Stack } from 'aws-cdk-lib/aws-iam'; new CfnRole(this, 'MyRole', { assumeRolePolicyDocument: { Version: '2012-10-17', Statement: [ { Effect: 'Allow', Principal: { AWS: `arn:aws:iam::${Stack.of(this).account}:root`, }, Action: ['sts:AssumeRole', 'sts:SetSourceIdentity'], }, ], }, // 按需添加其他属性,比如roleName、path、policies等 });
这种方式需要手动编写JSON格式的策略文档,适合对策略结构有极致自定义需求的场景。
内容的提问来源于stack exchange,提问作者Jason Wadsworth
相关产品推荐
相关产品推荐

