-
-
Save moorryan/93fa4be65fc5ea60b3ed to your computer and use it in GitHub Desktop.
Openstack: clean up ports that are associated with deleted instances
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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