gce使用示例指南启动实例python api

时间:2016-11-23 12:05:49

标签: python api google-cloud-platform createinstance google-cloud-python

我尝试复制google网站上的以下指南 https://cloud.google.com/compute/docs/tutorials/python-guide

我无法弄清楚什么是桶,计算意味着什么。我需要将哪种参数传递到脚本中? 我应该把什么放在getFromFamily中(     project =' debian-cloud',family =' debian-8')。执行()如果我想启动私人图片? 我会像下面那样传入变量吗?

create_instance(compute,projectname, us-east1-a, instance-1, bucket)

我已将脚本简化如下。我拿出了我认为不需要的参数。

def create_instance(compute, project, zone, name, bucket):

image_response = compute.images().getFromFamily(
    project='debian-cloud', family='debian-8').execute()
source_disk_image = image_response['selfLink']

# Configure the machine
machine_type = "us-east1-b/%s/machineTypes/f1-micro" % zone
startup_script = open(
    os.path.join(
        os.path.dirname(__file__), 'startup-script.sh'), 'r').read()

config = {
    'name': instance-1,
    'machineType': f1-micro,

    # Specify the boot disk and the image to use as a source.
    'disks': [
        {
            'boot': True,
            'autoDelete': True,
            'initializeParams': {
                'sourceImage': /global/imagename,
            }
        }
    ],

    # Specify a network interface with NAT to access the public
    # internet.
    'networkInterfaces': [{
        'network': 'global/networks/default',
        'accessConfigs': [
            {'type': 'ONE_TO_ONE_NAT', 'name': 'External NAT'}
        ]
    }],

    # Allow the instance to access cloud storage and logging.
    'serviceAccounts': [{
        'email': 'default',
        'scopes': [
            'https://www.googleapis.com/auth/devstorage.read_write',

        ]
    }],

    # Metadata is readable from the instance and allows you to
    # pass configuration from deployment scripts to instances.
    'metadata': {
        'items': [{
            # Startup script is automatically executed by the
            # instance upon startup.
            'key': 'startup-script',
            'value': startup_script
        },  {
            'key': 'bucket',
            'value': bucket
        }]
    }
}

return compute.instances().insert(
    project=project,
    zone=zone,
    body=config).execute()

2 个答案:

答案 0 :(得分:1)

这已经有一段时间了,但这里有一些信息。

仅当您希望实例具有共享存储位置(文档here)时才需要bucket。如果不需要存储桶,则应删除元数据bucket键值(尽管我很惊讶地看到创建具有假存储桶名称的实例不会失败)。

compute是经过身份验证的客户端对象,用于与您的“计算引擎”进行交互。服务。要获取客户端,您需要按照这些instructions获取密钥,密钥和刷新令牌。这是一个代码示例:

from googleapiclient import discovery
from oauth2client.client import GoogleCredentials
from oauth2client import GOOGLE_TOKEN_URI
credentials = GoogleCredentials(access_token=None, client_id='your-client-id', 
                                client_secret='your-client-secret',
                                refresh_token='your-refresh-token',
                                token_expiry=None, token_uri=GOOGLE_TOKEN_URI,
                                user_agent='Python client library')
compute = discovery.build('compute', 'v1', credentials=credentials)

对于私有图片,如果您想使用相同的代码,则需要在GCE console中找到并识别它们,并提供projectfamily个标识符。您还可以使用API​​按名称获取图像:

image = compute.images().get(project='your-project-id', image='your-image-name').execute(),其中image['selfLink']应作为sourceImage实例config提供import pandas as pd import numpy as np from io import StringIO from sklearn import linear_model as lm data= '''Fruit jan feb mar apr may jun jul aug sep oct nov dec Apples nan nan nan 600 550 620 nan nan 300 100 200 50 Bananas 740 720 780 700 250 140 20 nan nan nan nan nan Kiwis nan nan nan nan 400 550 nan 500 nan 40 50 nan Oranges nan 300 350 300 400 500 nan nan nan nan nan nan Grapes 150 200 250 200 50 50 40 35 30 20 10 nan''' def coefficient(row): y = np.array(row['jan':'dec'].astype(float)) y = np.nan_to_num(y) y = y[y != 0] x = np.arange(1,len(y)+1).reshape(len(y),1) return lm.LinearRegression().fit(x,y).coef_ df = pd.read_csv(StringIO(data),delimiter='\s+') df['COEF'] = df.apply(coefficient,axis=1)

答案 1 :(得分:0)

该示例已过时:注意oauth2client现在已弃用,而Google Auth是当前的客户端库。这是更新的解决方案。至关重要的步骤是生成正确的更新后的json。这可以通过在授权的服务帐户下使用等效的REST命令转换您的预期实例来实现。

enter image description here

import google.auth
import googleapiclient.discovery
PROJECT_ID = "<your project ID>"
ZONE = "<your zone>"

credentials, _ = google.auth.default()
compute = googleapiclient.discovery.build('compute', 'v1', 
credentials=credentials)

config = "{generate your instance's json from equivalent REST}"

compute.instances().insert(project=PROJECT_ID, zone=ZONE, 
body=config).execute()