Python 快速入门:创建模板和部署





3.00/5 (3投票s)
本文档讨论如何使用 Python 客户端库,作为使用任何 Google 客户端库编写 Deployment Manager API 的示例。
引言
尽管 Google Cloud SDK 命令行工具是开始使用 Deployment Manager 的最简单、最快捷的方法,但您也可以直接或使用客户端库编写 API。本文档讨论如何使用 Python 客户端库,作为使用任何 Google 客户端库编写 Deployment Manager API 的示例。
在本快速入门结束时,您应该知道如何
- 使用本地发现文档
- 使用 OAuth 2.0 客户端库(包含在 Python 客户端库中)授权 API
- 创建您自己的模板,并部署资源
目录
必备组件
在运行此快速入门之前,您必须
- 注册并启用 Deployment Manager。
- 如果您尚未启用 Google Compute Engine,请启用它。
- 找到您的 Google Developers Console 项目 ID。
要确定您的项目 ID,请执行以下操作
- 访问Google Developers Console。
- 在主登陆页面上的表格中找到您的项目。
- 项目 ID 出现在表格的第二列。
- 下载 google-api-python-client 库。
授权服务
此示例使用 OAuth 2.0 授权。您需要创建一个客户端 ID 和客户端密钥,并将两者与 oauth2client 库一起使用。默认情况下,oauth2 库包含在 google-api-python-client 库中,您应该在 先决条件部分下载了该库。对于此示例,您需要为 已安装的应用程序 创建一个客户端 ID 和密钥。
要查找您的项目的客户端 ID 和客户端密钥,请执行以下操作
- 访问Google Developers Console。
- 选择一个项目,或创建一个新项目。
- 在左侧边栏中,展开 API 和身份验证。接下来,点击 API。在 API 列表中,确保 Google Cloud Deployment Manager API 的状态为 ON。
- 在左侧边栏中,选择 凭据。
- 如果尚未执行此操作,请通过点击 创建新客户端 ID 并提供创建凭据所需的信息来创建项目的 OAuth 2.0 凭据。
- 在与您的每个凭据关联的表格中查找 客户端 ID 和 客户端密钥。
请注意,并非所有类型的凭据都使用客户端 ID 和客户端密钥,如果未使用,则不会在表格中列出。
为 已安装的应用程序 创建客户端 ID 和密钥后,通过单击 下载 JSON 并将文件命名为 client_secrets.json 将其保存在本地。接下来,在与 client_secrets.json 文件相同的目录中创建一个名为 helloworld.py 的文件,并提供以下代码
#!/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)
如果此时运行该程序,系统将提示您授予对 Deployment Manager 的访问权限。在浏览器中运行完该过程后,您的应用程序应该被授权访问 Deployment Manager API。
构建和初始化 API
在可信测试人员阶段,您需要使用本地发现文档构建和初始化 Deployment Manager API 的一个版本。为此,请在您的应用程序中包含以下粗体行
#!/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)
太棒了,现在您可以开始向 API 发出请求了!
列出资源
要列出 Deployment Manager 资源,请使用以下方法之一
- 列出模板
-
deployment_service.templates().list(projectId=<project-id>)
- 列出部署
-
deployment_service.deployments().list(projectId=<project-id>, region=region)
对于此示例,我们将查询 API 以获取服务列表。将以下行添加到您的应用程序
#!/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)
运行该应用程序以查看您的请求的结果。在命令行中,运行
python helloworld.py
如果您有要列出的服务,您的结果应与以下内容类似
{
"resources": [
{
"name": "myservice"
},
{
"name": "myotherservice"
}
]
}
如果您没有任何资源,您应该会收到一个空的资源列表作为响应。
添加资源
要添加资源,请使用以下方法之一
- 添加模板
-
deployment_service.templates().insert(projectId=<project-id>, body=template)
template
将包含模板的配置设置。例如,template
可能如下所示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" }] }] } } } } }
- 添加部署
-
deployment_service.deployments().insert(projectId=<project-id>, body=deployment, region=<region>)
请求正文必须包含您要创建的部署的名称和您要使用的模板
deployment = { "name" : "my-deployment-name", "templateName" : "my-template-name" }
在我们的示例中,我们将插入一个模板和一个部署。
#!/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)
删除资源
使用以下方法删除资源
- 删除部署
-
deployment_service.deployments().delete(projectId=<project-id>, deploymentName=<deployment-name>, region=<region>)
- 删除模板
-
deployment_service.templates().delete(projectName=<project-id>, templateName=<template-name>)
在我们的示例中,我们将删除我们刚刚创建的部署。将以下行添加到您的文件中
#!/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)
后续步骤
此快速入门提供了一个关于如何使用 Deployment Manager API 的非常基本的示例。有关 API 方法的完整列表,请查看 参考文档。您还可以查看可以使用的 可用客户端库。
除非另有说明,本页的代码示例根据 Apache 2.0 许可证 授权。