Click here to Skip to main content
13,251,760 members (83,063 online)
Click here to Skip to main content
Add your own
alternative version

Tagged as

Stats

6.1K views
4 bookmarked
Posted 2 Dec 2014

Python Quickstart: Creating a template and deployment

, 2 Dec 2014
Rate this:
Please Sign up or sign in to vote.
This document discusses how to use the Python Client Library as an example of using any of the Google Client Libraries to write against the Deployment Manager API.

Editorial Note

This article is for our sponsors at CodeProject. These articles are intended to provide you with information on products and services that we consider useful and of value to developers

Introduction

Although the Google Cloud SDK command-line tool is the easiest and quickest way to get started using Deployment Manager, you can also write against the API directly or using the client libraries. This document discusses how to use the Python Client Library as an example of using any of the Google Client Libraries to write against the Deployment Manager API.

At the end of this quickstart, you should know how to:

  • Use a local discovery document
  • Authorize to the API using the OAuth 2.0 client library (included in the Python client library)
  • Create your own template, and deploy resources

Contents

Prerequisites

Before you can run this quickstart, you must:

  1. Sign up and enable Deployment Manager.
  2. Enable Google Compute Engine if you haven't already.
  3. Find your Google Developers Console project ID.

    To determine your project ID, do the following:

    1. Go to the Google Developers Console.
    2. Find your project in the table on the main landing page.
    3. The project ID appears in the second column of the table.
  4. Download the google-api-python-client library.

Authorizing the service

This sample uses OAuth 2.0 authorization. You will need to create a client ID and client secret, and use both with the oauth2client library. By default, the oauth2 library is included in the google-api-python-client library, which you should have downloaded in the Prerequisites section. For this sample, you will need to create a client ID and secret for an Installed application.

To find your project's client ID and client secret, do the following:

  1. Go to the Google Developers Console.
  2. Select a project, or create a new one.
  3. In the sidebar on the left, expand APIs & auth. Next, click APIs. In the list of APIs, make sure the status is ON for the Google Cloud Deployment Manager API.
  4. In the sidebar on the left, select Credentials.
  5. If you haven't done so already, create your project's OAuth 2.0 credentials by clicking Create new Client ID, and providing the information needed to create the credentials.
  6. Look for the Client ID and Client secret in the table associated with each of your credentials.

Note that not all types of credentials use both a client ID and client secret and won't be listed in the table if they are not used.

Once you have created your client ID and secret for an Installed application, save it locally by clicking Download JSON and naming the file client_secrets.json. Next, create a file called helloworld.py in the same directory as the client_secrets.json file and provide the following code:

#!/usr/bin/python

import os
import logging
import sys
import argparse
import httplib2
import json
from oauth2client.client import flow_from_clientsecrets
from oauth2client import tools
from oauth2client.file import Storage
from oauth2client.tools import run_flow
from apiclient.discovery import build

MANAGE_SCOPE = "https://www.googleapis.com/auth/ndev.cloudman"
CLIENT_SECRETS = 'client_secrets.json'
OAUTH2_STORAGE = 'oauth2.dat'

def main(argv):
  logging.basicConfig(level=logging.INFO)

  parser = argparse.ArgumentParser(
    description=__doc__,
    formatter_class=argparse.RawDescriptionHelpFormatter,
    parents=[tools.argparser])

  # Parse the command-line flags.
  flags = parser.parse_args(argv[1:])

  # Perform OAuth 2.0 authorization.
  flow = flow_from_clientsecrets(CLIENT_SECRETS, scope=MANAGE_SCOPE)
  storage = Storage(OAUTH2_STORAGE)
  credentials = storage.get()

  if credentials is None or credentials.invalid:
    credentials = run_flow(flow, storage, flags)
  http = httplib2.Http()
  auth_http = credentials.authorize(http=http)

if __name__ == "__main__":
    main(sys.argv)

If you run the program at this point, you should be prompted to grant access to your Deployment Manager. Once you've run through that process in your browser, your application should be authorized to access the Deployment Manager API.

Building and initializing the API

During the trusted tester phase, you need to build and initialize a version of the Deployment Manager API using a local discovery document. To do so, include the following boldfaced lines in your application:

#!/usr/bin/python

import os
import logging
import sys
import argparse
import httplib2
import json
from oauth2client.client import flow_from_clientsecrets
from oauth2client import tools
from oauth2client.file import Storage
from oauth2client.tools import run_flow
from apiclient.discovery import build

MANAGE_SCOPE = "https://www.googleapis.com/auth/ndev.cloudman"
CLIENT_SECRETS = 'client_secrets.json'
OAUTH2_STORAGE = 'oauth2.dat'
API_VERSION = "v1beta2"

def main(argv):
  logging.basicConfig(level=logging.INFO)

  parser = argparse.ArgumentParser(
    description=__doc__,
    formatter_class=argparse.RawDescriptionHelpFormatter,
    parents=[tools.argparser])

  # Parse the command-line flags.
  flags = parser.parse_args(argv[1:])

  # Perform OAuth 2.0 authorization.
  flow = flow_from_clientsecrets(CLIENT_SECRETS, scope=MANAGE_SCOPE)
  storage = Storage(OAUTH2_STORAGE)
  credentials = storage.get()

  if credentials is None or credentials.invalid:
    credentials = run_flow(flow, storage, flags)
  http = httplib2.Http()
  auth_http = credentials.authorize(http=http)

  # Build the service
  deployment_service = build("manager", API_VERSION)

if __name__ == "__main__":
    main(sys.argv)

Great, now you can start making requests to the API!

Listing resources

To list Deployment Manager resources, use one of the following methods:

Listing templates
deployment_service.templates().list(projectId=<var><project-id></var>)
Listing deployments
deployment_service.deployments().list(projectId=<var><project-id></var>, region=<var>region</var>)

For this example, we will query the API for a list of services. Add the following lines to your application:

#!/usr/bin/python

import os
import logging
import sys
import argparse
import httplib2
import json
from oauth2client.client import flow_from_clientsecrets
from oauth2client import tools
from oauth2client.file import Storage
from oauth2client.tools import run_flow
from apiclient.discovery import build

MANAGE_SCOPE = "https://www.googleapis.com/auth/ndev.cloudman"
CLIENT_SECRETS = 'client_secrets.json'
OAUTH2_STORAGE = 'oauth2.dat'
API_VERSION = "v1beta2"
PROJECT_ID = "your-project-id"

def main(argv):
  logging.basicConfig(level=logging.INFO)

  parser = argparse.ArgumentParser(
    description=__doc__,
    formatter_class=argparse.RawDescriptionHelpFormatter,
    parents=[tools.argparser])

  # Parse the command-line flags.
  flags = parser.parse_args(argv[1:])

  # Perform OAuth 2.0 authorization.
  flow = flow_from_clientsecrets(CLIENT_SECRETS, scope=MANAGE_SCOPE)
  storage = Storage(OAUTH2_STORAGE)
  credentials = storage.get()

  if credentials is None or credentials.invalid:
    credentials = run_flow(flow, storage, flags)
  http = httplib2.Http()
  auth_http = credentials.authorize(http=http)

  # Build the service
  deployment_service = build("manager", API_VERSION)

  # List templates
  listTemplates(auth_http, deployment_service)

def listTemplates(auth_http, deployment_service):
  request = deployment_service.templates().list(projectId=PROJECT_ID)
  response = request.execute(auth_http)

  _printResults(response)

def _printResults(response):

  print json.dumps(response, sort_keys=True, indent=4, separators=(',', ': '))

if __name__ == "__main__":
    main(sys.argv)

Run the application to see the results of your request. On the command line, run:

python helloworld.py

If you have services to list, your result should look similar to the following:

{
  "resources": [
    {
      "name": "myservice"
    },
    {
      "name": "myotherservice"
    }
  ]
}

If you don't have any resources, you should receive an empty resource list in response.

Adding resources

To add a resource, use one of the following methods:

Adding a template
deployment_service.templates().insert(projectId=<var><project-id></var>, body=<var>template</var>)

template would contain the configuration settings of the template. For example, template might look like the following:

template = {
  "name": TEMPLATE_NAME,
  "modules": {
    "virtualMachineModule": {
      "type": "REPLICA_POOL",
      "replicaPoolModule": {
        "numReplicas": "4",
        "replicaPoolParams": {
          "v1beta1": {
          "machineType": "n1-standard-1",
          "zone": ZONE,
          "disksToCreate": [{
            "boot": "true",
            "autoDelete": "true",
            "initializeParams": {
              "diskSizeGB": "10",
              "sourceImage": IMAGE_URI
            }
           }],
          "networkInterfaces": [{
            "network" : "default",
            "accessConfigs": [{
              "name": "External NAT",
              "type": "ONE_TO_ONE_NAT"
            }]
          }]
       }
     }
    }
   }
  }
Adding a Deployment
deployment_service.deployments().insert(projectId=<project-id>, body=deployment, region=<region>)

The body of the request must contain the name of the deployment you want to create and the template you want to use:

 deployment = {
  "name" : "my-deployment-name",
  "templateName" : "my-template-name"
}

In our example, we are going to insert a template and a deployment.

#!/usr/bin/python

import os
import logging
import sys
import argparse
import httplib2
import json
from oauth2client.client import flow_from_clientsecrets
from oauth2client import tools
from oauth2client.file import Storage
from oauth2client.tools import run_flow
from apiclient.discovery import build

MANAGE_SCOPE = "https://www.googleapis.com/auth/ndev.cloudman"
CLIENT_SECRETS = 'client_secrets.json'
OAUTH2_STORAGE = 'oauth2.dat'
API_VERSION = "v1beta2"
PROJECT_ID = "your-project-id"
TEMPLATE_NAME = "mynewtemplate"
DEPLOYMENT_NAME = "sampledeployment"
REGION = "us-central1"
ZONE = REGION + "-a"
IMAGE_URI = "https://www.googleapis.com/compute/v1/projects/debian-cloud/global/images/debian-7-wheezy-v20141120"

def main(argv):
  logging.basicConfig(level=logging.INFO)

  parser = argparse.ArgumentParser(
    description=__doc__,
    formatter_class=argparse.RawDescriptionHelpFormatter,
    parents=[tools.argparser])

  # Parse the command-line flags.
  flags = parser.parse_args(argv[1:])

  # Perform OAuth 2.0 authorization.
  flow = flow_from_clientsecrets(CLIENT_SECRETS, scope=MANAGE_SCOPE)
  storage = Storage(OAUTH2_STORAGE)
  credentials = storage.get()

  if credentials is None or credentials.invalid:
    credentials = run_flow(flow, storage, flags)
  http = httplib2.Http()
  auth_http = credentials.authorize(http=http)

  # Build the service
  deployment_service = build("manager", API_VERSION)

'''
  # List templates
  listTemplates(auth_http, deployment_service)
'''
  # Create a template
  createTemplate(auth_http, deployment_service)

  # Create a deployment
  addDeployment(auth_http, deployment_service)

def createTemplate(auth_http, deployment_service):
  template = {
    "name": TEMPLATE_NAME,
    "modules": {
      "virtualMachineModule": {
        "type": "REPLICA_POOL",
        "replicaPoolModule": {
          "numReplicas": "4",
          "replicaPoolParams": {
            "v1beta1": {
            "machineType": "n1-standard-1",
            "zone": ZONE,
            "disksToCreate": [{
              "boot": "true",
              "autoDelete": "true",
              "initializeParams": {
                "diskSizeGB": "10",
                "sourceImage": IMAGE_URI
              }
             }],
            "networkInterfaces": [{
              "network" : "default",
              "accessConfigs": [{
                "name": "External NAT",
                "type": "ONE_TO_ONE_NAT"
              }]
            }]
         }
       }
      }
     }
    }

  request = deployment_service.templates().insert(projectId=PROJECT_ID, body=template)
  response = request.execute(auth_http)

  _printResults(response)

def addDeployment(auth_http, deployment_service):
  body = {
    "name" : DEPLOYMENT_NAME,
    "templateName" : TEMPLATE_NAME
  }

  request = deployment_service.deployments().insert(projectId=PROJECT_ID, body=body, region=REGION)
  response = request.execute(auth_http)

  request = deployment_service.deployments().get(projectId=PROJECT_ID, deploymentName=DEPLOYMENT_NAME)
  response = request.execute(auth_http)

  _printResults(response)

def listTemplates(auth_http, deployment_service):
  request = deployment_service.templates().list(projectId=PROJECT_ID)
  response = request.execute(auth_http)

  _printResults(response)

def _printResults(response):

  print json.dumps(response, sort_keys=True, indent=4, separators=(',', ': '))

if __name__ == "__main__":
    main(sys.argv)

Deleting resources

Use the following methods to delete a resource:

Deleting a deployment
deployment_service.deployments().delete(projectId=<var><project-id></var>, deploymentName=<var><deployment-name></var>, region=<var><region></var>)
Deleting a template
deployment_service.templates().delete(projectName=<var><project-id></var>, templateName=<var><template-name></var>)

In our example, we will delete the deployment we just created. Add the following lines to your file:

#!/usr/bin/python

import os
import logging
import sys
import argparse
import httplib2
import json
from oauth2client.client import flow_from_clientsecrets
from oauth2client import tools
from oauth2client.file import Storage
from oauth2client.tools import run_flow
from apiclient.discovery import build

MANAGE_SCOPE = "https://www.googleapis.com/auth/ndev.cloudman"
CLIENT_SECRETS = 'client_secrets.json'
OAUTH2_STORAGE = 'oauth2.dat'
API_VERSION = "v1beta2"
PROJECT_ID = "your-project-id"
TEMPLATE_NAME = "mynewtemplate"
DEPLOYMENT_NAME = "sampledeployment"
REGION = "us-central1"
ZONE = REGION + "-a"
IMAGE_URI = "https://www.googleapis.com/compute/v1/projects/debian-cloud/global/images/debian-7-wheezy-v20141120"

def main(argv):
  logging.basicConfig(level=logging.INFO)

  parser = argparse.ArgumentParser(
    description=__doc__,
    formatter_class=argparse.RawDescriptionHelpFormatter,
    parents=[tools.argparser])

  # Parse the command-line flags.
  flags = parser.parse_args(argv[1:])

  # Perform OAuth 2.0 authorization.
  flow = flow_from_clientsecrets(CLIENT_SECRETS, scope=MANAGE_SCOPE)
  storage = Storage(OAUTH2_STORAGE)
  credentials = storage.get()

  if credentials is None or credentials.invalid:
    credentials = run_flow(flow, storage, flags)
  http = httplib2.Http()
  auth_http = credentials.authorize(http=http)

  # Build the service
  deployment_service = build("manager", API_VERSION)

'''
  # List templates
  listTemplates(auth_http, deployment_service)

  # Create a template
  createTemplate(auth_http, deployment_service)

  # Create a deployment
  addDeployment(auth_http, deployment_service)
'''

   # Delete a deployment
  deleteDeployment(auth_http, deployment_service)

def deleteDeployment(auth_http, deployment_service):
  request = deployment_service.deployments().delete(projectId=PROJECT_ID, deploymentName=DEPLOYMENT_NAME, region=REGION)
  response = request.execute(auth_http)

  _printResults(response)

  # Create a deployment
  addDeployment(auth_http, deployment_service)

def createTemplate(auth_http, deployment_service):
  template = {
    "name": TEMPLATE_NAME,
    "modules": {
      "virtualMachineModule": {
        "type": "REPLICA_POOL",
        "replicaPoolModule": {
          "numReplicas": "4",
          "replicaPoolParams": {
            "v1beta1": {
            "machineType": "n1-standard-1",
            "zone": ZONE,
            "disksToCreate": [{
              "boot": "true",
              "autoDelete": "true",
              "initializeParams": {
                "diskSizeGB": "10",
                "sourceImage": IMAGE_URI
              }
             }],
            "networkInterfaces": [{
              "network" : "default",
              "accessConfigs": [{
                "name": "External NAT",
                "type": "ONE_TO_ONE_NAT"
              }]
            }]
         }
       }
      }
     }
    }

  request = deployment_service.templates().insert(projectId=PROJECT_ID, body=template)
  response = request.execute(auth_http)

  _printResults(response)

def addDeployment(auth_http, deployment_service):
  body = {
    "name" : DEPLOYMENT_NAME,
    "templateName" : TEMPLATE_NAME
  }

  request = deployment_service.deployments().insert(projectId=PROJECT_ID, body=body, region=REGION)
  response = request.execute(auth_http)

  request = deployment_service.deployments().get(projectId=PROJECT_ID, deploymentName=DEPLOYMENT_NAME)
  response = request.execute(auth_http)

  _printResults(response)

def listTemplates(auth_http, deployment_service):
  request = deployment_service.templates().list(projectId=PROJECT_ID)
  response = request.execute(auth_http)

  _printResults(response)

def _printResults(response):

  print json.dumps(response, sort_keys=True, indent=4, separators=(',', ': '))

if __name__ == "__main__":
    main(sys.argv)

Next steps

This quickstart provided a very basic example of how to use the Deployment Manager API. For a full list of API methods, review the reference documentation. You can also review the available client libraries that you can use.

Except as otherwise noted, the code samples of this page is licensed under the Apache 2.0 License.

License

This article, along with any associated source code and files, is licensed under The Creative Commons Attribution 3.0 Unported License

Share

About the Author

Google Cloud Platform
United States United States
No Biography provided

You may also be interested in...

Pro
Pro

Comments and Discussions

 
-- There are no messages in this forum --
Permalink | Advertise | Privacy | Terms of Use | Mobile
Web03 | 2.8.171114.1 | Last Updated 2 Dec 2014
Article Copyright 2014 by Google Cloud Platform
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid