How to lookup computed value created from separate stack?

I have two stacks:
One creates a lambda function and its role
The other creates methods for use in AWS API Gateway.

Is there a way to lookup the computed ID of the lambda for use in the authorizer that’s created in the method stack? Looking at the documentation for lookup, it’s not clear if this could even be achieved. I’m open to any alternative suggestions as well (terraform version 12.5).
Thanks in advance!

Yes this can be achieved. In the first stack, you would need to define an output for the lambda id:

output "lambda_arn" {
  value = aws_lambda_function.example_lambda.arn
}

You would need to use remote state to store your state file. Terraform cloud offers this and you can sign up at app.terraform.io .

In your second stack, you would use the terraform remote state data source to import the outputs from the first stack. So it would be a little something like this:


data "terraform_remote_state" "lambdas" {
  backend = "remote"

  config = {
    organization = "DevOps-Rob"
    workspaces = {
      name = "lambda-prod"
    }
  }
}

Bare in mind that the above config block is for Terraform Cloud. You could easily adapt it to use AWS S3 bucket if thats where you’re storing your state file.

With this block declared, we now have access to the outputs in the state file of the first stack so we would reference it in a resource like this:

resource "aws_api_gateway_authorizer" "example" {
  name                   = "example"
  rest_api_id            = aws_api_gateway_rest_api.example.id
  authorizer_uri         = data.terraform_remote_state.lambdas.lambda_arn
  authorizer_credentials = aws_iam_role.invocation_role.arn
}

The authorizer_url argument shows how we have utilised the output from a remote state file. I should point out that this creates a dependancy on the first stack as it relies on an output value that does not exist until the first stack has been applied so bare this in mind with your orchestration.

Hope this helps

1 Like

Wow! Thank you so much for this exceptionally detailed response!! Very much appreciated.

1 Like

Came back to this post to use this again for another project. Note that the examples are good for 0.11.x, but in 0.12.x referencing the remote state is slightly different:

0.11.x from example in this post:

authorizer_uri         = data.terraform_remote_state.lambdas.lambda_arn

Now in 0.12.x example from same reference in this post:

authorizer_uri         = data.terraform_remote_state.lambdas.outputs.lambda_arn

I found this HERE

1 Like

Good shout @P05TMAN thanks for keeping the community updated. I’m sure many will find this useful!

1 Like