In CDK IAM Users, Groups or Roles have two methods to add PolicyStatements:
- X.addToPolicy (CDK API Reference) and
- X.addToPrincipalPolicy (CDK API Reference)
Whats the difference between then? The API Reference isn't much help.
In CDK IAM Users, Groups or Roles have two methods to add PolicyStatements:
Whats the difference between then? The API Reference isn't much help.
TL;DR Both add a statement to a Principal's inline policy. The only difference is the return value.
Both accept a PolicyStatement and synth a AWS::IAM::Policy
resource to the Principal. However, addToPolicy
returns a "success" boolean, while addToPrincipalPolicy
returns an object.
This is easy to see by looking at the aws-cdk source implementation of the Role
class:
// 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 };
}
Role.fromRoleArn
(ie. an IRole), you cannot use addToPolicy
(only addToPrincipalPolicy
is implemented on IRole).