Aziz.G
Aziz.G

Reputation: 3721

Adding managed policy aws with cdk

I am trying to add a managed policy to a role that contains an account id:

    const role = iam.Role.fromRoleArn(
          this,
          'Role',
          `arn:aws:iam::${cdk.Stack.of(this).account}:role/example-role`,
        );
    
        role.addManagedPolicy(iam.ManagedPolicy.fromAwsManagedPolicyName('AmazonDynamoDBFullAccess'));
        role.addManagedPolicy(iam.ManagedPolicy.fromAwsManagedPolicyName('AmazonKinesisFullAccess'));

on the aws console i can't see the policy being added to the role.

fyi My aws-cli is logged with the right account.

enter image description here

Upvotes: 2

Views: 10277

Answers (2)

gshpychka
gshpychka

Reputation: 11512

Unfortunately, CDK cannot modify external resources. So the changes will go through, but will have no effect.

The proper way is to create the role with CDK and add the policy in the same place where you're creating the role.

Here's a relevant excerpt from the documentation:

Although you can use an external resource anywhere you'd use a similar resource defined in your AWS CDK app, you cannot modify it. For example, calling addToResourcePolicy (Python: add_to_resource_policy) on an external s3.Bucket does nothing.

Upvotes: 5

kidbrax
kidbrax

Reputation: 2434

The docs seem to say this is possible, but I am having the same issue.

Using existing roles

If there are Roles in your account that have already been created which you would like to use in your CDK application, you can use Role.fromRoleArn to import them, as follows:

role = iam.Role.from_role_arn(self, "Role", "arn:aws:iam::123456789012:role/MyExistingRole",
    # Set 'mutable' to 'false' to use the role as-is and prevent adding new
    # policies to it. The default is 'true', which means the role may be
    # modified as part of the deployment.
    mutable=False
)

Upvotes: 1

Related Questions