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)來了的,
所以可以簡(jiǎ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

簡(jiǎn)單獲取:

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)系作者
  • 序言:七十年代末狠轻,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子彬犯,更是在濱河造成了極大的恐慌向楼,老刑警劉巖,帶你破解...
    沈念sama閱讀 211,194評(píng)論 6 490
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件谐区,死亡現(xiàn)場(chǎng)離奇詭異湖蜕,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)宋列,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 90,058評(píng)論 2 385
  • 文/潘曉璐 我一進(jìn)店門昭抒,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人炼杖,你說我怎么就攤上這事灭返。” “怎么了坤邪?”我有些...
    開封第一講書人閱讀 156,780評(píng)論 0 346
  • 文/不壞的土叔 我叫張陵熙含,是天一觀的道長(zhǎng)。 經(jīng)常有香客問我艇纺,道長(zhǎng)怎静,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 56,388評(píng)論 1 283
  • 正文 為了忘掉前任黔衡,我火速辦了婚禮蚓聘,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘盟劫。我一直安慰自己夜牡,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 65,430評(píng)論 5 384
  • 文/花漫 我一把揭開白布捞高。 她就那樣靜靜地躺著氯材,像睡著了一般。 火紅的嫁衣襯著肌膚如雪硝岗。 梳的紋絲不亂的頭發(fā)上氢哮,一...
    開封第一講書人閱讀 49,764評(píng)論 1 290
  • 那天,我揣著相機(jī)與錄音型檀,去河邊找鬼冗尤。 笑死,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的裂七。 我是一名探鬼主播皆看,決...
    沈念sama閱讀 38,907評(píng)論 3 406
  • 文/蒼蘭香墨 我猛地睜開眼,長(zhǎng)吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼背零!你這毒婦竟也來了腰吟?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 37,679評(píng)論 0 266
  • 序言:老撾萬榮一對(duì)情侶失蹤徙瓶,失蹤者是張志新(化名)和其女友劉穎毛雇,沒想到半個(gè)月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體侦镇,經(jīng)...
    沈念sama閱讀 44,122評(píng)論 1 303
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡灵疮,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 36,459評(píng)論 2 325
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了壳繁。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片震捣。...
    茶點(diǎn)故事閱讀 38,605評(píng)論 1 340
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖闹炉,靈堂內(nèi)的尸體忽然破棺而出蒿赢,到底是詐尸還是另有隱情,我是刑警寧澤剩胁,帶...
    沈念sama閱讀 34,270評(píng)論 4 329
  • 正文 年R本政府宣布诉植,位于F島的核電站,受9級(jí)特大地震影響昵观,放射性物質(zhì)發(fā)生泄漏晾腔。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 39,867評(píng)論 3 312
  • 文/蒙蒙 一啊犬、第九天 我趴在偏房一處隱蔽的房頂上張望灼擂。 院中可真熱鬧,春花似錦觉至、人聲如沸剔应。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,734評(píng)論 0 21
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽峻贮。三九已至,卻和暖如春应闯,著一層夾襖步出監(jiān)牢的瞬間纤控,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 31,961評(píng)論 1 265
  • 我被黑心中介騙來泰國(guó)打工碉纺, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留船万,地道東北人刻撒。 一個(gè)月前我還...
    沈念sama閱讀 46,297評(píng)論 2 360
  • 正文 我出身青樓,卻偏偏與公主長(zhǎng)得像耿导,于是被迫代替她去往敵國(guó)和親声怔。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 43,472評(píng)論 2 348

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

  • 第一章 OpenStack基礎(chǔ) OpenStack管理的資源及提供的服務(wù)OpenStack做為一個(gè)操作系統(tǒng)舱呻,...
    sgt_tiger閱讀 12,894評(píng)論 4 72
  • Nova Nova醋火,即計(jì)算服務(wù),是OpenStack計(jì)算的彈性控制器箱吕。Nova可以說是整個(gè)云平臺(tái)最重要的組件胎撇,Op...
    邵勝奧閱讀 4,141評(píng)論 0 8
  • Openstack Mitaka安裝部署教程 一、實(shí)驗(yàn)環(huán)境: 系統(tǒng):centos7.2-minimal 網(wǎng)絡(luò):管理...
    指間_流年閱讀 2,187評(píng)論 0 0
  • 天破了殖氏,自己煉石來補(bǔ); 洪水來了姻采,不問先知雅采,自己挖河渠疏通; 疾病流行慨亲,不求神跡婚瓜,自己試藥自己治; 在東海淹死了就...
  • 小張被調(diào)到教育局工作了刑棵,很多人都覺得不可思議——憑什么巴刻,他要學(xué)歷沒學(xué)歷,要關(guān)系沒關(guān)系蛉签!有人議論:“沒聽說他有什么后...
    春風(fēng)絮語閱讀 528評(píng)論 4 3