Search code examples
aws-lambdaaws-amplifyaws-cdkaws-secrets-manager

How to Seamlessly Integrate AWS Amplify with AWS CDK for Resource Sharing?


I'm working on a project that involves both AWS Amplify for frontend hosting and authentication and AWS CDK for backend resource management. I've come across a challenge where I need to share resource ARNs (e.g., State Machine ARNs) between the two.

AWS Amplify Lambda Function Snippet:

const command = new StartExecutionCommand({
  stateMachineArn:  process.env.ENV === "prod" ? "" :"",
  input: JSON.stringify(record),
  name: "xyz",
});

To achieve this, I've considered storing these ARNs in AWS Secrets Manager, which my Lambda functions can then retrieve. However, I'm concerned about potential issues, like if the ARN changes during a CDK update but the secret in Secrets Manager hasn't been updated yet.

  1. Are there best practices or patterns for integrating AWS Amplify and AWS CDK to share resource identifiers or configurations?
  2. What pitfalls should I be aware of, and how can I mitigate potential issues like race conditions between CDK resource updates and Secrets Manager updates?
  3. Is there a more efficient way to do this without involving Secrets Manager or another service?

Any insights or recommendations would be greatly appreciated!


Solution

  • You want to expose non-secret identifiers from your backend CDK stack to an existing Lambda created with the Amplify CLI.1

    One option is to store the backend ARNs as environment variables in your "Amplify" Lambda function. The env vars would be updated every time your backend stack changes, triggered by an event. Here's how it would work:

    1. Add env vars to your Amplify Lambda. Enter the ARN values manually (a one-time manual step).
    2. CloudFormation emits events during the stack update lifecycle. Add an EventBridge rule to your backend stack that fires each time the stack is updated.
    3. Add an "Updater" Lambda to your backend stack. Set it as the rule's target.
    4. The Updater Lambda's job is to update Amplify Lambda's env vars with the SDK's UpdateFunctionConfigurationCommand. Add some env vars to the construct's environment prop: (a) the required ARNs (available as construct properties) and (b) the name of your Amplify Lambda (needed for the SDK command).

    There are other approaches. You could use a Custom Resource instead of events to trigger the Updater Lambda. You could store the ARNs in Systems Manager Parameters instead of as environment variables.2

    Also consider migrating your frontend to the CDK as well. You'd use the @aws-cdk/aws-amplify-alpha module. That would make the entire problem disappear.


    1. The problem isn't really related to Amplify: it generalizes to passing CDK identifiers to *any* non-CDK resource.
    2. Secrets cost money but Parameters are free, so I would avoid SecretsManager.