From 784ba7054b0dd9aeb6d9cd925b9bb687f29c5c80 Mon Sep 17 00:00:00 2001 From: Sam Goodwin Date: Fri, 15 Mar 2019 01:35:33 -0700 Subject: [PATCH] fix(lambda): expose underlying function's role on the alias --- packages/@aws-cdk/aws-lambda/lib/alias.ts | 1 + .../@aws-cdk/aws-lambda/test/test.alias.ts | 59 ++++++++++++++++++- 2 files changed, 59 insertions(+), 1 deletion(-) diff --git a/packages/@aws-cdk/aws-lambda/lib/alias.ts b/packages/@aws-cdk/aws-lambda/lib/alias.ts index ba2d0c6681520..15c4818102c05 100644 --- a/packages/@aws-cdk/aws-lambda/lib/alias.ts +++ b/packages/@aws-cdk/aws-lambda/lib/alias.ts @@ -84,6 +84,7 @@ export class Alias extends FunctionBase { super(scope, id); this.underlyingLambda = props.version.lambda; + this.role = this.underlyingLambda.role; new CfnAlias(this, 'Resource', { name: props.aliasName, diff --git a/packages/@aws-cdk/aws-lambda/test/test.alias.ts b/packages/@aws-cdk/aws-lambda/test/test.alias.ts index cd2b30baeeaa9..7ff54f0a80c59 100644 --- a/packages/@aws-cdk/aws-lambda/test/test.alias.ts +++ b/packages/@aws-cdk/aws-lambda/test/test.alias.ts @@ -1,5 +1,5 @@ import { beASupersetOfTemplate, expect, haveResource } from '@aws-cdk/assert'; -import { AccountPrincipal } from '@aws-cdk/aws-iam'; +import { AccountPrincipal, PolicyStatement } from '@aws-cdk/aws-iam'; import { Stack } from '@aws-cdk/cdk'; import { Test } from 'nodeunit'; import lambda = require('../lib'); @@ -127,6 +127,63 @@ export = { Principal: "123456" })); + test.done(); + }, + + 'alias exposes real Lambdas role'(test: Test) { + const stack = new Stack(); + + // GIVEN + const fn = new lambda.Function(stack, 'MyLambda', { + code: new lambda.InlineCode('hello()'), + handler: 'index.hello', + runtime: lambda.Runtime.NodeJS610, + }); + + const version = fn.addVersion('1'); + const alias = new lambda.Alias(stack, 'Alias', { aliasName: 'prod', version }); + + // THEN + test.equals(alias.role, fn.role); + + test.done(); + }, + + 'addToRolePolicy on alias forwards to real Lambda'(test: Test) { + const stack = new Stack(); + + // GIVEN + const fn = new lambda.Function(stack, 'MyLambda', { + code: new lambda.InlineCode('hello()'), + handler: 'index.hello', + runtime: lambda.Runtime.NodeJS610, + }); + + const version = fn.addVersion('1'); + const alias = new lambda.Alias(stack, 'Alias', { aliasName: 'prod', version }); + + // WHEN + alias.addToRolePolicy(new PolicyStatement() + .addAction('s3:GetObject') + .addAllResources()); + test.equals(alias.role, fn.role); + + // THEN + expect(stack).to(haveResource('AWS::IAM::Policy', { + PolicyDocument: { + Statement: [{ + Action: "s3:GetObject", + Effect: "Allow", + Resource: "*" + }], + Version: "2012-10-17" + }, + PolicyName: "MyLambdaServiceRoleDefaultPolicy5BBC6F68", + Roles: [{ + Ref: "MyLambdaServiceRole4539ECB6" + }] + })); + test.done(); } };