Marrying Terraform and Serverless Framework by Using the Parameter Store

Marrying Terraform and Serverless Framework by Using the Parameter Store

Get the best of both worlds by leveraging the Parameter Store to exchange ARNs

If you want to build a serverless application, the Serverless Framework gives you a head start if you want to have your service up and running fast. In very few lines of YAML, you’re able to configure Lambda functions and expose them via REST, HTTP, or event Socket Gateways. You’re able to attach authorizers easily and you can do a lot of fine-tuning like for example adding CloudWatch triggers for regularly invoking your functions to stay warm.

But what if your application ecosystems evolve around more than Lambda functions and gateways? Most likely you’ve used Terraform for provisioning and managing your infrastructure and I don’t need to highlight all of its awesome features. Surely, you could define your remaining infrastructure by extending your serverless.yml file with custom CloudFormation resources. But that’s not fun and you will miss Terraform soon.

There’s an easy way to combine both.

Getting the best of the two worlds

You can maintain all your infrastructure, excluding your Lambda functions and gateways, with Terraform and then just expose everything you need in your serverless functions via the Parameter Store. For example, if you want to use DynamoDB and its streams capability, just expose the ARN of the stream:

resource "aws_ssm_parameter" "stream_arn" {  
  type        = "String"  
  name        = "transaction-stream-arn"  
  value       = aws_dynamodb_table.transaction.stream_arn  
  overwrite   = true  

  lifecycle {  
    ignore_changes = [value]  
  }  
}

Afterward, you can use the exposed parameters in your serverless.yml via ${ssm.eu-central-1:/transaction-stream-arn}. The only thing you need to make sure is that your dependencies are always from your serverless infrastructure to infrastructure created via Terraform because you need to apply Terraform at first and you can’t have cyclic dependencies.

Combining Serverless Framework with Terraform via Parameter Store

That’s it. 🎉