Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(stepfunctions-tasks): add optional role property to EvaluateExpressionProps #29288

Closed
Closed
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { App, Stack, StackProps } from 'aws-cdk-lib';
import * as integ from '@aws-cdk/integ-tests-alpha';
import { Construct } from 'constructs';
import * as sfn from 'aws-cdk-lib/aws-stepfunctions';
import * as iam from 'aws-cdk-lib/aws-iam';
import * as cdk from 'aws-cdk-lib';
import * as tasks from 'aws-cdk-lib/aws-stepfunctions-tasks';
import { STANDARD_NODEJS_RUNTIME } from '../../config';
Expand All @@ -14,9 +15,19 @@ import { STANDARD_NODEJS_RUNTIME } from '../../config';
*/

class TestStack extends Stack {

readonly statemachine: sfn.StateMachine;

constructor(scope: Construct, id: string, props?: StackProps) {
super(scope, id, props);

const customRole = new iam.Role(this, 'Role', {
assumedBy: new iam.ServicePrincipal('lambda.amazonaws.com'),
});
customRole.addManagedPolicy(
iam.ManagedPolicy.fromAwsManagedPolicyName('service-role/AWSLambdaBasicExecutionRole'),
);

const sum = new tasks.EvaluateExpression(this, 'Sum', {
expression: '$.a + $.b',
resultPath: '$.c',
Expand All @@ -32,9 +43,10 @@ class TestStack extends Stack {
expression: '(new Date()).toUTCString()',
resultPath: '$.now',
runtime: STANDARD_NODEJS_RUNTIME,
role: customRole,
});

const statemachine = new sfn.StateMachine(this, 'StateMachine', {
this.statemachine = new sfn.StateMachine(this, 'StateMachine', {
definition: sum
.next(multiply)
.next(
Expand All @@ -46,16 +58,39 @@ class TestStack extends Stack {
});

new cdk.CfnOutput(this, 'StateMachineARN', {
value: statemachine.stateMachineArn,
value: this.statemachine.stateMachineArn,
});
}
}

const app = new App();

new integ.IntegTest(app, 'EvaluateExpressionInteg', {
testCases: [new TestStack(app, 'cdk-sfn-evaluate-expression-integ')],
const testStack = new TestStack(app, 'cdk-sfn-evaluate-expression-integ');

const testCase = new integ.IntegTest(app, 'EvaluateExpressionInteg', {
testCases: [testStack],
diffAssets: true,
});

const start = testCase.assertions.awsApiCall('StepFunctions', 'startExecution', {
stateMachineArn: testStack.statemachine.stateMachineArn,
name: '309d2593-a5a2-4ea5-b401-f778ef06467c',
input: '{ "a": 3, "b": 4 }',
});

// describe the results of the execution
testCase.assertions
.awsApiCall(
'StepFunctions',
'describeExecution',
{
executionArn: start.getAttString('executionArn'),
})
.expect(integ.ExpectedResult.objectLike({
status: 'SUCCEEDED',
}))
.waitForAssertions({
totalTimeout: cdk.Duration.minutes(3),
});

app.synth();
7 changes: 4 additions & 3 deletions packages/aws-cdk-lib/aws-stepfunctions-tasks/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -127,9 +127,10 @@ new sfn.StateMachine(this, 'StateMachine', {
});
```

The `EvaluateExpression` supports a `runtime` prop to specify the Lambda
runtime to use to evaluate the expression. Currently, only runtimes
of the Node.js family are supported.
The `EvaluateExpression` supports a `runtime` prop to specify the Lambda runtime to use to evaluate
the expression. Currently, only runtimes of the Node.js family are supported.

To bring your own custom execution role for the Lambda function use the `role` property.

## API Gateway

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,13 @@ export interface EvaluateExpressionProps extends sfn.TaskStateBaseProps {
* @default - the latest Lambda node runtime available in your region.
*/
readonly runtime?: lambda.Runtime;

/**
* This is the role that will be assumed by the function upon execution.
*
* @default - a role will be automatically created
lagroujl marked this conversation as resolved.
Show resolved Hide resolved
*/
readonly role?: iam.IRole;
}

/**
Expand Down Expand Up @@ -58,7 +65,7 @@ export class EvaluateExpression extends sfn.TaskStateBase {
constructor(scope: Construct, id: string, private readonly props: EvaluateExpressionProps) {
super(scope, id, props);

this.evalFn = createEvalFn(this.props.runtime, this);
this.evalFn = createEvalFn(this.props, this);

this.taskPolicies = [
new iam.PolicyStatement({
Expand Down Expand Up @@ -96,7 +103,7 @@ export class EvaluateExpression extends sfn.TaskStateBase {
}
}

function createEvalFn(runtime: lambda.Runtime | undefined, scope: Construct) {
function createEvalFn(props: EvaluateExpressionProps, scope: Construct) {
const NO_RUNTIME = Symbol.for('no-runtime');
const lambdaPurpose = 'Eval';

Expand All @@ -112,14 +119,19 @@ function createEvalFn(runtime: lambda.Runtime | undefined, scope: Construct) {
[NO_RUNTIME]: '41256dc5-4457-4273-8ed9-17bc818694e5',
};

const uuid = nodeJsGuids[runtime?.name ?? NO_RUNTIME];
let uuid = nodeJsGuids[props.runtime?.name ?? NO_RUNTIME];
if (!uuid) {
throw new Error(`The runtime ${runtime?.name} is currently not supported.`);
throw new Error(`The runtime ${props.runtime?.name} is currently not supported.`);
}

if (props.role) {
uuid += props.role.node.addr;
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I am not totally sure if this is the right way to go about this. But the point is, I want the role to be part of the signature of the function created, so if I want to use different roles in one part of the stack or don't set a role at all, it will create different functions, instead of the first occurrence blocking all of the others.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is there a risk of this uuid being too long?

Copy link
Author

@lagroujl lagroujl Mar 20, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I could not find one documented. Also, addr should have a fixed length of 42. SingletonFunction eventually passes it to tryFindChild. So that is where a length constraint could potentially come up, but otherwise, I think the risk is very low/none.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

More likely, what I'm worried about is this addr value changing between deployments and deleting/recreating the function. I'm not sure I understand how the value of addr is calculated well enough to guarantee that won't happen

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Are you able to test that? Does it change?

Copy link
Contributor

@paulhcsun paulhcsun Apr 26, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What is the value of props.role.node.addr? Could we use the props.role.roleName/roleArn instead?

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What is the value of props.role.node.addr?

https://docs.aws.amazon.com/cdk/api/v2/docs/constructs.Node.html#addr

tl:dr; SHA-1 of the components of the construct path.

Could we use the props.role.roleName/roleArn instead?

No. this could be a token and change between deployments.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Were you able to test if the value of props.role.node.addr changes between deployments? From the description, Addresses are calculated using a SHA-1 of the components of the construct path., I'm not confident that it would be the same between deployments.

}

return new EvalNodejsSingletonFunction(scope, 'EvalFunction', {
uuid,
lambdaPurpose,
runtime,
role: props.role,
});
}
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { Template } from '../../assertions';
import * as iam from '../../aws-iam';
import { Runtime, RuntimeFamily } from '../../aws-lambda';
import * as sfn from '../../aws-stepfunctions';
import { Stack } from '../../core';
Expand Down Expand Up @@ -111,3 +112,47 @@ test('With Node.js 20.x', () => {
Runtime: 'nodejs20.x',
});
});

test('With created role', () => {
// WHEN
const role = new iam.Role(stack, 'Role', {
assumedBy: new iam.ServicePrincipal('lambda.amazonaws.com'),
roleName: 'role-for-test',
});

const taskWithoutRole = new tasks.EvaluateExpression(stack, 'TaskWithoutRole', {
expression: '$.a + $.b',
});

const taskWithRole = new tasks.EvaluateExpression(stack, 'TaskWithRole', {
expression: '$.a + $.b',
role,
});

new sfn.StateMachine(stack, 'SM', {
definitionBody: sfn.DefinitionBody.fromChainable(taskWithRole.next(taskWithoutRole)),
});

// THEN
Template.fromStack(stack).resourceCountIs('AWS::Lambda::Function', 2);

Template.fromStack(stack).hasResourceProperties('AWS::Lambda::Function', {
Runtime: 'nodejs18.x',
Role: {
'Fn::GetAtt': ['Role1ABCC5F0', 'Arn'],
},
});

Template.fromStack(stack).resourcePropertiesCountIs('AWS::IAM::Role', {
AssumeRolePolicyDocument: {
Statement: [
{
Principal: {
Service: 'lambda.amazonaws.com',
},
},
],
},
},
2);
});
Loading