Skip to content

Commit 936464f

Browse files
authored
fix(iam): support adding permissions to imported roles (#2805)
Now create a Policy and attach it to imported roles as well. This will only work for imported roles in the same account. If you need to reference roles in other accounts without trying to add these policy statements, use an `AwsPrincipal`. Relates to #2381, #2651, #2652, #2662.
1 parent b8a1c8e commit 936464f

File tree

2 files changed

+40
-5
lines changed

2 files changed

+40
-5
lines changed

Diff for: packages/@aws-cdk/aws-iam/lib/role.ts

+13-5
Original file line numberDiff line numberDiff line change
@@ -116,13 +116,21 @@ export class Role extends Resource implements IRole {
116116
public readonly roleArn = roleArn;
117117
public readonly roleName = Stack.of(scope).parseArn(roleArn).resourceName!;
118118

119-
public addToPolicy(_statement: PolicyStatement): boolean {
120-
// Statement will be added to resource instead
121-
return false;
119+
private readonly attachedPolicies = new AttachedPolicies();
120+
private defaultPolicy?: Policy;
121+
122+
public addToPolicy(statement: PolicyStatement): boolean {
123+
if (!this.defaultPolicy) {
124+
this.defaultPolicy = new Policy(this, 'Policy');
125+
this.attachInlinePolicy(this.defaultPolicy);
126+
}
127+
this.defaultPolicy.addStatement(statement);
128+
return true;
122129
}
123130

124-
public attachInlinePolicy(_policy: Policy): void {
125-
// FIXME: Add warning that we're ignoring this
131+
public attachInlinePolicy(policy: Policy): void {
132+
this.attachedPolicies.attach(policy);
133+
policy.attachToRole(this);
126134
}
127135

128136
public attachManagedPolicy(_arn: string): void {

Diff for: packages/@aws-cdk/aws-iam/test/test.role.ts

+27
Original file line numberDiff line numberDiff line change
@@ -260,5 +260,32 @@ export = {
260260
test.deepEqual(importedRole.roleArn, 'arn:aws:iam::123456789012:role/S3Access');
261261
test.deepEqual(importedRole.roleName, 'S3Access');
262262
test.done();
263+
},
264+
265+
'add policy to imported role'(test: Test) {
266+
// GIVEN
267+
const stack = new Stack();
268+
const importedRole = Role.fromRoleArn(stack, 'ImportedRole', 'arn:aws:iam::123456789012:role/MyRole');
269+
270+
// WHEN
271+
importedRole.addToPolicy(new PolicyStatement()
272+
.addAction('s3:*')
273+
.addResource('xyz'));
274+
275+
// THEN
276+
expect(stack).to(haveResource('AWS::IAM::Policy', {
277+
PolicyDocument: {
278+
Statement: [
279+
{
280+
Action: "s3:*",
281+
Effect: "Allow",
282+
Resource: "xyz"
283+
}
284+
],
285+
Version: "2012-10-17"
286+
},
287+
Roles: [ "MyRole" ]
288+
}));
289+
test.done();
263290
}
264291
};

0 commit comments

Comments
 (0)