๐Ÿš€ How to Integrate a Cross-Account Lambda with a API Gateway REST API ๐ŸŒ

chanaka.supun
4 min readOct 17, 2024

--

Hey there! ๐Ÿ‘‹ Recently, I ran into a cool challenge: How do you hook up a Lambda function from one AWS account with a REST API in another? ๐Ÿค” As more organizations go the multi-account route for better security and structure, connecting cross-account Lambdas with REST or HTTP APIs is becoming super common! ๐Ÿ’ปโœจ

So, if youโ€™re in that boat ๐Ÿ›ณ๏ธ, hereโ€™s a fun step-by-step guide on how to do it! ๐ŸŽ‰ Letโ€™s dive in! ๐ŸŠโ€โ™‚๏ธ

๐ŸŽฏ Audience:
Hey new joiners! ๐Ÿ‘‹ This article is just for YOU! ๐ŸŽ‰ If youโ€™re new to aws or curious about how to set up a REST API with cross-account Lambda integration, youโ€™re in the right place! ๐Ÿš€ Whether youโ€™re just getting started or want to sharpen your skills, this guide will walk you through everything step-by-step. ๐Ÿ› ๏ธ Letโ€™s get you up and running in no time! ๐Ÿ’ก๐Ÿ”ฅ

๐ŸŽฏ What Youโ€™ll Need:

  • 2 AWS accounts (weโ€™ll call them Account A & Account B ๐Ÿ ๐Ÿ )
  • IAM permissions to create Lambda, API Gateway, and IAM roles ๐Ÿ”‘

๐Ÿ› ๏ธ Step 1: Create a Lambda Function in Account B

First, we need to whip up a Lambda function in Account B. ๐Ÿง‘โ€๐Ÿ’ป Hereโ€™s a simple code to start with:

export const handler = async (event) => {
// TODO implement
const response = {
statusCode: 200,
body: JSON.stringify('Hello from lambda!'),
};
return response;
};

Once thatโ€™s done, copy the ARN of the Lambda function. Weโ€™ll need this later! ๐Ÿ“โœจ

๐ŸŒ Step 2: Set Up an API Gateway in Account A

Hop over to Account A ๐Ÿƒโ€โ™‚๏ธ and create a shiny new API Gateway!

โœจ After that, add a method and paste the ARN of the Lambda function from Account B into the Lambda function section. ๐Ÿ’ก

Donโ€™t forget to copy the ARN of the API Gateway resource โ€” youโ€™ll need it in the next step! ๐Ÿ“‹

โš™๏ธ Step 3: Permissions Setup

Okay, time to test!

๐ŸŽฏ Butโ€ฆ ๐Ÿ›‘ Oops! Youโ€™ll probably get an error like:

โŒ Execution failed due to configuration error: Invalid permissions on Lambda function ๐Ÿ˜ฌ

No worries, letโ€™s fix this! ๐Ÿง‘โ€๐Ÿ”ง

Go back to Account B, navigate to your Lambda function, and head to the Permissions section. ๐Ÿ” Scroll to Resource-based policy statements and click Add permission.

  • Choose API Gateway as the AWS service
  • Paste the API Gateway ARN you copied earlier (you can use a wildcard * for the method)
  • For Action, select lambda:InvokeFunction ๐Ÿ› ๏ธ

Save your changes, and youโ€™re good to go! โœ…

๐Ÿš€ Step 4: Test It!

Back in Account A, letโ€™s give it another whirl! ๐ŸŽฏ Run the API call, andโ€ฆ ๐ŸŽ‰ You should see a successful response from your Lambda now! ๐Ÿ™Œ

And thatโ€™s it! Youโ€™ve successfully connected your cross-account Lambda with a REST API! ๐ŸŽ‰๐ŸŽ‰ Super cool, right? Now go and wow your team with this seamless integration! ๐Ÿ’ก๐Ÿ’ช

--

--