CodexBloom - Programming Q&A Platform

Terraform: implementing Role Assumption for Cross-Account Lambda Invocation

👀 Views: 1 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-11
terraform aws lambda cross-account JavaScript

I'm working with a scenario while trying to set up a Lambda function in one AWS account to invoke a resource in another account using Terraform. The Lambda function is configured to assume a role in the target account, but I'm getting a `AccessDeniedException` when the function attempts to invoke the resource. Here's a simplified version of what I've done: 1. In the target account, I've created a role with a trust relationship that allows the Lambda execution role from the source account to assume it. The trust policy looks like this: ```json { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Principal": { "AWS": "arn:aws:iam::SOURCE_ACCOUNT_ID:role/LambdaExecutionRole" }, "Action": "sts:AssumeRole" } ] } ``` 2. In the source account, I have the Lambda function and the execution role defined like this: ```hcl resource "aws_iam_role" "lambda_exec_role" { name = "LambdaExecutionRole" assume_role_policy = data.aws_iam_policy_document.lambda_assume_role_policy.json } data "aws_iam_policy_document" "lambda_assume_role_policy" { statement { actions = ["sts:AssumeRole"] principals { type = "AWS" identifiers = [aws_iam_role.target_role.arn] } } } resource "aws_lambda_function" "my_lambda" { function_name = "MyLambdaFunction" role = aws_iam_role.lambda_exec_role.arn handler = "index.handler" runtime = "nodejs14.x" source_code_hash = filebase64sha256("./lambda.zip") } ``` 3. I'm also invoking the resource with the following code in the Lambda: ```javascript const AWS = require('aws-sdk'); const lambda = new AWS.Lambda(); exports.handler = async (event) => { const params = { FunctionName: 'arn:aws:lambda:TARGET_REGION:TARGET_ACCOUNT_ID:function:TargetFunction', InvocationType: 'Event', }; return await lambda.invoke(params).promise(); }; ``` Despite setting everything up according to the documentation, I still receive an `AccessDeniedException` indicating that the Lambda function want to assume the required role. I've double-checked the role ARNs and trust relationships, and they seem correct. Has anyone encountered this scenario or have any insights on what might be going wrong? Any help would be greatly appreciated! This is for a microservice running on Debian. Any advice would be much appreciated.