Skip to content

Instantly share code, notes, and snippets.

@moorryan
Last active August 29, 2015 14:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save moorryan/93fa4be65fc5ea60b3ed to your computer and use it in GitHub Desktop.
Save moorryan/93fa4be65fc5ea60b3ed to your computer and use it in GitHub Desktop.
Openstack: clean up ports that are associated with deleted instances
#!/usr/bin/env python
"""
clean up ports that are associated with deleted instances
"""
import os
import novaclient
from neutronclient.neutron import client as net
from novaclient.v1_1 import client as nova
def main():
h_nova = nova.Client(os.environ['OS_USERNAME'],
os.environ['OS_PASSWORD'],
os.environ['OS_TENANT_NAME'],
os.environ['OS_AUTH_URL'],
region_name=os.environ['OS_REGION_NAME'])
h_net = net.Client('2.0',
username=os.environ['OS_USERNAME'],
password=os.environ['OS_PASSWORD'],
tenant_name=os.environ['OS_TENANT_NAME'],
auth_url=os.environ['OS_AUTH_URL'],
region_name=os.environ['OS_REGION_NAME'])
port_list = h_net.list_ports()
ports = port_list.get('ports', [])
for port in ports:
# filter out all but the ports associated with instances
if not port['device_owner'].startswith('compute'):
continue
try:
server = h_nova.servers.get(port['device_id'])
print('Port %(port)s is associated with '
'server: %(server)s - %(status)s' %
{'port': port['id'], 'server': server.name,
'status': server.status})
except novaclient.exceptions.NotFound:
print('Removing port %(port)s as associated '
'instance "%(instance)s" does not exist' %
{'port': port['id'], 'instance': port['device_id']})
h_net.delete_port(port['id'])
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment