Skip to content

Commit

Permalink
feat(iam): support importing service roles (#5701)
Browse files Browse the repository at this point in the history
Service roles have a different ARN structure
(they have a 'service-role/' segment after the 'role/' part).
Explicitly check for that case when importing a role with such an ARN
(you cannot pass 'service-role/RoleName' as a legal role name).

Fixes #2651

Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
  • Loading branch information
skinny85 and mergify[bot] committed Jan 8, 2020
1 parent d323c0c commit 0f02dad
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 1 deletion.
7 changes: 6 additions & 1 deletion packages/@aws-cdk/aws-iam/lib/role.ts
Original file line number Diff line number Diff line change
Expand Up @@ -155,7 +155,12 @@ export class Role extends Resource implements IRole {
public static fromRoleArn(scope: Construct, id: string, roleArn: string, options: FromRoleArnOptions = {}): IRole {
const scopeStack = Stack.of(scope);
const parsedArn = scopeStack.parseArn(roleArn);
const roleName = parsedArn.resourceName!;
const resourceName = parsedArn.resourceName!;
// service roles have an ARN like 'arn:aws:iam::<account>:role/service-role/<roleName>'
// we want to support these as well, so strip out the 'service-role/' prefix if we see it
const roleName = resourceName.startsWith('service-role/')
? resourceName.slice('service-role/'.length)
: resourceName;

abstract class Import extends Resource implements IRole {
public readonly grantPrincipal: IPrincipal = this;
Expand Down
21 changes: 21 additions & 0 deletions packages/@aws-cdk/aws-iam/test/role.from-role-arn.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -476,6 +476,27 @@ describe('IAM Role.fromRoleArn', () => {
});
});
});

describe('imported with the ARN of a service role', () => {
beforeEach(() => {
roleStack = new Stack();
importedRole = Role.fromRoleArn(roleStack, 'Role',
`arn:aws:iam::${roleAccount}:role/service-role/codebuild-role`);
});

it("correctly strips the 'service-role' prefix from the role name", () => {
new Policy(roleStack, 'Policy', {
statements: [somePolicyStatement()],
roles: [importedRole],
});

expect(roleStack).toHaveResourceLike('AWS::IAM::Policy', {
"Roles": [
"codebuild-role",
],
});
});
});
});

function somePolicyStatement() {
Expand Down

0 comments on commit 0f02dad

Please sign in to comment.