Deploying the Python Bookshelf app using Cloud Deployment Manager

This tutorial shows how to deploy the Python Bookshelf sample appusingCloud Deployment Manager.

Deployment Manager lets you create the necessaryGoogle Cloudresources for a deployment in a single step, through a declarative, repeatable process.With Deployment Manager, you can update your deployments, trackyour modifications over time, create templates usingJinja or Python, and parameterize your templates, so that similar deployments share atemplate.

Objectives

  • Clone and configure the Bookshelf sample app.
  • Create Deployment Manager configurations and templates.
  • Create Deployment Manager deployments.
  • Deploy the Bookshelf sample app using Deployment Manager.

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.

New Google Cloud users might be eligible for afree trial.

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

  1. Sign in to your Google Cloud account. If you're new to Google Cloud, create an account to evaluate how our products perform in real-world scenarios. New customers also get $300 in free credits to run, test, and deploy workloads.
  2. In the Google Cloud console, on the project selector page, select or create a Google Cloud 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.create permission.Learn how to grant roles.
    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.

    Go to project selector

  3. Verify that billing is enabled for your Google Cloud project.

  4. Enable the Datastore API, Cloud Storage API, Pub/Sub API APIs.

    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.

    Enable the APIs

  5. Install the Google Cloud CLI.

  6. If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.

  7. Toinitialize the gcloud CLI, run the following command:

    gcloudinit
  8. In the Google Cloud console, on the project selector page, select or create a Google Cloud 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.create permission.Learn how to grant roles.
    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.

    Go to project selector

  9. Verify that billing is enabled for your Google Cloud project.

  10. Enable the Datastore API, Cloud Storage API, Pub/Sub API APIs.

    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.

    Enable the APIs

  11. Install the Google Cloud CLI.

  12. If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.

  13. Toinitialize the gcloud CLI, run the following command:

    gcloudinit
  14. Install Python,pip, andvirtualenv on your system. For instructions, seeSetting up a Python development environmentfor Google Cloud.

Creating a Cloud Storage bucket

The following instructions detail how to create a Cloud Storage bucket.Buckets are the basic containers that hold your data in Cloud Storage.

Note: You can chooseany name for your Cloud Storage bucket. It's a good practice to give your bucketthe same name as your project ID. Bucket names must be unique across all ofGoogle Cloud, so it's possible that you can't use yourproject ID as the bucket name.
  1. In your terminal window, create a Cloud Storage bucket, whereYOUR_BUCKET_NAME represents the name of your bucket:

    gcloudstoragebucketscreategs://YOUR_BUCKET_NAME
  2. To view uploaded images in the Bookshelf app, set the bucket's Identity and Access Managementpolicy to grant thelegacyObjectReader role toallUsers:

    gcloudstoragebucketsadd-iam-policy-bindinggs://YOUR_BUCKET_NAME--member=allUsers--role=roles/storage.legacyObjectReader

Cloning the sample app

The sample app is available on GitHub atGoogleCloudPlatform/getting-started-python.

  1. Clone the repository:

    gitclonehttps://github.com/GoogleCloudPlatform/getting-started-python.git-bsteps
  2. Go to the sample directory:

    cdgetting-started-python/7-gce

Configuring the app

  1. Openconfig.py for editing.

    • Set the value ofPROJECT_ID to your project ID.

    • Set the valueCLOUD_STORAGE_BUCKET to the name of your Cloud Storagebucket.

  2. Save and closeconfig.py.

Running the app on your local computer

  1. Create an isolated Python environment, and install dependencies:

    Linux/macOS

    virtualenv-ppython3envsourceenv/bin/activatepipinstall-rrequirements.txt

    Windows

    virtualenv-ppython3envenv\scripts\activatepipinstall-rrequirements.txt

  2. Run the application:

    pythonmain.py
  3. In your browser, enter the following address:

    http://localhost:8080

To stop the local web server, pressControl+C. If you want to exitthe virtual environment, enterdeactivate.

Deploying the sample app

Push your code to a repository

You can get your code onto a running Compute Engine instance in severalways. One way is to useCloud Source Repositories.Every project includes a Git repository that is available toCompute Engine instances. Your instances then pull the latest version ofyour app's code during startup. Using a Git repository is convenient becauseupdating your app doesn't require configuring new images or instances; justrestart an existing instance or create one.

  1. For your first time using Git, usegit config --global to set upyour identity.

  2. In your Google Cloud console, create a repository:

    Create repository

  3. Then push your app code to your project's repository where[YOUR_PROJECT_ID] is your project ID and[YOUR_REPO] is the nameof your repository:

    gitcommit-am"Updating configuration"gitconfigcredential.helpergcloud.shgitremoteaddcloudhttps://source.developers.google.com/p/[YOUR_PROJECT_ID]/r/[YOUR_REPO]gitpushcloudmaster

Create the deployment

After your configuration is committed and your code is uploaded toCloud Source Repositories, you can use the Deployment Managerto create the deployment:

  1. Go to thedeployment_manager directory:

    cdgetting-started-python/7-gce/gce/deployment_manager
  2. Create the deployment:

    gclouddeployment-managerdeploymentscreatemy-deployment--configconfig.yaml
  3. View a list of all the deployments:

    gclouddeployment-managerdeploymentslist
  4. Get a description of the deployment and the resources it created:

    gclouddeployment-managerdeploymentsdescribemy-deployment

View your app

After you create the forwarding rule, it can take several minutes for yourconfiguration to propagate and for traffic to be routed to your instances.

  1. To check the progress:

    gcloudcomputebackend-servicesget-healthbookshelf-my-deployment-frontend--global
  2. When at least one of your instances reportsHEALTHY, get the forwarding IPaddress for the load balancer:

    gcloudcomputeforwarding-ruleslist--global

    Your forwarding-rules IP address is in theIP_ADDRESS column.

  3. In your browser, enter the IP address from the list.

    Your app is now running on Google Cloud.

Understanding the code

Configure the deployment

You can see how the deployment is configured inconfig.yaml:

imports:-name:bookshelf.jinjapath:./bookshelf.jinjaresources:-name:bookshelftype:bookshelf.jinjaproperties:zone:us-central1-fmachine-type:n1-standard-1machine-image:https://www.googleapis.com/compute/v1/projects/debian-cloud/global/images/family/debian-9min-instances:1max-instances:10target-utilization:0.6scopes:-https://www.googleapis.com/auth/cloud-platform

The configuration file imports the template file as a resource and uses it todefine a resource namedbookshelf. The template takes several properties asparameters. For more information about creatingDeployment Manager configuration files, seeCreating a configuration.

Configure the deployment template's schema

Look at the schema filebookshelf.jinja.schema, which defines anddocuments the parameters that the deployment is expected to provide in itsconfiguration file. For more information about configuration schemas, seeUsing schemas.

info:title:BookshelfGCEDeployauthor:GoogleInc.description:CreatesaGCEDeploymentimports:-name:startup-scriptpath:../startup-script.shrequired:-zone-machine-type-min-instances-max-instances-scopesproperties:zone:description:Zonetocreatetheresourcesin.type:stringmachine-type:description:Typeofmachinetousetype:stringmachine-image:description:TheOSimagetouseonthemachinestype:stringmin-instances:description:TheminimumnumberofVMstheautoscalerwillcreatetype:integermax-instances:description:ThemaximumnumberofVMstheautoscalerwillcreatetype:integertarget-utilization:description:ThetargetCPUusagefortheautoscalertobaseitsscalingontype:numberscopes:description:AlistofscopestocreatetheVMwithtype:arrayminItems:1items:type:string

Configure the deployment template

The template defines several resources needed to create an autoscaled, load-balanced, managed instance group. For a full description of the resourcescreated, see the comments in the template and review theBookshelf on Compute Engine tutorial.

Keep in mind that Deployment Manager provides a way todeclaratively define resources, but most of the configuration for a givenresource is defined by its API. For example, most of the configuration optionsfor the instance template resource are found in theinstance template resource definition in the reference documentation for theCompute Engine API.

The template is written using theJinja templating language. When writing Deployment Manager templates,you can either use Jinja or Python. Jinja has the advantage of being moredeclarative, which can be more readable and easier to understand than Python.For some complex deployments, the full expressiveness of Python might makethings simpler. In this case, Jinja is sufficient to create the necessaryresources.

In a template, certain environment variables are automatically set, and you canaccess these variables by using theenv dictionary. In this case, the name ofthe deployment is referenced as a name to be reused when assigning names to theresources that are created. For more information about available environmentvariables, seeUsing environment variables in the Deployment Manager documentation:

{%setNAME="bookshelf-"+env["deployment"]%}{%setSERVICE="bookshelf-"+env["deployment"]+"-frontend"%}

The template uses the same startup script that is used in theCompute Engine tutorial.The script's content is inserted into the template, and theJinja indent directive indents the content correctly:

value:|{{imports['startup-script']|indent(14, true)}}

In a Deployment Manager Jinja template, you can also refer toresources created elsewhere in the template. In the following example, thebackend service uses the reference of the managed instance group to obtain theinstance group it should point to:

-group:$(ref.{{ NAME }}-frontend-group.instanceGroup)zone: {{ properties['zone'] }}

Properties specified inconfig.yaml can be used in the template:

minNumReplicas: {{ properties['min-instances'] }}maxNumReplicas: {{ properties['max-instances'] }}loadBalancingUtilization:utilizationTarget: {{ properties['target-utilization'] }}

Clean up

To avoid incurring charges to your Google Cloud account for the resources used in this tutorial, either delete the project that contains the resources, or keep the project and delete the individual resources.

Delete the project

The easiest way to eliminate billing is to delete the project that you created for the tutorial.

To delete the project:

    Caution: Deleting a project has the following effects:
    • Everything in the project is deleted. If you used an existing project for the tasks in this document, when you delete it, you also delete any other work you've done in the project.
    • Custom project IDs are lost. When you created this project, you might have created a custom project ID that you want to use in the future. To preserve the URLs that use the project ID, such as anappspot.com URL, delete selected resources inside the project instead of deleting the whole project.

    If you plan to explore multiple architectures, tutorials, or quickstarts, reusing projects can help you avoid exceeding project quota limits.

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

    Go to Manage resources

  2. In the project list, select the project that you want to delete, and then clickDelete.
  3. In the dialog, type the project ID, and then clickShut down to delete the project.

Delete your deployment

To delete your deployment, enter the following command. This command deletes theload balancer and any Compute Engine instances that are associated withyour deployment:

gclouddeployment-managerdeploymentsdeletemy-deployment

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-17 UTC.