addToPrincipalPolicy 与 addToPolicy 之间有什么区别
What's the difference between addToPrincipalPolicy vs addToPolicy
在 CDK IAM 用户、组或角色中有两种添加策略声明的方法:
- X.addToPolicy (CDK API Reference) 和
- X.addToPrincipalPolicy (CDK API Reference)
那有什么区别?
API 参考没有多大帮助。
TL;DR 两者都向委托人的内联策略添加了一条语句。唯一的区别是 return 值。
两者都接受 PolicyStatement and synth a AWS::IAM::Policy
resource to the Principal. However, addToPolicy
returns a "success" boolean, while addToPrincipalPolicy
returns an object.
通过查看 Role
class 的 aws-cdk source 实现很容易看出这一点:
// role.ts
export class Role extends Resource implements IRole {
// ...
public addToPolicy(statement: PolicyStatement): boolean {
return this.addToPrincipalPolicy(statement).statementAdded;
}
public addToPrincipalPolicy(statement: PolicyStatement): AddToPrincipalPolicyResult {
if (!this.defaultPolicy) {
this.defaultPolicy = new Policy(this, 'Policy');
this.attachInlinePolicy(this.defaultPolicy);
}
this.defaultPolicy.addStatements(statement);
return { statementAdded: true, policyDependable: this.defaultPolicy };
}
在 CDK IAM 用户、组或角色中有两种添加策略声明的方法:
- X.addToPolicy (CDK API Reference) 和
- X.addToPrincipalPolicy (CDK API Reference)
那有什么区别? API 参考没有多大帮助。
TL;DR 两者都向委托人的内联策略添加了一条语句。唯一的区别是 return 值。
两者都接受 PolicyStatement and synth a AWS::IAM::Policy
resource to the Principal. However, addToPolicy
returns a "success" boolean, while addToPrincipalPolicy
returns an object.
通过查看 Role
class 的 aws-cdk source 实现很容易看出这一点:
// role.ts
export class Role extends Resource implements IRole {
// ...
public addToPolicy(statement: PolicyStatement): boolean {
return this.addToPrincipalPolicy(statement).statementAdded;
}
public addToPrincipalPolicy(statement: PolicyStatement): AddToPrincipalPolicyResult {
if (!this.defaultPolicy) {
this.defaultPolicy = new Policy(this, 'Policy');
this.attachInlinePolicy(this.defaultPolicy);
}
this.defaultPolicy.addStatements(statement);
return { statementAdded: true, policyDependable: this.defaultPolicy };
}