Serverless CloudFormation Exports and Terraform
By jjm
Last weekend I was doing some improvements on my blog setup, part of this was looking into how you can take CloudFormation Outputs from a serverless CF stack and use the outputs in Terraform when setting up a lambda_function_association
for CloudFront instead of them being hardcoded.
This would then allow me to create a GitHub Action workflow which deploys these Lambda functions and automatically have the latest versions auto applied next time the Terraform runs to update the AWS infrastructure for CloudFront.
Turns out it was really simple, and involved adding Outputs
under resources
and defining the required export’s for LambdaFunctionQualifiedArn
which automatically has the value already defined. Additionally the function name was also needed for aws_lambda_permission
resources later:
resources:
Outputs:
GNUTerryPratchettLambdaFunctionName:
Description: The subDirDefaultIndex Lambda Function Name.
Value:
Ref: GNUTerryPratchettLambdaFunction
Export:
Name: GNUTerryPratchettLambdaFunctionName
GNUTerryPratchettLambdaFunctionQualifiedArn:
Description: The GNUTerryPratchett Lambda Function Qualified Arn.
Export:
Name: GNUTerryPratchettLambdaFunctionQualifiedArn
Then in Terraform you just need to add an aws_cloudformation_export data source:
data "aws_cloudformation_export" "gnu_terry_pratchett_qualified_arn" {
name = "GNUTerryPratchettLambdaFunctionQualifiedArn"
}
data "aws_cloudformation_export" "gnu_terry_pratchett" {
name = "GNUTerryPratchettLambdaFunctionName"
}
Then when you want to reference the qualified ARN (including the version) of the Lambda functions its just using data.aws_cloudformation_export.gnu_terry_pratchett_qualified_arn.value
. If you need just the FunctionName it’s a case of using data.aws_cloudformation_export.gnu_terry_pratchett.value
instead.