Skip to content

Adding multiple service principals in CDK

0

Does CDK let you add multiple service principals to a role?

const fnRole = new iam.Role(this, "some-role-id", {
   roleName: "redirect-function-role",
   assumedBy: new iam.ServicePrincipal('lambda.amazonaws.com')  /* others? */
})

I tried a few things:

        fnRole.grantAssumeRole(new iam.ServicePrincipal('edgelambda.amazonaws.com'))
        fnRole.grant(new iam.ServicePrincipal('edgelambda.amazonaws.com'), "sts:AssumeRole")

These didn't seem to have any effect whatsoever (but no errors).

asked 3 years ago2.8K views

1 Answer
0
Accepted Answer

Yes, the AWS CDK allows you to add multiple service principals to an IAM Role. However, instead of using the grantAssumeRole method, you should use a CompositePrincipal. This allows you to combine multiple principals together.

Here's how you can do it:

import * as iam from '@aws-cdk/aws-iam';
import * as cdk from '@aws-cdk/core';
// ... inside your Stack
const role = new iam.Role(this, 'MyRole', {
  assumedBy: new iam.CompositePrincipal(
    new iam.ServicePrincipal('lambda.amazonaws.com'),
    new iam.ServicePrincipal('edgelambda.amazonaws.com')
  )
});

This code will create an IAM Role that can be assumed by both lambda.amazonaws.com and edgelambda.amazonaws.com.

The CompositePrincipal class allows you to combine multiple principal entities, making it a powerful tool when creating more complex IAM Policies.

AWS

answered 3 years ago

EXPERT

reviewed 3 years ago

You are not logged in. Log in to post an answer.

A good answer clearly answers the question and provides constructive feedback and encourages professional growth in the question asker.