Resizing Servers Using Python

The following example shows how to resize a server using Python. It looks more complex than the curl example, but that's only because it also shows how to extract the flavor URL:

#!/usr/bin/python

import base64
import urllib
import httplib
import json
import os
from urlparse import urlparse

### --8<--8<--8<--8<--8<--8<--8<--8<--8<--8<--8<--8<--8<--
###
###  insert the 'Get OpenStack Credentials' snippet here
###
### --8<--8<--8<--8<--8<--8<--8<--8<--8<--8<--8<--8<--8<--

###
### Resize a server
###

# HTTP connection #2

srvID = 1       # server ID number
flavorID = 3        # flavor ID number

url2 = apiurlt[1]

# Flavor URL

# HTTP connection #2

params2 = urllib.urlencode({})
headers2 = { "X-Auth-Token":apitoken, "Content-type":"application/json" }

if (usehttps == True):
    conn2 = httplib.HTTPSConnection(url2, key_file='../cert/priv.pem', cert_file='../cert/srv_test.crt')
else:
    conn2 = httplib.HTTPConnection(url2)

conn2.request("GET", "%s/flavors" % apiurlt[2], params2, headers2)

# HTTP response #2

response2 = conn2.getresponse()
data2 = response2.read()
dd2 = json.loads(data2)

conn2.close()

n = len(dd2["flavors"])
m = range(n)

for i in m:
    if dd2["flavors"][i]["id"] == flavorID:
        sFlavorRef = dd2["flavors"][i]["links"][0]["href"]

# HTTP connection #3

params3 = urllib.urlencode(json.dumps({"resize": {"flavorRef": sFlavorRef}}))
headers3 = { "X-Auth-Token":apitoken, "Content-type":"application/json" }

if (usehttps == True):
    conn3 = httplib.HTTPSConnection(url2, key_file='../cert/priv.pem', cert_file='../cert/srv_test.crt')
else:
    conn3 = httplib.HTTPConnection(url2)

conn3.request("POST", "%s/servers/%s/action" % (apiurlt[2], srvID), params3, headers3)

# HTTP response #3

response3 = conn3.getresponse()
data3 = response3.read()
conn3.close()


loading table of contents...