OpenStack SDK 使用

OpenStack針對(duì)不同的用戶提供4種與Python API交互的方式:

1)OpenStack SDK
2)Shadow
3)per-project libraries
4)直接通過RESTful調(diào)用keystoneauth

前提知識(shí):
1)RESTful Web 服務(wù)
2)HTTP /1.1
3)JSON與數(shù)據(jù)序列化格式


1.OpenStack SDK

OpenStack Software Development Kit(OpenStack SDK),用于編寫創(chuàng)建Python的自動(dòng)化腳本,并在openstack中管理云資源。SDK實(shí)現(xiàn)了與OpenStack API 的Python綁定,使你能夠通過調(diào)用Python對(duì)象來執(zhí)行Python中的自動(dòng)化任務(wù),而不是直接使用REST調(diào)用。

新用戶應(yīng)該使用OpenStack SDK 來進(jìn)行編碼。

2.Shadow

Shadow是一個(gè)抽象庫(就是沒有實(shí)現(xiàn)的),專注于隱藏OpenStack云之間的實(shí)現(xiàn)差異。雖然OpenStack SDK向底層REST API提供了一個(gè)干凈的對(duì)象接口,但如果這樣做有利的話,陰影隱藏它們。如果您計(jì)劃針對(duì)許多OpenStack云運(yùn)行相同的Python程序,則可能需要使用陰影 - 但是如果您需要訪問沒有云中性抽象映射的云的任何功能,則無法執(zhí)行此操作有陰影。

3.per-project libraries

每個(gè)OpenStack項(xiàng)目都會(huì)生成一個(gè)包裝自己的REST API的客戶端庫。除非因某些原因沒有其他選擇,否則應(yīng)避免每個(gè)項(xiàng)目庫。

4.直接通過REST調(diào)用keystoneauth

所有OpenStack的API實(shí)際上都是REST API。
該 keystoneauth庫提供了一個(gè)對(duì)象,它看起來非常像一個(gè) 會(huì)話從Python對(duì)象 請(qǐng)求庫,處理所有身份驗(yàn)證的為您服務(wù)。
如果您更輕松地處理REST,或者如果您的云中實(shí)現(xiàn)了某項(xiàng)功能,但尚未在任何library中獲得支持,則此選項(xiàng)適用于你。


安裝OpenStack SDK

每個(gè)OpenStack項(xiàng)目都有自己的python庫。
這些庫命令與命令行客戶機(jī)捆綁在一起。例如:compute API 的Python綁定與python-novaclient包捆綁在一起。

注意:項(xiàng)目的理解:
keystone 是一個(gè)項(xiàng)目 neutron是一個(gè)項(xiàng)目 nova使用一個(gè)項(xiàng)目 等等
keystone是你注冊(cè)project


認(rèn)證(Authenticate )

使用SDK時(shí)候,你必須先對(duì)OpenStack 的endpoint進(jìn)行身份驗(yàn)證,然后才能使用OpenStack 服務(wù)。因?yàn)樗许?xiàng)目都使用keystone進(jìn)行身份驗(yàn)證,所以無論你決定更使用哪種服務(wù)或者庫,這個(gè)過程都是一樣的。每個(gè)library都有更加先進(jìn)和復(fù)雜的方式來做事情,如果有需要的話。

處理云配置和憑據(jù)有兩種基本方法:
1)環(huán)境變量通過openrc.sh文件
2)clouds.yaml配置文件

環(huán)境變量已經(jīng)是使用最久的,是您最有可能從云提供商那里獲得的形式。如果您只有一個(gè)云端帳戶,那么它們是最方便的方式。
clouds.yaml 是一個(gè)新的方式,旨在幫助有多個(gè)OpenStack云使用他們的人。

openrc.sh:里面存放的是環(huán)境變量。比如賬號(hào),密碼等。


創(chuàng)建一個(gè)經(jīng)典客戶端對(duì)象

所有的傳統(tǒng)客戶端對(duì)象可以以相同的方式構(gòu)造-唯一的區(qū)別是第一個(gè)參數(shù)make_client不同。
下面的例子可以使用compute 去獲得一個(gè)nova client,但是neutron能夠通過將compute改為network獲得。

要使用具有Compute endpoint 的 python-novaclient,請(qǐng)使用下面的方法創(chuàng)建:

import os_client_config

nova = os_client_config.make_client(
    'compute',
    auth_url='https://example.com',
    username='example-openstack-user',
    password='example-password',
    project_name='example-project-name',
    region_name='example-region-name')

如果你想要一個(gè)特定的微型版本的Nova API,你可以把它作為version參數(shù):

import os_client_config

nova = os_client_config.make_client(
    'compute',
    version='2.10',
    auth_url='https://example.com',
    username='example-openstack-user',
    password='example-password',
    project_name='example-project-name',
    region_name='example-region-name')

注意:nova client代表的是可以操作nova的相關(guān)功能。

如果對(duì)使用自定義身份驗(yàn)證endpoint進(jìn)行身份驗(yàn)證,則必須在auth_type參數(shù)中提供插件的名稱 。
例如,Rackspace公共云是具有可選的自定義身份驗(yàn)證后端的OpenStack部署。正常的梯形密碼認(rèn)證工作原理非常好,你可能希望使用rackspace-keystonauth-plugin中定制的rackspace keystoneauth API Key 插件。

nova = os_client_config.make_client(
    'compute',
    auth_type='rackspace_apikey',
    auth_url='https://example.com',
    username='example-openstack-user',
    api_key='example-apikey',
    project_name='example-project-name',
    region_name='example-region-name')

管理image

在使用SDK中的image的時(shí)候,你將調(diào)用glancenova

列出image:

import glanceclient.v2.client as glclient
glance = glclient.Client(...)
images = glance.images.list()

images方法返回一個(gè)python生成器(generator),如以下雨python解釋器的交互所示:

>>> images = glance.images.list()
>>> images
<generator object list at 0x105e9c2d0>
>>> list(images)
[{u'checksum': u'f8a2eeee2dc65b3d9b6e63678955bd83',
  u'container_format': u'ami',
  u'created_at': u'2013-10-20T14:28:10Z',
  u'disk_format': u'ami',
  u'file': u'/v2/images/dbc9b2db-51d7-403d-b680-3f576380b00c/file',
  u'id': u'dbc9b2db-51d7-403d-b680-3f576380b00c',
  u'kernel_id': u'c002c82e-2cfa-4952-8461-2095b69c18a6',
  u'min_disk': 0,
  u'min_ram': 0,
  u'name': u'cirros-0.3.5-x86_64-uec',
  u'protected': False,
  u'ramdisk_id': u'4c1c9b4f-3fe9-425a-a1ec-1d8fd90b4db3',
  u'schema': u'/v2/schemas/image',
  u'size': 25165824,
  u'status': u'active',
  u'tags': [],
  u'updated_at': u'2013-10-20T14:28:11Z',
  u'visibility': u'public'},
 {u'checksum': u'69c33642f44ca552ba4bb8b66ad97e85',
  u'container_format': u'ari',
  u'created_at': u'2013-10-20T14:28:09Z',
  u'disk_format': u'ari',
  u'file': u'/v2/images/4c1c9b4f-3fe9-425a-a1ec-1d8fd90b4db3/file',
  u'id': u'4c1c9b4f-3fe9-425a-a1ec-1d8fd90b4db3',
  u'min_disk': 0,
  u'min_ram': 0,
  u'name': u'cirros-0.3.5-x86_64-uec-ramdisk',
  u'protected': False,
  u'schema': u'/v2/schemas/image',
  u'size': 3714968,
  u'status': u'active',
  u'tags': [],
  u'updated_at': u'2013-10-20T14:28:10Z',
  u'visibility': u'public'},
 {u'checksum': u'c352f4e7121c6eae958bc1570324f17e',
  u'container_format': u'aki',
  u'created_at': u'2013-10-20T14:28:08Z',
  u'disk_format': u'aki',
  u'file': u'/v2/images/c002c82e-2cfa-4952-8461-2095b69c18a6/file',
  u'id': u'c002c82e-2cfa-4952-8461-2095b69c18a6',
  u'min_disk': 0,
  u'min_ram': 0,
  u'name': u'cirros-0.3.5-x86_64-uec-kernel',
  u'protected': False,
  u'schema': u'/v2/schemas/image',
  u'size': 4955792,
  u'status': u'active',
  u'tags': [],
  u'updated_at': u'2013-10-20T14:28:09Z',
  u'visibility': u'public'}]

通過ID獲得image

要從ID中檢索出圖像對(duì)象,請(qǐng)調(diào)用以下方法:

import glanceclient.v2.client as glclient
image_id = 'c002c82e-2cfa-4952-8461-2095b69c18a6'
glance = glclient.Client(...)
image = glance.images.get(image_id)

通過名字獲得image:

image服務(wù)python綁定 不支持按名稱檢索image對(duì)象。然而,compute python 綁定(nova),可以讓你通過名稱獲得Image對(duì)象。用通過名稱獲取Image對(duì)象,方法如下:

import novaclient.v2.client as nvclient
name = "cirros"
nova = nvclient.Client(...)
image = nova.images.find(name=name)

上傳鏡像:

import glanceclient.v2.client as glclient
imagefile = "/tmp/myimage.img"
glance = glclient.Client(...)
with open(imagefile) as fimage:
  glance.images.create(name="myimage", is_public=False, disk_format="qcow2",
                       container_format="bare", data=fimage)

將CORS header 分配給請(qǐng)求

跨原始資源共享 Cross-Origin Resource Sharing(CORS)
是一個(gè)貴方,用于定義瀏覽器和服務(wù)器如果通過使用HTTP headers(標(biāo)頭),例如由Object Storage API 請(qǐng)求分配的HTTP 頭 進(jìn)行通信。對(duì)象存儲(chǔ)API支持以下headers:


調(diào)用對(duì)象為了刪除:

要確定對(duì)象存儲(chǔ)系統(tǒng)是否支持此功能,請(qǐng)參閱管理對(duì)象和容器。
計(jì)劃要?jiǎng)h除的對(duì)象有助于管理不想永久存儲(chǔ)的對(duì)象,例如日志文件,數(shù)據(jù)集的定期備份,或者在指定時(shí)間過時(shí)的文檔或者圖像。
要安排一個(gè)要?jiǎng)h除的對(duì)象,請(qǐng)?jiān)趯?duì)象中包含這些頭中的一個(gè)PUT或者POST 請(qǐng)求:

X-Delete-At

UNIX紀(jì)元的事件戳,是證書形式。例如:1348691905(時(shí)間戳)代表的是:Wed, 26 Sept 2012 20:38:25 GMT
它指定您希望對(duì)象到期的時(shí)間,不再被提供,并從對(duì)象存儲(chǔ)完全刪除。

X-Delete-After

就是請(qǐng)求之后,隔了這么多時(shí)間就刪除。

注意:X-Delete-AtX-Delete-After都是請(qǐng)求頭里面的參數(shù)。

使用POST方法將過期標(biāo)頭分配給要過期的現(xiàn)有對(duì)象。

下面的例子是執(zhí)行之后在時(shí)間戳1390581073失效:

$ curl -i publicURL/marktwain/goodbye -X PUT -H "X-Auth-Token: token" \
  -H "X-Delete-At: 1390581073" -H "Content-Length: 14" -H \
  "Content-Type: application/octet-stream"

下面是經(jīng)過864000久之后失效:

PUT /<api version>/<account>/<container>/<object> HTTP/1.1
Host: storage.example.com
X-Auth-Token: eaaafd18-0fed-4b3a-81b4-663c99ec1cbb
Content-Type: image/jpeg
X-Delete-After: 864000

配置實(shí)例的訪問和安全性

當(dāng)使用SDK中的圖像時(shí),你將調(diào)用novaclient方法。

添加密鑰對(duì):

生成一個(gè)密鑰對(duì),可以調(diào)用:novaclient.v1_1.keypairs.KeypairManager.create 方法:

import novaclient.v2.client as nvclient
nova = nvclient.Client(...)
keypair_name = "staging"
keypair = nova.keypairs.create(name=keypair_name)
print keypair.private_key

python腳本輸出會(huì)是這樣的:

-----BEGIN RSA PRIVATE KEY-----
MIIEowIBAAKCAQEA8XkaMqInSPfy0hMfWO+OZRtIgrQAbQkNcaNHmv2GN2G6xZlb\nuBRux5Xk/6SZ
ABaNPm1nRWm/ZDHnxCsFTcAl2LYOQXx3Cl2qKNY4r2di4G48GAkd\n7k5lDP2RgQatUM8npO0CD9PU
...
mmrceYYK08/lQ7JKLmVkdzdQKt77+v1oBBuHiykLfI6h1m77NRDw9r8cV\nzczYeoALifpjTPMkKS8
ECfDCuDn/vc9K1He8CRaJHf8AMLQLM3MN
-----END RSA PRIVATE KEY-----

你通常將私鑰寫入文件以便稍后使用。該文件只能由文件所有者讀取和寫入;否則,SSH客戶端將拒絕讀取私鑰文件。最安全的方法是使用適當(dāng)?shù)臋?quán)限創(chuàng)建文件:

import novaclient.v2.client as nvclient
import os
nova = nvclient.Client(...)
keypair_name = "staging"
private_key_filename = "/home/alice/id-staging"
keypair = nova.keypairs.create(name=keypair_name)

# Create a file for writing that can only be read and written by
owner
fp = os.open(private_key_filename, os.O_WRONLY | os.O_CREAT, 0o600)
with os.fdopen(fp, 'w') as f:
    f.write(keypair.private_key)

導(dǎo)入密鑰對(duì):

如果已經(jīng)使用位于該公鑰的密鑰對(duì)生成了密鑰對(duì),則~/.ssh/id_rsa.pub將該文件的內(nèi)容傳遞給novaclient.v1_1.keypairs.KeypairManager.create方法將公鑰導(dǎo)入到Compute:

import novaclient.v2.client as nvclient
import os.path
with open(os.path.expanduser('~/.ssh/id_rsa.pub')) as f:
    public_key = f.read()
nova = nvclient.Client(...)
nova.keypairs.create('mykey', public_key)

列出密鑰對(duì):

import novaclient.v2.client as nvclient
nova = nvclient.Client(...)
keypairs = nova.keypairs.list()

創(chuàng)建和管理安全組:

import novaclient.v2.client as nvclient
nova = nvclient.Client(...)
security_groups = nova.security_groups.list()

創(chuàng)建具有指定名稱和描述的安全組:

import novaclient.v2.client as nvclient
nova = nvclient.Client(...)
nova.security_groups.create(name="web", description="Web servers")

刪除安全組:

import novaclient.v2.client as nvclient
nova = nvclient.Client(...)
group = nova.security_groups.find(name="web")
nova.security_groups.delete(group)
# The following lines would also delete the group:
# nova.security_groups.delete(group.id)
# group.delete()

創(chuàng)建和管理安全組角色:
查看安全組角色:

import novaclient.v2.client as nvclient
nova = nvclient.Client(...)
group = nova.security_groups.find(name="web")
print group.rules

增加角色給安全組:

import novaclient.v2.client as nvclient
nova = nvclient.Client(...)
group = nova.security_groups.find(name="web")
# Add rules for ICMP, tcp/80 and tcp/443
nova.security_group_rules.create(group.id, ip_protocol="icmp",
                                 from_port=-1, to_port=-1)
nova.security_group_rules.create(group.id, ip_protocol="tcp",
                                 from_port=80, to_port=80)
nova.security_group_rules.create(group.id, ip_protocol="tcp",
                                 from_port=443, to_port=443)

網(wǎng)絡(luò)

要理解用本節(jié)的信息,應(yīng)該對(duì)OpenStack Networking,OpenStack Compute以及兩者之間的集成有一個(gè)一般的了解。還應(yīng)該可以訪問實(shí)現(xiàn)Networking API v2.0的插件。

設(shè)置環(huán)境變量:

確保你設(shè)置相關(guān)的環(huán)境變量。

使用shell 文件設(shè)置以下的環(huán)境變量去獲得憑證:

export OS_USERNAME="admin"
export OS_PASSWORD="password"
export OS_TENANT_NAME="admin"
export OS_AUTH_URL="http://IPADDRESS/v2.0"

獲取憑證,本節(jié)中的示例使用以下的方法:

def get_credentials():
    d = {}
    d['username'] = os.environ['OS_USERNAME']
    d['password'] = os.environ['OS_PASSWORD']
    d['auth_url'] = os.environ['OS_AUTH_URL']
    d['tenant_name'] = os.environ['OS_TENANT_NAME']
    return d

就是一個(gè)字典,里面包含了環(huán)境信息。
上面的代碼存在于credentials.py,都是被導(dǎo)入進(jìn)來了的,
所以可以簡單使用下面的方法獲得字典:

nova_credentials = get_nova_credentials()

打印值:

def print_values(val, type):
    if type == 'ports':
        val_list = val['ports']
    if type == 'networks':
        val_list = val['networks']
    if type == 'routers':
        val_list = val['routers']
    for p in val_list:
        for k, v in p.items():
            print("%s : %s" % (k, v))
        print('\n')


def print_values_server(val, server_id, type):
    if type == 'ports':
        val_list = val['ports']

    if type == 'networks':
        val_list = val['networks']
    for p in val_list:
        bool = False
        for k, v in p.items():
            if k == 'device_id' and v == server_id:
                bool = True
        if bool:
            for k, v in p.items():
                print("%s : %s" % (k, v))
            print('\n')

上面的代碼是存在于utils.py文件中,可以直接導(dǎo)入。

創(chuàng)建網(wǎng)絡(luò):

#!/usr/bin/env python
from neutronclient.v2_0 import client
from credentials import get_credentials

network_name = 'sample_network'
credentials = get_credentials()
neutron = client.Client(**credentials)
try:
    body_sample = {'network': {'name': network_name,
                   'admin_state_up': True}}

    netw = neutron.create_network(body=body_sample)
    net_dict = netw['network']
    network_id = net_dict['id']
    print('Network %s created' % network_id)

    body_create_subnet = {'subnets': [{'cidr': '192.168.199.0/24',
                          'ip_version': 4, 'network_id': network_id}]}

    subnet = neutron.create_subnet(body=body_create_subnet)
    print('Created subnet %s' % subnet)
finally:
    print("Execution completed")

列出網(wǎng)絡(luò):

#!/usr/bin/env python
from neutronclient.v2_0 import client
from credentials import get_credentials
from utils import print_values

credentials = get_credentials()
neutron = client.Client(**credentials)
netw = neutron.list_networks()

print_values(netw, 'networks')

創(chuàng)建端口:

#!/usr/bin/env python
from neutronclient.v2_0 import client
import novaclient.v2.client as nvclient
from credentials import get_credentials
from credentials import get_nova_credentials

credentials = get_nova_credentials()
nova_client = nvclient.Client(**credentials)

# Replace with server_id and network_id from your environment

server_id = '9a52795a-a70d-49a8-a5d0-5b38d78bd12d'
network_id = 'ce5d204a-93f5-43ef-bd89-3ab99ad09a9a'
server_detail = nova_client.servers.get(server_id)
print(server_detail.id)

if server_detail != None:
    credentials = get_credentials()
    neutron = client.Client(**credentials)

    body_value = {
                     "port": {
                             "admin_state_up": True,
                             "device_id": server_id,
                             "name": "port1",
                             "network_id": network_id
                      }
                 }
    response = neutron.create_port(body=body_value)
    print(response)

監(jiān)聽端口:

#!/usr/bin/env python
from neutronclient.v2_0 import client
from credentials import get_credentials
from utils import print_values

credentials = get_credentials()
neutron = client.Client(**credentials)
ports = neutron.list_ports()
print_values(ports, 'ports')

監(jiān)聽服務(wù)端口:

#!/usr/bin/env python
from neutronclient.v2_0 import client
import novaclient.v2.client as nvclient
from credentials import get_credentials
from credentials import get_nova_credentials
from utils import print_values_server

credentials = get_nova_credentials()
nova_client = nvclient.Client(**credentials)

# change these values according to your environment

server_id = '9a52795a-a70d-49a8-a5d0-5b38d78bd12d'
network_id = 'ce5d204a-93f5-43ef-bd89-3ab99ad09a9a'
server_detail = nova_client.servers.get(server_id)
print(server_detail.id)

if server_detail is not None:
    credentials = get_credentials()
    neutron = client.Client(**credentials)
    ports = neutron.list_ports()

    print_values_server(ports, server_id, 'ports')
    body_value = {'port': {
        'admin_state_up': True,
        'device_id': server_id,
        'name': 'port1',
        'network_id': network_id,
        }}

    response = neutron.create_port(body=body_value)
    print(response)

創(chuàng)建路由和給子網(wǎng)增加端口:

1)導(dǎo)入modules:

from neutronclient.v2_0 import client
import novaclient.v2.client as nvclient
from credentials import get_credentials
from credentials import get_nova_credentials
from utils import print_values_server

2)獲得nova憑證,可以參考上面的。

3)創(chuàng)建nova_client實(shí)例:

nova_client = nvclient.Client(**credentials)

4)為子網(wǎng)創(chuàng)建路由和端口:

# Replace with network_id from your environment

network_id = '81bf592a-9e3f-4f84-a839-ae87df188dc1'

credentials = get_credentials()
neutron = client.Client(**credentials)
neutron.format = json
request = {'router': {'name': 'router name',
                      'admin_state_up': True}}

router = neutron.create_router(request)
router_id = router['router']['id']
# for example: '72cf1682-60a8-4890-b0ed-6bad7d9f5466'
router = neutron.show_router(router_id)
print(router)
body_value = {'port': {
    'admin_state_up': True,
    'device_id': router_id,
    'name': 'port1',
    'network_id': network_id,
    }}

response = neutron.create_port(body=body_value)
print(response)
print("Execution Completed")

創(chuàng)建路由:完整示例 :

#!/usr/bin/env python
from neutronclient.v2_0 import client
import novaclient.v2.client as nvclient
from credentials import get_credentials
from credentials import get_nova_credentials
from utils import print_values_server

credentials = get_nova_credentials()
nova_client = nvclient.Client(**credentials)

# Replace with network_id from your environment

network_id = '81bf592a-9e3f-4f84-a839-ae87df188dc1'
try:
    credentials = get_credentials()
    neutron = client.Client(**credentials)
    neutron.format = 'json'
    request = {'router': {'name': 'router name',
                          'admin_state_up': True}}
    router = neutron.create_router(request)
    router_id = router['router']['id']
    # for example: '72cf1682-60a8-4890-b0ed-6bad7d9f5466'
    router = neutron.show_router(router_id)
    print(router)
    body_value = {'port': {
        'admin_state_up': True,
        'device_id': router_id,
        'name': 'port1',
        'network_id': network_id,
        }}

    response = neutron.create_port(body=body_value)
    print(response)
finally:
    print("Execution completed")

刪除網(wǎng)絡(luò):
1)導(dǎo)入模塊:

from neutronclient.v2_0 import client
from credentials import get_credentials

2)獲得憑證:Get Nova credentials.

3)創(chuàng)建實(shí)例:

neutron = client.Client(**credentials)

4)刪除網(wǎng)絡(luò):

body_sample = {'network': {'name': network_name,
               'admin_state_up': True}}

netw = neutron.create_network(body=body_sample)
net_dict = netw['network']
network_id = net_dict['id']
print('Network %s created' % network_id)

body_create_subnet = {'subnets': [{'cidr': '192.168.199.0/24',
                      'ip_version': 4, 'network_id': network_id}]}

subnet = neutron.create_subnet(body=body_create_subnet)
print('Created subnet %s' % subnet)

neutron.delete_network(network_id)
print('Deleted Network %s' % network_id)

print("Execution completed")

完整示例:

#!/usr/bin/env python
from neutronclient.v2_0 import client
from credentials import get_credentials

network_name = 'temp_network'
credentials = get_credentials()
neutron = client.Client(**credentials)
try:
    body_sample = {'network': {'name': network_name,
                   'admin_state_up': True}}

    netw = neutron.create_network(body=body_sample)
    net_dict = netw['network']
    network_id = net_dict['id']
    print('Network %s created' % network_id)

    body_create_subnet = {'subnets': [{'cidr': '192.168.199.0/24',
                          'ip_version': 4, 'network_id': network_id}]}

    subnet = neutron.create_subnet(body=body_create_subnet)
    print('Created subnet %s' % subnet)

    neutron.delete_network(network_id)
    print('Deleted Network %s' % network_id)
finally:
    print("Execution Completed")

列出路由:
完整示例:

#!/usr/bin/env python
from neutronclient.v2_0 import client
from credentials import get_credentials
from utils import print_values

try:
    credentials = get_credentials()
    neutron = client.Client(**credentials)
    routers_list = neutron.list_routers(retrieve_all=True)
    print_values(routers_list, 'routers')
finally:
    print("Execution completed")

列出子網(wǎng):

#!/usr/bin/env python
from neutronclient.v2_0 import client
from credentials import get_credentials
from utils import print_values

credentials = get_credentials()
neutron = client.Client(**credentials)
subnets = neutron.list_subnets()
print(subnets)

計(jì)算:

獲得OpenStack憑證:

def get_nova_credentials_v2():
    d = {}
    d['version'] = '2'
    d['username'] = os.environ['OS_USERNAME']
    d['api_key'] = os.environ['OS_PASSWORD']
    d['auth_url'] = os.environ['OS_AUTH_URL']
    d['project_id'] = os.environ['OS_TENANT_NAME']
    return d

簡單獲取:

credentials = get_nova_credentials_v2()

列出服務(wù):

#!/usr/bin/env python
from credentials import get_nova_credentials_v2
from novaclient.client import Client

credentials = get_nova_credentials_v2()
nova_client = Client(**credentials)

print(nova_client.servers.list())

創(chuàng)建server:

#!/usr/bin/env python
import time
from credentials import get_nova_credentials_v2
from novaclient.client import Client

try:
    credentials = get_nova_credentials_v2()
    nova_client = Client(**credentials)

    image = nova_client.images.find(name="cirros")
    flavor = nova_client.flavors.find(name="m1.tiny")
    net = nova_client.networks.find(label="private")
    nics = [{'net-id': net.id}]
    instance = nova_client.servers.create(name="vm2", image=image,
                                      flavor=flavor, key_name="keypair-1", nics=nics)
    print("Sleeping for 5s after create command")
    time.sleep(5)
    print("List of VMs")
    print(nova_client.servers.list())
finally:
    print("Execution Completed")

刪除server:

#!/usr/bin/env python
from credentials import get_nova_credentials_v2
from novaclient.client import Client

credentials = get_nova_credentials_v2()
nova_client = Client(**credentials)

servers_list = nova_client.servers.list()
server_del = "vm1"
server_exists = False

for s in servers_list:
    if s.name == server_del:
        print("This server %s exists" % server_del)
        server_exists = True
        break
if not server_exists:
    print("server %s does not exist" % server_del)
else:
    print("deleting server..........")
    nova_client.servers.delete(s)
    print("server %s deleted" % server_del)

更新server:


#!/usr/bin/env python

from credentials import get_nova_credentials_v2
from novaclient.client import Client
from utils import print_server

credentials = get_nova_credentials_v2()
nova_client = Client(**credentials)

# Change the server_id specific to your environment

server_id = '99889c8d-113f-4a7e-970c-77f1916bfe14'
server = nova_client.servers.get(server_id)
n = server.name
print_server(server)

server.update(name=n +'1')
server_updated = nova_client.servers.get(server_id)
print_server(server_updated)

列出:

#!/usr/bin/env python

from credentials import get_nova_credentials_v2
from novaclient.client import Client
from utils import print_flavors

credentials = get_nova_credentials_v2()
nova_client = Client(**credentials)

flavors_list = nova_client.flavors.list()
print_flavors(flavors_list)

列出浮動(dòng)ip:

#!/usr/bin/env python

from credentials import get_nova_credentials_v2
from novaclient.client import Client
from utils import print_values_ip

credentials = get_nova_credentials_v2()
nova_client = Client(**credentials)
ip_list = nova_client.floating_ips.list()
print_values_ip(ip_list)

列出hosts:

#!/usr/bin/env python

from credentials import get_nova_credentials_v2
from novaclient.client import Client
from utils import print_hosts

credentials = get_nova_credentials_v2()
nova_client = Client(**credentials)
host_list = nova_client.hosts.list()

print_hosts(host_list)
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容