Skip to content

Instantly share code, notes, and snippets.

@nbcchen
Last active July 8, 2024 12:27
Show Gist options
  • Save nbcchen/8aef2f71bf6f7b870842b8b05d0b0d03 to your computer and use it in GitHub Desktop.
Save nbcchen/8aef2f71bf6f7b870842b8b05d0b0d03 to your computer and use it in GitHub Desktop.
Read different stuff from Serverless stack in Terraform
variable "env" {
type = string
}
# Read API Gateway API
# The name is always {stageName}-{serviceName}, unless apiName is specified
# Doesn't work with nested stacks created by serverless-plugin-split-stacks
# https://www.serverless.com/framework/docs/providers/aws/guide/serverless.yml#api-gateway-v1-rest-api
data "aws_api_gateway_rest_api" "rest_api" {
name = "${var.env}-${jsondecode(file("serverless.json"))["name"]}"
}
variable "env" {
type = string
}
data "aws_region" "current" {}
# read a serverless stack. It is always {serviceName}-{stageName}
# unless stackName is specified
# https://www.serverless.com/framework/docs/providers/aws/guide/serverless.yml#general-settings
data "aws_cloudformation_stack" "this" {
name = "${jsondecode(file("serverless.json"))["name"]}-${var.env}"
}
# Read API ID
# if there is an Api Gateway API created in the stack, Serverless emits a CloudFormation output called ServiceEndpoint
# it is the execution URL, and we can extract API ID from it
output "api_id" {
value = trimsuffix(
trimprefix(
data.aws_cloudformation_stack.this.outputs["ServiceEndpoint"],
"https://"
),
".execute-api.${data.aws_region.current.id}.amazonaws.com/${var.env}"
)
}
# Every Serverless stack that contains a Lambda function creates a deployment bucket by default,
# and the CF output name is ServerlessDeploymentBucketName
data "aws_s3_bucket" "deployment_bucket" {
bucket = data.aws_cloudformation_stack.this.outputs["ServerlessDeploymentBucketName"]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment