๐ How to Integrate a Cross-Account Lambda with a API Gateway REST API ๐
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! ๐ก๐ช