This Terraform script sets up a basic AWS infrastructure for a serverless application. The infrastructure includes a VPC with public and private subnets, an Internet Gateway, a NAT Gateway, an Amazon DocumentDB cluster, an API Gateway, and a Lambda function. The Lambda function interacts with the DocumentDB cluster, and the API Gateway provides a public interface to trigger the Lambda function.
Here is the design of the solution construct

- AWS CLI installed and configured
- Terraform CLI installed
- Configures the AWS provider for the
eu-west-1region.
provider "aws" {
region = "eu-west-1"
}- Defines a variable
secret_idwith a default value. This variable is used as the name for the DocumentDB cluster.
variable "secret_id" {
type = string
default = "documentdbblogdemo"
}- Creates a VPC with DNS support and hostnames enabled.
resource "aws_vpc" "vpc" {
cidr_block = "10.0.0.0/16"
enable_dns_support = true
enable_dns_hostnames = true
tags = {
Name = "Otel-Serverless-Demo"
}
}- Creates an Internet Gateway and associates it with the VPC.
resource "aws_internet_gateway" "gw" {
vpc_id = aws_vpc.vpc.id
tags = {
Name = "main"
}
}- Defines public and private subnets.
resource "aws_subnet" "public_subnet" {
count = 1
...
}
resource "aws_subnet" "private_subnet" {
count = 2
...
}- Creates a NAT Gateway for private subnet communication.
resource "aws_nat_gateway" "nat_gateway" {
...
}- Defines route tables for private subnets.
resource "aws_route_table" "private_route_table" {
...
}- Creates an Amazon DocumentDB cluster.
resource "aws_docdb_cluster" "docdb_cluster" {
...
}- Defines security groups for NAT Gateway and DocumentDB cluster.
resource "aws_security_group" "nat_sg" {
...
}
resource "aws_security_group" "docdb_sg" {
...
}- Sets up a Lambda function with necessary IAM roles and policies.
resource "aws_lambda_function" "lambda_function" {
...
}- Configures an API Gateway to trigger the Lambda function.
resource "aws_apigatewayv2_api" "http_api" {
...
}- Defines IAM roles and policies for Lambda execution.
resource "aws_iam_role" "iam_for_lambda" {
...
}
resource "aws_iam_policy" "lambda_policy" {
...
}- Sets up AWS Secrets Manager for storing secret information.
resource "aws_secretsmanager_secret" "docdb_secret" {
...
}
resource "aws_secretsmanager_secret_version" "docdb_secret_version" {
...
}- Deploys the API Gateway.
resource "aws_apigatewayv2_deployment" "api_deployment" {
...
}- Grants API Gateway permission to invoke the Lambda function.
resource "aws_lambda_permission" "lambda_permission" {
...
}- Outputs the URL of the deployed API Gateway stage.
output "api_gateway_url" {
...
}- Make sure your AWS CLI is configured with the necessary credentials.
- Install the Terraform CLI.
- Run
terraform initandterraform applyto create the infrastructure.
Remember to destroy the resources after usage by running terraform destroy to avoid unnecessary costs.