Deploy a Node.js API on Google Cloud Functions using Terraform
terraform
node
(latest version supported by Cloud Functions)gcloud
- Write your code on
src/
and run:
# Run function locally
npm run dev
- Write tests on
test/
npm run test
-
Create a Google Cloud account and set up Billing
-
Initialize the CLI
gcloud init
- Create a new project
# Replace PROJECT_ID with your Project ID.
gcloud projects create PROJECT_ID --name="My App"
- Set the project as default
gcloud config set project PROJECT_ID
- Enable billing
# List billing accounts
gcloud beta billing accounts list
# Link a billing account to project
gcloud beta billing projects link PROJECT_ID --billing-account=BILLING_ACCOUNT_ID
- Create the initial bucket
This bucket will store the .tfstate
files.
gsutil mb gs://PROJECT_ID-tfstate
- Rename
terraform.tfvars.example
# Development
mv terraform/environments/development/terraform.tfvars.example terraform/environments/development/terraform.tfvars
# Production
mv terraform/environments/production/terraform.tfvars.example mv terraform/environments/production/terraform.tfvars
-
On
terraform/
, find and replacePROJECT_ID
with your Project ID. -
Deploy 🤞
# Development
cd terraform/environments/development
# Production
cd terraform/environments/production
terraform init
terraform plan
terraform apply
You will see the function URL at the end of the result.
To shut everything down, run the following commands on this order:
# Delete all infrastructure
terraform destroy
# Optional: delete the project
gcloud projects delete PROJECT_ID
Deployment
When deploying for the first time, it can happen that Cloud Functions API and Cloud Build API are still being enabled and terraform apply
will fail. Just wait a few minutes and run the command again.
MIT 2020 Ruan Martinelli