create role with trust permission using cdk causing issues

1

I want to create a role with AmazonChimeFullAccess Permissions and allow lambda to run STS-AssumeRole. I could not able to create this role using IAM role using AWS Console but couldn't identify the way to create using CDK. The code used for creating this role in cdk is pasted below,

Permissions:

AmazonChimeFullAccess

Trusted entities:

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Principal": {
                "AWS": [
                    "arn:aws:iam::<account-number>:role/dev-lambda"
                ]
            },
            "Action": "sts:AssumeRole",
            "Condition": {}
        }
    ]
}

cdk code

val role = Role(
            stackInstance, "StsChimeChatAssumeRole",
            RoleProps.builder()
                .assumedBy(ServicePrincipal("sts.amazonaws.com"))
                .build()
        )

        // Add a statement to the trust policy to allow the AWS account with ID "123456789012" to assume the role
        role.addToPolicy(
            PolicyStatement.Builder
                .create()
                .effect(Effect.ALLOW)
                .principals(listOf(ArnPrincipal("arn:aws:iam::<account-number>:role/dev")))
                .actions(listOf("sts:AssumeRole"))
                .build()
        )

        role.addManagedPolicy(ManagedPolicy.fromAwsManagedPolicyName("AmazonChimeFullAccess"))

Error:

Exception in thread "main" java.lang.RuntimeException: Error: Validation failed with the following errors:
  [TemplateServiceStack/dev/TemplateServiceDevWaveLambdaStack/StsChimeChatAssumeRole/DefaultPolicy] A PolicyStatement used in an identity-based policy cannot specify any IAM principals.
  [TemplateServiceStack/dev/TemplateServiceDevWaveLambdaStack/StsChimeChatAssumeRole/DefaultPolicy] A PolicyStatement used in an identity-based policy must specify at least one resource.
1 Answer
1
Accepted Answer

In order to create a Role with the trust policy you have provided with the managed policy attached, you will need to do the following:

// Create a Role that can be assumed by the Lambda's Role.
val role = Role(
            stackInstance, "StsChimeChatAssumeRole",
            RoleProps.builder()
                .assumedBy(ArnPrincipal("arn:aws:iam::<account-number>:role/dev"))
                .build()
        )

// Add the managed policy to the Role.
        role.addManagedPolicy(ManagedPolicy.fromAwsManagedPolicyName("AmazonChimeFullAccess"))

The addToPolicy method allows you to attach IAM policies to a Role, not trust policies.

AWS
answered a year ago
profile picture
EXPERT
reviewed a month 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.

Guidelines for Answering Questions