Jump Start Solution: Three-tier web app

Last reviewed 2024-10-08 UTC

This guide helps you understand and deploy the Three-tier web app Jump Start Solution, which demonstrates how to quickly deploy a multi-tier web application stack to Google Cloud.

The three-tier web app solution deploys a task-tracker app in Google Cloud. The app has a web-based frontend and an API layer in the middle tier. The frontend and API layer are containerized apps that are deployed as serverless services. The backend is a SQL database. The solution also includes an in-memory cache to serve frequently accessed data. Each tier in this solution is independent. You can develop, update, and scale any tier without affecting the other tiers. This architecture enables efficient app development and delivery.

This guide is intended for developers who have some background with deploying multi-tier app stacks. It assumes that you're familiar with basic cloud concepts, though not necessarily Google Cloud. Experience with Terraform is helpful.

Products used

The solution uses the following Google Cloud products:

  • Cloud Run: A fully managed service that lets you build and deploy serverless containerized apps. Google Cloud handles scaling and other infrastructure tasks so that you can focus on the business logic of your code.
  • Cloud SQL: A fully managed MySQL or PostgreSQL database in Google Cloud.
  • Memorystore for Redis: A service that provides application caching using a scalable, secure, and highly available in-memory service for Redis and Memcached.
  • Virtual Private Cloud (VPC) network: A global virtual network that spans all Google Cloud regions and that lets you interconnect your cloud resources.

For information about how these products are configured and how they interact, see the next section.

Architecture

The example app that the three-tier web app solution deploys is a task-tracking app for which the code already exists. The following diagram shows the architecture of the infrastructure that the solution deploys:

Architecture of the infrastructure required for the three-tier web app solution.

The following subsections describe the request flow and the configuration of the Google Cloud resources that are shown in the diagram.

Request flow

The following is the request processing flow of the task-tracker app that this solution deploys. The steps in the flow are numbered as shown in the preceding architecture diagram.

  1. A web-based frontend receives requests from clients to the task-tracker app. The frontend is a Cloud Run service, which renders an HTML client in the user's browser.
  2. The frontend sends requests to an API layer, which is also deployed as a Cloud Run service.
  3. Data that is read frequently is cached in and served from a Memorystore for Redis instance.
  4. Requests that can't be served from the in-memory Redis cache are sent by the API layer to a Cloud SQL database.

Resource configuration

This section describes the configuration of the Cloud Run, Memorystore, Cloud SQL, and networking resources that the solution deploys. If you're familiar with the Terraform configuration language, you can change some of these settings, as described later in this guide.

To view the configuration settings, click the following subsections:

Cloud Run services

Parameter Preconfigured setting
Compute capacity per container instance 1 vCPU, 512-MiB memory
Autoscaling range (number of container instances)

Frontend: 0-8

API layer: 0-8

Memorystore for Redis instance

Parameter Preconfigured setting
Redis version Version 6.x
Service tier Basic, no high availability (HA)
Memory 1 GB
Data encryption

At rest: Google-owned and Google-managed key

In transit: Not encrypted

Cloud SQL database

Parameter Preconfigured setting
Database version PostgreSQL 14 or MySQL 8.0
Machine type db-g1-small: 1 vCPU, 1.7-GB memory
Availability Single zone
Storage 10-GB SSD, with autoscaling enabled

Networking resources

The Cloud SQL instance is attached to a customer-created VPC network and has an internal IP address.

Serverless VPC Access provides connectivity from the Cloud Run instance that hosts the API layer to the Cloud SQL instance. Requests from the Cloud Run service to the Cloud SQL instance use internal DNS and internal IP addresses. Response traffic also uses the internal network. In other words, traffic between the app and the database is not exposed to the internet. Also, traffic over Serverless VPC Access can have lower latency than traffic that traverses the internet.

Connectivity between the Memorystore instance and the Cloud SQL database is through a direct-peering connection.

Cost

For an estimate of the cost of the Google Cloud resources that the three-tier web app solution uses, see the precalculated estimate in the Google Cloud Pricing Calculator.

Use the estimate as a starting point to calculate the cost of your deployment. You can modify the estimate to reflect any configuration changes that you plan to make for the resources that are used in the solution.

The precalculated estimate is based on assumptions for certain factors, including the following:

  • The Google Cloud locations where the resources are deployed.
  • The amount of time that the resources are used.

Before you begin

To deploy this solution, you first need a Google Cloud project and some IAM permissions.

Create or choose a Google Cloud project

When you deploy the solution, you choose the Google Cloud project where the resources are deployed. You can either create a new project or use an existing project for the deployment.

If you want to create a new project, do so before you begin the deployment. Using a new project can help avoid conflicts with previously provisioned resources, such as resources that are used for production workloads.

To create a project, complete the following steps:

  1. In the Google Cloud console, go to the project selector page.

    Go to project selector

  2. Click Create project.

  3. Name your project. Make a note of your generated project ID.

  4. Edit the other fields as needed.

  5. Click Create.

Get the required IAM permissions

To start the deployment process, you need the Identity and Access Management (IAM) permissions that are listed in the following table.

If you created a new project for this solution, then you have the roles/owner basic role in that project and have all the necessary permissions. If you don't have the roles/owner role, then ask your administrator to grant these permissions (or the roles that include these permissions) to you.

IAM permission required Predefined role that includes the required permissions

serviceusage.services.enable

Service Usage Admin
(roles/serviceusage.serviceUsageAdmin)

iam.serviceAccounts.create

Service Account Admin
(roles/iam.serviceAccountAdmin)

resourcemanager.projects.setIamPolicy

Project IAM Admin
(roles/resourcemanager.projectIamAdmin)
config.deployments.create
config.deployments.list
Cloud Infrastructure Manager Admin
(roles/config.admin)
iam.serviceAccount.actAs Service Account User
(roles/iam.serviceAccountUser)

About temporary service account permissions

If you start the deployment process through the console, Google creates a service account to deploy the solution on your behalf (and to delete the deployment later if you choose). This service account is assigned certain IAM permissions temporarily; that is, the permissions are revoked automatically after the solution deployment and deletion operations are completed. Google recommends that after you delete the deployment, you delete the service account, as described later in this guide.

View the roles assigned to the service account

These roles are listed here in case an administrator of your Google Cloud project or organization needs this information.

  • roles/artifactregistry.admin
  • roles/cloudsql.admin
  • roles/compute.networkAdmin
  • roles/iam.serviceAccountAdmin
  • roles/iam.serviceAccountUser
  • roles/redis.admin
  • roles/resourcemanager.projectIamAdmin
  • roles/run.admin
  • roles/servicenetworking.serviceAgent
  • roles/serviceusage.serviceUsageViewer
  • roles/vpcaccess.admin

Deploy the solution

To help you deploy this solution with minimal effort, a Terraform configuration is provided in GitHub. The Terraform configuration defines all the Google Cloud resources that are required for the solution.

You can deploy the solution by using one of the following methods:

  • Through the console: Use this method if you want to try the solution with the default configuration and see how it works. Cloud Build deploys all the resources that are required for the solution. When you no longer need the deployed solution, you can delete it through the console. Any resources that you create after you deploy the solution might need to be deleted separately.

    To use this deployment method, follow the instructions in Deploy through the console.

  • Using the Terraform CLI: Use this method if you want to customize the solution or if you want to automate the provisioning and management of the resources by using the infrastructure as code (IaC) approach. Download the Terraform configuration from GitHub, optionally customize the code as necessary, and then deploy the solution by using the Terraform CLI. After you deploy the solution, you can continue to use Terraform to manage the solution.

    To use this deployment method, follow the instructions in Deploy using the Terraform CLI.

Deploy through the console

Complete the following steps to deploy the preconfigured solution.

  1. In the Google Cloud Jump Start Solutions catalog, go to the Three-tier web app solution.

    Go to the Three-tier web app solution

  2. Review the information that's provided on the page, such as the estimated cost of the solution and the estimated deployment time.

  3. When you're ready to start deploying the solution, click Deploy.

    A step-by-step configuration pane is displayed.

  4. Complete the steps in the configuration pane.

    Note the name that you enter for the deployment. This name is required later when you delete the deployment.

    When you click Deploy, the Solution deployments page is displayed. The Status field on this page shows Deploying.

  5. Wait for the solution to be deployed.

    If the deployment fails, the Status field shows Failed. You can use the Cloud Build log to diagnose the errors. For more information, see Errors when deploying through the console.

    After the deployment is completed, the Status field changes to Deployed.

  6. To view and use the task-tracker app that this solution deploys, click Actions on the Solution deployments page, and then select View web app.

    The frontend web page of the task-tracker app is displayed in a new browser tab.

  7. To view the Google Cloud resources that are deployed and their configuration, take an interactive tour.

    Start the tour

When you no longer need the solution, you can delete the deployment to avoid continued billing for the Google Cloud resources. For more information, see Delete the deployment.

Deploy using the Terraform CLI

This section describes how you can customize the solution or automate the provisioning and management of the solution by using the Terraform CLI. Solutions that you deploy by using the Terraform CLI are not displayed in the Solution deployments page in the Google Cloud console.

Set up the Terraform client

You can run Terraform either in Cloud Shell or on your local host. This guide describes how to run Terraform in Cloud Shell, which has Terraform preinstalled and configured to authenticate with Google Cloud.

The Terraform code for this solution is available in a GitHub repository.

  1. Clone the GitHub repository to Cloud Shell.

    Open in Cloud Shell

    A prompt is displayed to confirm downloading the GitHub repository to Cloud Shell.

  2. Click Confirm.

    Cloud Shell is launched in a separate browser tab, and the Terraform code is downloaded to the $HOME/cloudshell_open directory of your Cloud Shell environment.

  3. In Cloud Shell, check whether the current working directory is $HOME/cloudshell_open/terraform-google-three-tier-web-app/. This is the directory that contains the Terraform configuration files for the solution. If you need to change to that directory, run the following command:

    cd $HOME/cloudshell_open/terraform-google-three-tier-web-app/
    
  4. Initialize Terraform by running the following command:

    terraform init
    

    Wait until you see the following message:

    Terraform has been successfully initialized!
    

Configure the Terraform variables

The Terraform code that you downloaded includes variables that you can use to customize the deployment based on your requirements. For example, you can specify the Google Cloud project and the region where you want the solution to be deployed.

  1. Make sure that the current working directory is $HOME/cloudshell_open/terraform-google-three-tier-web-app/. If it isn't, go to that directory.

  2. In the same directory, create a text file named terraform.tfvars.

  3. In the terraform.tfvars file, copy the following code snippet, and set values for the required variables.

    • Follow the instructions that are provided as comments in the code snippet.
    • This code snippet includes only the variables for which you must set values. The Terraform configuration includes other variables that have default values. To review all the variables and the default values, see the variables.tf file that's available in the $HOME/cloudshell_open/terraform-google-three-tier-web-app/ directory.
    • Make sure that each value that you set in the terraform.tfvars file matches the variable type as declared in the variables.tf file. For example, if the type that’s defined for a variable in the variables.tf file is bool, then you must specify true or false as the value of that variable in the terraform.tfvars file.
    # This is an example of the terraform.tfvars file.
    # The values in this file must match the variable types declared in variables.tf.
    # The values in this file override any defaults in variables.tf.
    
    # ID of the project in which you want to deploy the solution
    project_id = "PROJECT_ID"
    
    # Google Cloud region where you want to deploy the solution
    # Example: us-central1
    region = "REGION"
    
    # Google Cloud zone where you want to deploy the solution
    # Example: us-central1-a
    zone = "ZONE"
    

    For information about the values that you can assign to the required variables, see the following:

Validate and review the Terraform configuration

  1. Make sure that the current working directory is $HOME/cloudshell_open/terraform-google-three-tier-web-app/. If it isn't, go to that directory.

  2. Verify that the Terraform configuration has no errors:

    terraform validate
    

    If the command returns any errors, make the required corrections in the configuration and then run the terraform validate command again. Repeat this step until the command returns the following message:

    Success! The configuration is valid.
    
  3. Review the resources that are defined in the configuration:

    terraform plan
    
  4. If you didn't create the terraform.tfvars file as described earlier, Terraform prompts you to enter values for the variables that don't have default values. Enter the required values.

    The output of the terraform plan command is a list of the resources that Terraform provisions when you apply the configuration.

    If you want to make any changes, edit the configuration and then run the terraform validate and terraform plan commands again.

Provision the resources

When no further changes are necessary in the Terraform configuration, deploy the resources.

  1. Make sure that the current working directory is $HOME/cloudshell_open/terraform-google-three-tier-web-app/. If it isn't, go to that directory.

  2. Apply the Terraform configuration:

    terraform apply
    
  3. If you didn't create the terraform.tfvars file as described earlier, Terraform prompts you to enter values for the variables that don't have default values. Enter the required values.

    Terraform displays a list of the resources that will be created.

  4. When you're prompted to perform the actions, enter yes.

    Terraform displays messages showing the progress of the deployment.

    If the deployment can't be completed, Terraform displays the errors that caused the failure. Review the error messages and update the configuration to fix the errors. Then run the terraform apply command again. For help with troubleshooting Terraform errors, see Errors when deploying the solution using the Terraform CLI.

    After all the resources are created, Terraform displays the following message:

    Apply complete!
    

    The Terraform output also lists the frontend URL of the task-tracker app (endpoint) and the name of the Cloud SQL instance (sqlservername), as shown in the following example:

    endpoint = "https://three-tier-app-fe-pn4ngg7gnq-uc.a.run.app"
    sqlservername = "three-tier-app-db-75c2"
    
  5. To view and use the task-tracker app that the solution deployed, copy the endpoint URL from the previous step and open the URL in a browser.

    The frontend web page of the task-tracker app is displayed in a new browser tab.

  6. To view the Google Cloud resources that are deployed and their configuration, take an interactive tour.

    Start the tour

When you no longer need the solution, you can delete the deployment to avoid continued billing for the Google Cloud resources. For more information, see Delete the deployment.

Customize the solution

This section provides information that Terraform developers can use to modify the three-tier web app solution in order to meet their own technical and business requirements. The guidance in this section is relevant only if you deploy the solution by using the Terraform CLI.

The Resource configuration section (earlier in this guide) lists the preconfigured parameters of the Google Cloud resources that the three-tier web app solution provisions. You can customize the solution by changing some parameters in the main.tf file.

To customize the solution, complete the following steps in Cloud Shell:

  1. Make sure that the current working directory is $HOME/cloudshell_open/terraform-google-three-tier-web-app/. If it isn't, go to that directory.

  2. Open the main.tf file and make the required changes, as shown in the examples in the following table:

    Parameter Terraform code
    Cloud Run scaling Argument in the main.tf file: autoscaling.knative.dev/maxScale

    Code snippet

    resource "google_cloud_run_service" "api" {
    ...
      template {
      ...
        metadata {
          annotations = {
            "autoscaling.knative.dev/maxScale" = "COUNT"
            ...
          }
        }
      }
    }
    Redis version Argument in the main.tf file: redis_version

    Code snippet

    resource "google_redis_instance" "main" {
      ...
      redis_version = "VERSION"
      ...
    }

    Caution: The Google-provided Terraform configuration has been validated for Redis version 6.x. If you change the version, the deployed solution might not work as intended.

    Redis tier Argument in the main.tf file: tier

    Code snippet

    resource "google_redis_instance" "main" {
      ...
      tier = "TIER"
      ...
    }
    Redis memory Argument in the main.tf file: memory_size_gb

    Code snippet

    resource "google_redis_instance" "main" {
      ...
      memory_size_gb = SIZE
      ...
    }
    PostgreSQL or MySQL version Argument in the main.tf file: database_version

    Code snippet

    resource "google_sql_database_instance" "main" {
      ...
      database_version = "VERSION"
      ...
    ...
    }

    Caution: The Google-provided Terraform configuration has been validated for PostgreSQL version 14 and MySQL version 8.0. If you change the version, the deployed solution might not work as intended.

    Database machine type Argument in the main.tf file: settings.tier

    Code snippet

    resource "google_sql_database_instance" "main" {
      ...
      settings {
        tier = "MACHINE_TYPE"
        ...
      }
    ...
    }
    Database storage Argument in the main.tf file: settings.disk_size

    Code snippet

    resource "google_sql_database_instance" "main" {
      ...
      settings {
        ...
        ...
        disk_size = SIZE
        ...
      }
      ...
    }

  3. Validate and review the Terraform configuration.

  4. Provision the resources.

Design recommendations

This section provides recommendations for using the three-tier web app solution to develop an architecture that meets your requirements for security, reliability, cost, and performance.

To view the design recommendations for each area, click the appropriate tab.

Security

Design focus Recommendations
Data encryption
  • By default, Cloud Run encrypts data by using a Google-owned and Google-managed key. To protect your containers by using a key that you control, you can use customer-managed encryption keys. For more information, see Using customer-managed encryption keys .
  • By default, Memorystore uses Google-owned and Google-managed keys to encrypt data at rest. To encrypt data by using a key that you control, you can use customer-managed encryption keys. For more information, see About customer-managed encryption keys (CMEK).
  • You can enable encryption of in-transit data in Memorystore by using the Transport Layer Security (TLS) protocol. For more information, see About in-transit encryption.
Software supply-chain security To ensure that only authorized container images are deployed to the Cloud Run services, you can use Binary Authorization.
Access control
  • The Cloud Run service that runs the API layer allows ingress from any source. For enhanced security, you can restrict ingress to allow traffic from only internal sources. For more information, see Restricting ingress for Cloud Run.
  • To guard your application against unauthorized access, you can enable the AUTH feature in Memorystore, so that incoming client connections are authenticated. For more information, see About Redis AUTH.

Reliability

Design focus Recommendations
App scaling The Cloud Run services in the solution are configured to autoscale the container instances horizontally based on the request load. Review and adjust the autoscaling parameters based on your requirements. For more information, see About container instance autoscaling.
Request handling To improve the responsiveness of Cloud Run services that store client-specific state on container instances, you can use session affinity. Requests from the same client are routed to the same container instance, on a best-effort basis. For more information, see Setting session affinity (services).
Data durability To protect your data against loss, you can use automated backups of the Cloud SQL database. For more information, see About Cloud SQL backups.
Database high availability (HA)

The Cloud SQL database in the solution is deployed in a single zone. For HA, you can use a multi-zone configuration. For more information, see About high availability.

If database HA is a critical requirement, AlloyDB for PostgreSQL is an alternative Google Cloud service that you can consider.

Database reliability

The Cloud SQL instance in this solution uses the db-g1-small machine type, which uses a shared-core CPU. This machine type is designed to provide resources for a low-cost database that might be appropriate for test and development environments only. If you need production-grade reliability, consider using a machine type that provides more CPU and memory.

A Cloud SQL instance that uses the db-g1-small machine type is not included in the Cloud SQL service level agreement (SLA). For more information about configurations that are excluded from the SLA, see Operational guidelines.

Cache HA To help ensure HA for the in-memory cache layer in this solution, you can use the Standard Tier of Memorystore for Redis. The service creates read replicas for distributed read operations, and provides automatic failover. For more information, see Redis tier capabilities.

Cost

Design focus Recommendations
Resource efficiency

Cloud Run determines the number of requests that should be sent to a container instance based on CPU usage and memory usage. By increasing the maximum concurrency setting, you can reduce the number of container instances that Cloud Run needs to create, and therefore reduce cost. For more information, see Maximum concurrent requests per instance (services).

The Cloud Run services in this solution are configured to allocate CPUs only during request processing. When a Cloud Run service finishes handling a request, the container instance's access to CPUs is disabled. For information about the cost and performance effect of this configuration, see CPU allocation (services).

Resource usage

If your app needs to handle requests globally, consider deploying the Cloud Run services to multiple regions. Cross-region deployment can help to reduce the cost of cross-continent data transfer traffic. Google recommends a cross-region deployment if you decide to use a load balancer and CDN. For more information, see Serve traffic from multiple regions.

Performance

Design focus Recommendations
App startup time To reduce the performance effect of cold starts, you can configure the minimum number of Cloud Run container instances to a non-zero value. For more information, see General development tips for Cloud Run.
Frontend response time

If your app handles requests globally, to help ensure faster responses to client requests, consider deploying the Cloud Run services in multiple regions. You can use a global load balancer to route requests to the nearest region. For more information, see Serve traffic from multiple regions.

Multi-region deployments can also help to reduce the volume of cross-continent egress traffic, and therefore reduce the cost of operating the app.

Database performance

For performance-sensitive applications, you can improve performance of Cloud SQL by using a larger machine type and by increasing the storage capacity.

If database performance is a critical requirement, AlloyDB for PostgreSQL is an alternative Google Cloud service that you can consider.

Cache performance To improve the performance experience for users of your app, you can increase the capacity of the Memorystore for Redis instance. At larger capacities, the network throughput is higher. For more information, see Memory management best practices.

Note the following:

  • Before you make any design changes, assess the cost impact and consider potential trade-offs with other features. You can assess the cost impact of design changes by using the Google Cloud Pricing Calculator.
  • To implement design changes in the solution, you need expertise in Terraform coding and advanced knowledge of the Google Cloud services that are used in the solution.
  • If you modify the Google-provided Terraform configuration and if you then experience errors, create issues in GitHub. GitHub issues are reviewed on a best-effort basis and are not intended for general usage questions.
  • For more information about designing and setting up production-grade environments in Google Cloud, see Landing zone design in Google Cloud and Google Cloud setup checklist.

Delete the deployment

When you no longer need the solution deployment, to avoid continued billing for the resources that you created, delete the deployment.

Delete through the console

Use this procedure if you deployed the solution through the console.

  1. In the Google Cloud console, go to the Solution deployments page.

    Go to Solution deployments

  2. Select the project that contains the deployment that you want to delete.

  3. Locate the deployment that you want to delete.

  4. In the row for the deployment, click Actions and then select Delete.

    You might need to scroll to see Actions in the row.

  5. Enter the name of the deployment and then click Confirm.

    The Status field shows Deleting.

    If the deletion fails, see the troubleshooting guidance in Error when deleting a deployment.

When you no longer need the Google Cloud project that you used for the solution, you can delete the project. For more information, see Optional: Delete the project.

Delete using the Terraform CLI

Use this procedure if you deployed the solution by using the Terraform CLI.

  1. In Cloud Shell, make sure that the current working directory is $HOME/cloudshell_open/terraform-google-three-tier-web-app/. If it isn't, go to that directory.

  2. Remove the resources that were provisioned by Terraform:

    terraform destroy
    

    Terraform displays a list of the resources that will be destroyed.

  3. When you're prompted to perform the actions, enter yes.

    Terraform displays messages showing the progress. After all the resources are deleted, Terraform displays the following message:

    Destroy complete!
    

    If the deletion fails, see the troubleshooting guidance in Error when deleting a deployment.

When you no longer need the Google Cloud project that you used for the solution, you can delete the project. For more information, see Optional: Delete the project.

Optional: Delete the project

If you deployed the solution in a new Google Cloud project, and if you no longer need the project, then delete it by completing the following steps:

  1. In the Google Cloud console, go to the Manage resources page.

    Go to Manage resources

  2. In the project list, select the project that you want to delete, and then click Delete.
  3. At the prompt, type the project ID, and then click Shut down.

If you decide to retain the project, then delete the service account that was created for this solution, as described in the next section.

Optional: Delete the service account

If you deleted the project that you used for the solution, then skip this section.

As mentioned earlier in this guide, when you deployed the solution, a service account was created on your behalf. The service account was assigned certain IAM permissions temporarily; that is, the permissions were revoked automatically after the solution deployment and deletion operations were completed, but the service account isn't deleted. Google recommends that you delete this service account.

  • If you deployed the solution through the Google Cloud console, go to the Solution deployments page. (If you're already on that page, refresh the browser.) A process is triggered in the background to delete the service account. No further action is necessary.

  • If you deployed the solution by using the Terraform CLI, complete the following steps:

    1. In the Google Cloud console, go to the Service accounts page.

      Go to Service accounts

    2. Select the project that you used for the solution.

    3. Select the service account that you want to delete.

      The email ID of the service account that was created for the solution is in the following format:

      goog-sc-DEPLOYMENT_NAME-NNN@PROJECT_ID.iam.gserviceaccount.com
      

      The email ID contains the following values:

      • DEPLOYMENT_NAME: the name of the deployment.
      • NNN: a random 3-digit number.
      • PROJECT_ID: the ID of the project in which you deployed the solution.
    4. Click Delete.

Troubleshoot errors

The actions that you can take to diagnose and resolve errors depend on the deployment method and the complexity of the error.

Errors when deploying through the console

If the deployment fails when you use the console, do the following:

  1. Go to the Solution deployments page.

    If the deployment failed, the Status field shows Failed.

  2. View the details of the errors that caused the failure:

    1. In the row for the deployment, click Actions.

      You might need to scroll to see Actions in the row.

    2. Select View Cloud Build logs.

  3. Review the Cloud Build log and take appropriate action to resolve the issue that caused the failure.

Errors when deploying using the Terraform CLI

If the deployment fails when you use Terraform, the output of the terraform apply command includes error messages that you can review to diagnose the problem.

The examples in the following sections show deployment errors that you might encounter when you use Terraform.

API not enabled error

If you create a project and then immediately attempt to deploy the solution in the new project, the deployment might fail with an error like the following:

Error: Error creating Network: googleapi: Error 403: Compute Engine API has not
been used in project PROJECT_ID before or it is disabled. Enable it by visiting
https://console.developers.google.com/apis/api/compute.googleapis.com/overview?project=PROJECT_ID
then retry. If you enabled this API recently, wait a few minutes for the action
to propagate to our systems and retry.

If this error occurs, wait a few minutes and then run the terraform apply command again.

Cannot assign requested address error

When you run the terraform apply command, a cannot assign requested address error might occur, with a message like the following:

Error: Error creating service account:
 Post "https://iam.googleapis.com/v1/projects/PROJECT_ID/serviceAccounts:
 dial tcp [2001:db8:ffff:ffff::5f]:443:
 connect: cannot assign requested address

If this error occurs, run the terraform apply command again.

Configuration error

If any of the resource arguments have values that aren't supported, an error like the following occurs:

Error: Error creating Instance: googleapi: Error 400: Provided Redis version is
not supported: REDIS_5_X
│ com.google.apps.framework.request.StatusException:
  <eye3 title='INVALID_ARGUMENT'/>
  generic::INVALID_ARGUMENT: Provided Redis version is not supported: REDIS_5_X
Details:
│ [
│   {
│     "@type": "type.googleapis.com/google.rpc.BadRequest",
│     "fieldViolations": [
│       {
│         "description": "Invalid value: REDIS_5_X",
│         "field": "instance.redis_version"
│       }
│     ]
│   }
│ ]
│
│   with google_redis_instance.main,
│   on main.tf line 96, in resource "google_redis_instance" "main":
│   96: resource "google_redis_instance" "main" {

In this case, the intent was to use Redis version 5, but the value specified for the instance.redis_version argument (REDIS_5_X) in the main.tf file is not valid. The correct value is REDIS_5_0, as enumerated in the Memorystore REST API documentation.

Error when deleting a deployment

In certain cases, attempts to delete a deployment might fail:

  • After deploying a solution through the console, if you change any resource that was provisioned by the solution, and if you then try to delete the deployment, the deletion might fail. The Status field on the Solution deployments page shows Failed, and the Cloud Build log shows the cause of the error.
  • After deploying a solution by using the Terraform CLI, if you change any resource by using a non-Terraform interface (for example, the console), and if you then try to delete the deployment, the deletion might fail. The messages in the output of the terraform destroy command show the cause of the error.

Review the error logs and messages, identify and delete the resources that caused the error, and then try deleting the deployment again.

If a console-based deployment doesn't get deleted and if you can't diagnose the error by using the Cloud Build log, then you can delete the deployment by using the Terraform CLI, as described in the next section.

Delete a console-based deployment by using the Terraform CLI

This section describes how to delete a console-based deployment if errors occur when you try to delete it through the console. In this approach, you download the Terraform configuration for the deployment that you want to delete and then use the Terraform CLI to delete the deployment.

  1. Identify the region where the deployment's Terraform code, logs, and other data are stored. This region might be different from the region that you selected while deploying the solution.

    1. In the Google Cloud console, go to the Solution deployments page.

      Go to Solution deployments

    2. Select the project that contains the deployment that you want to delete.

    3. In the list of deployments, identify the row for the deployment that you want to delete.

    4. Click View all row content.

    5. In the Location column, note the second location, as highlighted in the following example:

      Location of the deployment code, logs and other artifacts.

  2. In the Google Cloud console, activate Cloud Shell.

    Activate Cloud Shell

    At the bottom of the Google Cloud console, a Cloud Shell session starts and displays a command-line prompt. Cloud Shell is a shell environment with the Google Cloud CLI already installed and with values already set for your current project. It can take a few seconds for the session to initialize.

  3. Create environment variables for the project ID, region, and name of the deployment that you want to delete:

    export REGION="REGION"
    export PROJECT_ID="PROJECT_ID"
    export DEPLOYMENT_NAME="DEPLOYMENT_NAME"
    

    In these commands, replace the following:

    • REGION: the location that you noted earlier in this procedure.
    • PROJECT_ID: the ID of the project where you deployed the solution.
    • DEPLOYMENT_NAME: the name of the deployment that you want to delete.
  4. Get the ID of the latest revision of the deployment that you want to delete:

    export REVISION_ID=$(curl \
        -H "Authorization: Bearer $(gcloud auth print-access-token)" \
        -H "Content-Type: application/json" \
        "https://config.googleapis.com/v1alpha2/projects/${PROJECT_ID}/locations/${REGION}/deployments/${DEPLOYMENT_NAME}" \
        | jq .latestRevision -r)
        echo $REVISION_ID
    

    The output is similar to the following:

    projects/PROJECT_ID/locations/REGION/deployments/DEPLOYMENT_NAME/revisions/r-0
    
  5. Get the Cloud Storage location of the Terraform configuration for the deployment:

    export CONTENT_PATH=$(curl \
        -H "Authorization: Bearer $(gcloud auth print-access-token)" \
        -H "Content-Type: application/json" \
        "https://config.googleapis.com/v1alpha2/${REVISION_ID}" \
        | jq .applyResults.content -r)
        echo $CONTENT_PATH
    

    The following is an example of the output of this command:

    gs://PROJECT_ID-REGION-blueprint-config/DEPLOYMENT_NAME/r-0/apply_results/content
    
  6. Download the Terraform configuration from Cloud Storage to Cloud Shell:

    gcloud storage cp $CONTENT_PATH $HOME --recursive
    cd $HOME/content/
    

    Wait until the Operation completed message is displayed, as shown in the following example:

    Operation completed over 45 objects/268.5 KiB
    
  7. Initialize Terraform:

    terraform init
    

    Wait until you see the following message:

    Terraform has been successfully initialized!
    
  8. Remove the deployed resources:

    terraform destroy
    

    Terraform displays a list of the resources that will be destroyed.

    If any warnings about undeclared variables are displayed, ignore the warnings.

  9. When you're prompted to perform the actions, enter yes.

    Terraform displays messages showing the progress. After all the resources are deleted, Terraform displays the following message:

    Destroy complete!
    
  10. Delete the deployment artifact:

    curl -X DELETE \
        -H "Authorization: Bearer $(gcloud auth print-access-token)" \
        -H "Content-Type: application/json" \
        "https://config.googleapis.com/v1alpha2/projects/${PROJECT_ID}/locations/${REGION}/deployments/${DEPLOYMENT_NAME}?force=true&delete_policy=abandon"
    
  11. Wait a few seconds and then verify that the deployment artifact was deleted:

    curl -H "Authorization: Bearer $(gcloud auth print-access-token)" \
        -H "Content-Type: application/json" \
        "https://config.googleapis.com/v1alpha2/projects/${PROJECT_ID}/locations/${REGION}/deployments/${DEPLOYMENT_NAME}" \
        | jq .error.message
    

    If the output shows null, wait a few seconds and then run the command again.

    After the deployment artifact is deleted, a message as shown in the following example is displayed:

    Resource 'projects/PROJECT_ID/locations/REGION/deployments/DEPLOYMENT_NAME' was not found
    

Submit feedback

Jump Start Solutions are for informational purposes only and are not officially supported products. Google may change or remove solutions without notice.

To troubleshoot errors, review the Cloud Build logs and the Terraform output.

To submit feedback, do the following:

  • For documentation, in-console tutorials, or the solution, use the Send Feedback button on the page.
  • For unmodified Terraform code, create issues in the GitHub repository. GitHub issues are reviewed on a best-effort basis and are not intended for general usage questions.

What's next

Review the following documentation to learn about architectural and operational best practices for the products that are used in this solution: