7

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.

1 Answer 1

8

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 };
  }
1
  • 3
    Also, if you have a role sourced via Role.fromRoleArn (ie. an IRole), you cannot use addToPolicy (only addToPrincipalPolicy is implemented on IRole).
    – joshweir
    Jan 6 at 2:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.