Deploy a basic Flask web server by using Terraform Stay organized with collections Save and categorize content based on your preferences.
In this tutorial, you learn how to get started with Terraform by using Terraformto create a basic web server on Compute Engine.
In this tutorial, you do the following:
- Use Terraform to create a VM in Google Cloud.
- Start a basic Python Flask server.
Costs
In this document, you use the following billable components of Google Cloud:
To generate a cost estimate based on your projected usage, use thepricing calculator.
When you finish the tasks that are described in this document, you can avoid continued billing by deleting the resources that you created. For more information, seeClean up.
Before you begin
Prepare to start the tutorial.
Select or create a project
In the Google Cloud console, go to the project selector page.
Select or create a Google Cloud project.
Note: If you don't plan to keep the resources that you create in this procedure, create a project instead of selecting an existing project. After you finish these steps, you can delete the project, removing all resources associated with the project.Roles required to select or create a project
- Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
- Create a project: To create a project, you need the Project Creator role (
roles/resourcemanager.projectCreator), which contains theresourcemanager.projects.createpermission.Learn how to grant roles.
Set up permissions
Make sure that you have the necessaryCompute Engine permissions on your user account:
compute.instances.*compute.firewalls.*
Learn more about roles and permissions.
Enable the API
Enable the Compute Engine API.
Roles required to enable APIs
To enable APIs, you need the Service Usage Admin IAM role (roles/serviceusage.serviceUsageAdmin), which contains theserviceusage.services.enable permission.Learn how to grant roles.
Start Cloud Shell
Cloud Shell is aCompute Engine virtual machine.
The service credentials associated with this virtual machine are automatic, sothere is no need to set up or download a service account key.
Terraform is integrated with Cloud Shell, and Cloud Shell automaticallyauthenticates Terraform, letting you get started with less setup.
Create the Compute Engine VM
First, you define the VM's settings in a Terraform configuration file. Then, yourun Terraform commands to create the VM in your project.
Create the directory
Create a new directory. In your new directory, create amain.tf file for the Terraform configuration. The contents of this filedescribe all of the Google Cloud resources to be created in the project.
In Cloud Shell:
mkdir tf-tutorial && cd tf-tutorial
nano main.tf
Create the Virtual Private Cloud network and subnet
In this section, you create a Virtual Private Cloud (VPC) network and subnet for the VM'snetwork interface.
Add the following Terraform resources to themain.tf file that you created:
resource "google_compute_network" "vpc_network" { name = "my-custom-mode-network" auto_create_subnetworks = false mtu = 1460}resource "google_compute_subnetwork" "default" { name = "my-custom-subnet" ip_cidr_range = "10.0.1.0/24" region = "us-west1" network = google_compute_network.vpc_network.id}Create the Compute Engine VM resource
In this section, you create a single Compute Engine instance runningDebian. In this tutorial, you use the smallestmachine type that's available. Later, you canupgrade to a larger machine type.
Add the followinggoogle_compute_instance Terraform resource to themain.tf file that you created.
# Create a single Compute Engine instanceresource "google_compute_instance" "default" { name = "flask-vm" machine_type = "f1-micro" zone = "us-west1-a" tags = ["ssh"] boot_disk { initialize_params { image = "debian-cloud/debian-11" } } # Install Flask metadata_startup_script = "sudo apt-get update; sudo apt-get install -yq build-essential python3-pip rsync; pip install flask" network_interface { subnetwork = google_compute_subnetwork.default.id access_config { # Include this section to give the VM an external IP address } }}The sample code sets the Google Cloud zone tous-west1-a. You can changethis to a differentzone.
Initialize Terraform
At this point, you can runterraform init to add the necessary plugins andbuild the.terraform directory.
terraform init
Output:
Initializing the backend...Initializing provider plugins......Terraform has been successfully initialized!
Validate the Terraform configuration
Optionally, you can validate the Terraform code that you've built so far. Runterraform plan, which does the following:
- Verifies that the syntax of
main.tfis correct - Shows a preview of the resources that will be created
terraform plan
Output:
...Plan: 1 to add, 0 to change, 0 to destroy.Note: You didn't use the -out option to save this plan, so Terraform can'tguarantee to take exactly these actions if you run "terraform apply" now.
Apply the configuration
To create the VM, runterraform apply.
terraform apply
When prompted, enteryes.
Terraform calls Google Cloud APIs to set up the new VM. Check theVM instances page tosee the new VM.
Run a web server on Google Cloud
Your next steps are getting a web application created, deploying it to theVM, and creating a firewall rule to allow client requests to the webapplication.
Add a custom SSH firewall rule
Thedefault-allow-ssh firewall rule in thedefault network lets you useSSH to connect to the VM. If you'd rather use your own custom firewallrule, you can add the following resource at the end of yourmain.tf file:
resource "google_compute_firewall" "ssh" { name = "allow-ssh" allow { ports = ["22"] protocol = "tcp" } direction = "INGRESS" network = google_compute_network.vpc_network.id priority = 1000 source_ranges = ["0.0.0.0/0"] target_tags = ["ssh"]}Runterraform apply to create the firewall rule.
Connect to the VM with SSH
Validate that everything is set up correctly at this point by connecting to theVM with SSH.
Go to theVM Instances page.
Find the VM with the name
flask-vm.InConnect column, clickSSH.
An SSH-in-browser terminal window opens for the running VM.
For more information, seeConnecting toVMs.
Build the Flask app
You build aPython Flask app for this tutorial sothat you can have a single file describing your web server and test endpoints.
In the SSH-in-browser terminal, create a file called
app.py.nano app.py
Add the following to the
app.pyfile:fromflaskimportFlaskapp=Flask(__name__)@app.route('/')defhello_cloud():return'Hello Cloud!'app.run(host='0.0.0.0')Run
app.py:python3 app.py
Flask serves traffic on
Warning: This is a development server. Do not use it in a productiondeployment.localhost:5000by default.Open a second SSH connection:
- Go to theVM Instances page.
- Find the VM named
flask-vmand clickSSH.
In the second SSH connection, run
curlto confirm that the greeting thatyou configured inapp.pyis returned.curl http://0.0.0.0:5000
The output from this command is
Hello Cloud.
Open port 5000 on the VM
To connect to the web server from your local computer, the VM must haveport 5000 open. Google Cloud lets you open ports to traffic by usingfirewall rules.
Add the followinggoogle_compute_firewall Terraform resource at the end of yourmain.tf file.
resource "google_compute_firewall" "flask" { name = "flask-app-firewall" network = google_compute_network.vpc_network.id allow { protocol = "tcp" ports = ["5000"] } source_ranges = ["0.0.0.0/0"]}In Cloud Shell, runterraform apply to create the firewall rule.
Add an output variable for the web server URL
At the end of
main.tf, adda Terraform outputvariable to output the web server URL:// A variable for extracting the external IP address of the VMoutput "Web-server-URL" { value = join("",["http://",google_compute_instance.default.network_interface.0.access_config.0.nat_ip,":5000"])}Run
terraform apply.terraform apply
When prompted, enter
yes. Terraform prints the VM's external IPaddress and port 5000 to the screen, as follows:Web-server-URL = "http://IP_ADDRESS:5000"
At any time, you can run
terraform outputto return thisoutput:terraform output
Click the URL from the previous step, and see the "Hello Cloud!" message.
This means that your server is running.
Troubleshooting
If a required API isn't enabled, Terraform returns an error. The error messageincludes a link to enable the API. After enabling the API, you can rerun
terraform apply.If you can't connect to your VM through SSH:
- Make sure to add theSSH firewall rule.
- Make sure that your VM includes the
tags = ["ssh"]argument.
Clean up
After completing the tutorial, you can delete everything that youcreated so that you don't incur any further costs.
Terraform lets you remove all the resources defined in the configuration file byrunning theterraform destroy command:
terraform destroy
Enteryes to allow Terraform to delete your resources.
What's next
Except as otherwise noted, the content of this page is licensed under theCreative Commons Attribution 4.0 License, and code samples are licensed under theApache 2.0 License. For details, see theGoogle Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.
Last updated 2025-12-15 UTC.