'What's the difference between addToPrincipalPolicy vs addToPolicy

In CDK IAM Users, Groups or Roles have two methods to add PolicyStatements:

  1. X.addToPolicy (CDK API Reference) and
  2. X.addToPrincipalPolicy (CDK API Reference)

Whats the difference between then? The API Reference isn't much help.



Solution 1:[1]

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 };
  }

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 fedonev