Search code examples
typescriptaws-cdk

CDK Assume Role from optional Lambda role property/no non-null assertions within Composite Principal


I have a role that is defined with a composite principal, but I can't add my Lambda function because of no non-null assertions, e.g. this fails:

assumedBy: new CompositePrincipal(
                ...
                new ArnPrincipal(this.cleLambdaFunction.role?.roleArn!)
            ),

How can I add my lambda function's role to assumbedBy/CompositePrincipal? Is it possible for me to have my Lambda functions role assume my target role after definition of the target role? I'm wondering if there's a method that works like this

onboardingLambdaCle.lambdaFunc.lambdaFunction.role?.assumeRole(targetRole.roleArn);

Solution

  • I suggest you to take advantage of TypeScript control flow analysis and just check the existence of the property like this:

    import { CompositePrincipal, ArnPrincipal } from 'aws-cdk-lib/aws-iam';
    import { Function } from 'aws-cdk-lib/aws-lambda';
    
    declare const func: Function;
    
    if (func.role) {
        const assumedBy = new CompositePrincipal(
            new ArnPrincipal(func.role.roleArn)
        )
    }
    

    TypeScript playground