Home > Blockchain >  How to specify multiple principals in a policy document AWS CDK
How to specify multiple principals in a policy document AWS CDK

Time:04-24

I am working on cdk script and I want to specify multiple principals such as

"Principal": {
  "AWS": [
    "arn:aws:iam::AWS-account-ID:user/user-name-1", 
    "arn:aws:iam::AWS-account-ID:user/user-name-2"
  ]
}

This is pretty straightforward in a JSON document but when writing with a policy document, I am unsure how to specify it. I currently have

const principals : Array<IPrincipal> = ['arn:aws:iam::AWS-account-ID:user/user-name-1', 'arn:aws:iam::AWS-account-ID:user/user-name-2'] 

const myPolicy = new PolicyDocument({
      statements: [
        new PolicyStatement({
          actions: ['*'],
          effect: Effect.ALLOW,
          principals: principals,
          resources: ['*'],
        }),
      ],
    }); 

How, this is erroring out as

Cannot read property 'principalJson' of undefined

CodePudding user response:

The PolicyStatement principals key accepts an array of IPrincipal, but you are giving it a string array. The IUser type returned from the User.fromUserArn method is a superset of the IPrincipal interface, so that's what you need:

const principals: Array<iam.IUser> = [
  'arn:aws:iam::AWS-account-ID:user/user-name-1',
  'arn:aws:iam::AWS-account-ID:user/user-name-2',
].map((p, i) => iam.User.fromUserArn(this, `ImportedUser${i}`, p));
  • Related