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
Before you can run this quickstart, you must:
- Sign up and enable Deployment Manager.
- Enable Google Compute Engine if you haven’t already.
- Find your Google Developers Console project ID.To determine your project ID, do the following:
- Go to the Google Developers Console.
- Find your project in the table on the main landing page.
- The project ID appears in the second column of the table.
- 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:
- Go to the Google Developers Console.
- Select a project, or create a new one.
- 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.
- In the sidebar on the left, select Credentials.
- 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.
- 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
-
Collapse | Copy Code
deployment_service.templates().list(projectId=<var><project-id></var>)
- Listing deployments
-
Collapse | Copy Code
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
-
Collapse | Copy Code
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:Collapse | Copy Codetemplate = { "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
-
Collapse | Copy Code
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:
Collapse | Copy Codedeployment = { "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
-
Collapse | Copy Code
deployment_service.deployments().delete(projectId=<var><project-id></var>, deploymentName=<var><deployment-name></var>, region=<var><region></var>)
- Deleting a template
-
Collapse | Copy Code
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.