Im writing a program which automatically creates servers in openstack when needed. The problem is that I want the program to wait until the instance has gotten its ip address before proceeding. If the instance has not gotten its ip, novaclient will throw an exception and the object will die. Using the sleep function makes it work, but I dont want that to be the permanent solution.
ipAddress = None
try:
instance = nova.servers.create(name=self.hostName, image=image,
flavor=flavor, key_name="mykey",
nics=nics)
while(ipAddress == None): #<---Something like this, just actually working
for network in instance.networks['my_net']:
if re.match('\d+\.\d+\.\d+\.\d+', network):
self.ipAddress = network
break
print 'The server is waiting at IP address {0}.'.format(self.ipAddress)
except:
print "could not create webserver"
#WebManager.exception(hostname)
finally:
print("Execution Completed")
self.addToLoadbalancer()
Is there a way to write a sort of spinlock or similar that will wait unntil the server have gotten its ip? Any tips would be great.
I managed to fix the issue. It turned out it was hard to detect when the machine was ready by using only novaclient. By using nova list
I managed to get the ip address.
while 1 == 1:
result = getbash("nova list" + " | grep " + hostname + \\
" | awk '{print $12}'").split('=')
if re.match('\d+\.\d+\.\d+\.\d+', result[-1]):
self.ipAddress = result[-1]
print 'The server is waiting at IP address {0}.'.format(self.ipAddress)
break
sleep(1)
This code queries for the hostname and checks if the instance has recieved an ip address. The getbash() function is a simple subprocess
function which return the output of subprocess.Popen(command,stdout=subprocess.PIPE, shell=True)