3 # jose.lausuch@ericsson.com
4 # valentin.boucher@orange.com
5 # All rights reserved. This program and the accompanying materials
6 # are made available under the terms of the Apache License, Version 2.0
7 # which accompanies this distribution, and is available at
8 # http://www.apache.org/licenses/LICENSE-2.0
16 # ----------------------------------------------------------
20 # -----------------------------------------------------------
23 # *********************************************
25 # *********************************************
26 def check_credentials():
28 Check if the OpenStack credentials (openrc) are sourced
30 env_vars = ['OS_AUTH_URL', 'OS_USERNAME', 'OS_PASSWORD', 'OS_TENANT_NAME']
31 return all(map(lambda v: v in os.environ and os.environ[v], env_vars))
34 def get_credentials(service):
35 """Returns a creds dictionary filled with the following keys:
37 * password/api_key (depending on the service)
38 * tenant_name/project_id (depending on the service)
40 :param service: a string indicating the name of the service
41 requesting the credentials.
45 # Check that the env vars exists:
46 envvars = ('OS_USERNAME', 'OS_PASSWORD', 'OS_AUTH_URL', 'OS_TENANT_NAME')
47 for envvar in envvars:
48 if os.getenv(envvar) is None:
49 print("'%s' is not exported as an env variable." % envvar)
52 # Unfortunately, each of the OpenStack client will request slightly
53 # different entries in their credentials dict.
54 if service.lower() in ("nova", "cinder"):
59 tenant = "tenant_name"
61 # The most common way to pass these info to the script is to do it through
62 # environment variables.
64 "username": os.environ.get("OS_USERNAME"),
65 password: os.environ.get("OS_PASSWORD"),
66 "auth_url": os.environ.get("OS_AUTH_URL"),
67 tenant: os.environ.get("OS_TENANT_NAME")
69 cacert = os.environ.get("OS_CACERT")
70 if cacert is not None:
71 # each openstack client uses differnt kwargs for this
72 creds.update({"cacert": cacert,
74 "https_ca_cert": cacert,
75 "https_cacert": cacert,
77 creds.update({"insecure": "True", "https_insecure": "True"})
78 if not os.path.isfile(cacert):
79 print ("WARNING: The 'OS_CACERT' environment variable is " +
80 "set to %s but the file does not exist." % cacert)
84 def source_credentials(rc_file):
85 pipe = subprocess.Popen(". %s; env" % rc_file, stdout=subprocess.PIPE,
87 output = pipe.communicate()[0]
88 env = dict((line.split("=", 1) for line in output.splitlines()))
89 os.environ.update(env)
93 # *********************************************
95 # *********************************************
96 def get_instances(nova_client):
98 instances = nova_client.servers.list(search_opts={'all_tenants': 1})
101 print "Error [get_instances(nova_client)]:", e
105 def get_instance_status(nova_client, instance):
107 instance = nova_client.servers.get(instance.id)
108 return instance.status
110 # print ("Error [get_instance_status(nova_client, '%s')]:" %
115 def get_instance_by_name(nova_client, instance_name):
117 instance = nova_client.servers.find(name=instance_name)
120 print ("Error [get_instance_by_name(nova_client, '%s')]:" %
125 def get_flavor_id(nova_client, flavor_name):
126 flavors = nova_client.flavors.list(detailed=True)
129 if f.name == flavor_name:
135 def get_flavor_id_by_ram_range(nova_client, min_ram, max_ram):
136 flavors = nova_client.flavors.list(detailed=True)
139 if min_ram <= f.ram and f.ram <= max_ram:
145 def get_floating_ips(nova_client):
147 floating_ips = nova_client.floating_ips.list()
150 print "Error [get_floating_ips(nova_client)]:", e
154 def create_flavor(nova_client, flavor_name, ram, disk, vcpus):
156 flavor = nova_client.flavors.create(flavor_name, ram, vcpus, disk)
158 print ("Error [create_flavor(nova_client, '%s', '%s', '%s', "
159 "'%s')]:" % (flavor_name, ram, disk, vcpus)), e
164 def create_floating_ip(neutron_client):
165 extnet_id = get_external_net_id(neutron_client)
166 props = {'floating_network_id': extnet_id}
168 ip_json = neutron_client.create_floatingip({'floatingip': props})
169 fip_addr = ip_json['floatingip']['floating_ip_address']
170 fip_id = ip_json['floatingip']['id']
172 print "Error [create_floating_ip(neutron_client)]:", e
174 return {'fip_addr': fip_addr, 'fip_id': fip_id}
177 def add_floating_ip(nova_client, server_id, floatingip_id):
179 nova_client.servers.add_floating_ip(server_id, floatingip_id)
182 print ("Error [add_floating_ip(nova_client, '%s', '%s')]:" %
183 (server_id, floatingip_id)), e
187 def delete_instance(nova_client, instance_id):
189 nova_client.servers.force_delete(instance_id)
192 print "Error [delete_instance(nova_client, '%s')]:" % instance_id, e
196 def delete_floating_ip(nova_client, floatingip_id):
198 nova_client.floating_ips.delete(floatingip_id)
201 print ("Error [delete_floating_ip(nova_client, '%s')]:" %
206 # *********************************************
208 # *********************************************
209 def get_network_list(neutron_client):
210 network_list = neutron_client.list_networks()['networks']
211 if len(network_list) == 0:
217 def get_router_list(neutron_client):
218 router_list = neutron_client.list_routers()['routers']
219 if len(router_list) == 0:
225 def get_port_list(neutron_client):
226 port_list = neutron_client.list_ports()['ports']
227 if len(port_list) == 0:
233 def get_network_id(neutron_client, network_name):
234 networks = neutron_client.list_networks()['networks']
237 if n['name'] == network_name:
243 def get_subnet_id(neutron_client, subnet_name):
244 subnets = neutron_client.list_subnets()['subnets']
247 if s['name'] == subnet_name:
253 def get_router_id(neutron_client, router_name):
254 routers = neutron_client.list_routers()['routers']
257 if r['name'] == router_name:
263 def get_private_net(neutron_client):
264 # Checks if there is an existing shared private network
265 networks = neutron_client.list_networks()['networks']
266 if len(networks) == 0:
269 if (net['router:external'] is False) and (net['shared'] is True):
274 def get_external_net(neutron_client):
275 for network in neutron_client.list_networks()['networks']:
276 if network['router:external']:
277 return network['name']
281 def get_external_net_id(neutron_client):
282 for network in neutron_client.list_networks()['networks']:
283 if network['router:external']:
288 def check_neutron_net(neutron_client, net_name):
289 for network in neutron_client.list_networks()['networks']:
290 if network['name'] == net_name:
291 for subnet in network['subnets']:
296 def create_neutron_net(neutron_client, name):
297 json_body = {'network': {'name': name,
298 'admin_state_up': True}}
300 network = neutron_client.create_network(body=json_body)
301 network_dict = network['network']
302 return network_dict['id']
304 print "Error [create_neutron_net(neutron_client, '%s')]:" % name, e
308 def create_neutron_subnet(neutron_client, name, cidr, net_id):
309 json_body = {'subnets': [{'name': name, 'cidr': cidr,
310 'ip_version': 4, 'network_id': net_id}]}
312 subnet = neutron_client.create_subnet(body=json_body)
313 return subnet['subnets'][0]['id']
315 print ("Error [create_neutron_subnet(neutron_client, '%s', '%s', "
316 "'%s')]:" % (name, cidr, net_id)), e
320 def create_neutron_router(neutron_client, name):
321 json_body = {'router': {'name': name, 'admin_state_up': True}}
323 router = neutron_client.create_router(json_body)
324 return router['router']['id']
326 print "Error [create_neutron_router(neutron_client, '%s')]:" % name, e
330 def create_neutron_port(neutron_client, name, network_id, ip):
331 json_body = {'port': {
332 'admin_state_up': True,
334 'network_id': network_id,
335 'fixed_ips': [{"ip_address": ip}]
338 port = neutron_client.create_port(body=json_body)
339 return port['port']['id']
341 print ("Error [create_neutron_port(neutron_client, '%s', '%s', "
342 "'%s')]:" % (name, network_id, ip)), e
346 def update_neutron_net(neutron_client, network_id, shared=False):
347 json_body = {'network': {'shared': shared}}
349 neutron_client.update_network(network_id, body=json_body)
352 print ("Error [update_neutron_net(neutron_client, '%s', '%s')]:" %
353 (network_id, str(shared))), e
357 def update_neutron_port(neutron_client, port_id, device_owner):
358 json_body = {'port': {
359 'device_owner': device_owner,
362 port = neutron_client.update_port(port=port_id,
364 return port['port']['id']
366 print ("Error [update_neutron_port(neutron_client, '%s', '%s')]:" %
367 (port_id, device_owner)), e
371 def add_interface_router(neutron_client, router_id, subnet_id):
372 json_body = {"subnet_id": subnet_id}
374 neutron_client.add_interface_router(router=router_id, body=json_body)
377 print ("Error [add_interface_router(neutron_client, '%s', '%s')]:" %
378 (router_id, subnet_id)), e
382 def add_gateway_router(neutron_client, router_id):
383 ext_net_id = get_external_net_id(neutron_client)
384 router_dict = {'network_id': ext_net_id}
386 neutron_client.add_gateway_router(router_id, router_dict)
389 print ("Error [add_gateway_router(neutron_client, '%s')]:" %
394 def delete_neutron_net(neutron_client, network_id):
396 neutron_client.delete_network(network_id)
399 print ("Error [delete_neutron_net(neutron_client, '%s')]:" %
404 def delete_neutron_subnet(neutron_client, subnet_id):
406 neutron_client.delete_subnet(subnet_id)
409 print ("Error [delete_neutron_subnet(neutron_client, '%s')]:" %
414 def delete_neutron_router(neutron_client, router_id):
416 neutron_client.delete_router(router=router_id)
419 print ("Error [delete_neutron_router(neutron_client, '%s')]:" %
424 def delete_neutron_port(neutron_client, port_id):
426 neutron_client.delete_port(port_id)
429 print "Error [delete_neutron_port(neutron_client, '%s')]:" % port_id, e
433 def remove_interface_router(neutron_client, router_id, subnet_id):
434 json_body = {"subnet_id": subnet_id}
436 neutron_client.remove_interface_router(router=router_id,
440 print ("Error [remove_interface_router(neutron_client, '%s', '%s')]:" %
441 (router_id, subnet_id)), e
445 def remove_gateway_router(neutron_client, router_id):
447 neutron_client.remove_gateway_router(router_id)
450 print ("Error [remove_gateway_router(neutron_client, '%s')]:" %
455 def create_network_full(logger,
462 # Check if the network already exists
463 network_id = get_network_id(neutron_client, net_name)
464 subnet_id = get_subnet_id(neutron_client, subnet_name)
465 router_id = get_router_id(neutron_client, router_name)
467 if network_id != '' and subnet_id != '' and router_id != '':
468 logger.info("A network with name '%s' already exists..." % net_name)
470 neutron_client.format = 'json'
471 logger.info('Creating neutron network %s...' % net_name)
472 network_id = create_neutron_net(neutron_client, net_name)
477 logger.debug("Network '%s' created successfully" % network_id)
478 logger.debug('Creating Subnet....')
479 subnet_id = create_neutron_subnet(neutron_client, subnet_name,
484 logger.debug("Subnet '%s' created successfully" % subnet_id)
485 logger.debug('Creating Router...')
486 router_id = create_neutron_router(neutron_client, router_name)
491 logger.debug("Router '%s' created successfully" % router_id)
492 logger.debug('Adding router to subnet...')
494 if not add_interface_router(neutron_client, router_id, subnet_id):
497 logger.debug("Interface added successfully.")
499 logger.debug('Adding gateway to router...')
500 if not add_gateway_router(neutron_client, router_id):
503 logger.debug("Gateway added successfully.")
505 network_dic = {'net_id': network_id,
506 'subnet_id': subnet_id,
507 'router_id': router_id}
511 # *********************************************
513 # *********************************************
514 def get_security_groups(neutron_client):
516 security_groups = neutron_client.list_security_groups()[
518 return security_groups
520 print "Error [get_security_groups(neutron_client)]:", e
524 def get_security_group_id(neutron_client, sg_name):
525 security_groups = get_security_groups(neutron_client)
527 for sg in security_groups:
528 if sg['name'] == sg_name:
534 def create_security_group(neutron_client, sg_name, sg_description):
535 json_body = {'security_group': {'name': sg_name,
536 'description': sg_description}}
538 secgroup = neutron_client.create_security_group(json_body)
539 return secgroup['security_group']
541 print ("Error [create_security_group(neutron_client, '%s', '%s')]:" %
542 (sg_name, sg_description)), e
546 def create_secgroup_rule(neutron_client, sg_id, direction, protocol,
547 port_range_min=None, port_range_max=None):
548 if port_range_min is None and port_range_max is None:
549 json_body = {'security_group_rule': {'direction': direction,
550 'security_group_id': sg_id,
551 'protocol': protocol}}
552 elif port_range_min is not None and port_range_max is not None:
553 json_body = {'security_group_rule': {'direction': direction,
554 'security_group_id': sg_id,
555 'port_range_min': port_range_min,
556 'port_range_max': port_range_max,
557 'protocol': protocol}}
559 print ("Error [create_secgroup_rule(neutron_client, '%s', '%s', "
560 "'%s', '%s', '%s', '%s')]:" % (neutron_client, sg_id, direction,
561 port_range_min, port_range_max,
563 " Invalid values for port_range_min, port_range_max")
566 neutron_client.create_security_group_rule(json_body)
569 print ("Error [create_secgroup_rule(neutron_client, '%s', '%s', "
570 "'%s', '%s', '%s', '%s')]:" % (neutron_client, sg_id, direction,
571 port_range_min, port_range_max,
576 def add_secgroup_to_instance(nova_client, instance_id, secgroup_id):
578 nova_client.servers.add_security_group(instance_id, secgroup_id)
581 print ("Error [add_secgroup_to_instance(nova_client, '%s', '%s')]: " %
582 (instance_id, secgroup_id)), e
586 def update_sg_quota(neutron_client, tenant_id, sg_quota, sg_rule_quota):
587 json_body = {"quota": {
588 "security_group": sg_quota,
589 "security_group_rule": sg_rule_quota
593 neutron_client.update_quota(tenant_id=tenant_id,
597 print ("Error [update_sg_quota(neutron_client, '%s', '%s', "
598 "'%s')]:" % (tenant_id, sg_quota, sg_rule_quota)), e
602 def delete_security_group(neutron_client, secgroup_id):
604 neutron_client.delete_security_group(secgroup_id)
607 print ("Error [delete_security_group(neutron_client, '%s')]:" %
612 # *********************************************
614 # *********************************************
615 def get_images(nova_client):
617 images = nova_client.images.list()
620 print "Error [get_images]:", e
624 def get_image_id(glance_client, image_name):
625 images = glance_client.images.list()
628 if i.name == image_name:
634 def create_glance_image(glance_client, image_name, file_path, public=True):
635 if not os.path.isfile(file_path):
636 print "Error: file " + file_path + " does not exist."
639 with open(file_path) as fimage:
640 image = glance_client.images.create(name=image_name,
643 container_format="bare",
647 print ("Error [create_glance_image(glance_client, '%s', '%s', "
648 "'%s')]:" % (image_name, file_path, str(public))), e
652 def delete_glance_image(nova_client, image_id):
654 nova_client.images.delete(image_id)
657 print ("Error [delete_glance_image(nova_client, '%s')]:" % image_id), e
661 # *********************************************
663 # *********************************************
664 def get_volumes(cinder_client):
666 volumes = cinder_client.volumes.list(search_opts={'all_tenants': 1})
669 print "Error [get_volumes(cinder_client)]:", e
673 def list_volume_types(cinder_client, public=True, private=True):
675 volume_types = cinder_client.volume_types.list()
677 volume_types = [vt for vt in volume_types if not vt.is_public]
679 volume_types = [vt for vt in volume_types if vt.is_public]
682 print "Error [list_volume_types(cinder_client)]:", e
686 def create_volume_type(cinder_client, name):
688 volume_type = cinder_client.volume_types.create(name)
691 print "Error [create_volume_type(cinder_client, '%s')]:" % name, e
695 def update_cinder_quota(cinder_client, tenant_id, vols_quota,
696 snapshots_quota, gigabytes_quota):
697 quotas_values = {"volumes": vols_quota,
698 "snapshots": snapshots_quota,
699 "gigabytes": gigabytes_quota}
702 cinder_client.quotas.update(tenant_id, **quotas_values)
705 print ("Error [update_cinder_quota(cinder_client, '%s', '%s', '%s'"
706 "'%s')]:" % (tenant_id, vols_quota,
707 snapshots_quota, gigabytes_quota)), e
711 def delete_volume(cinder_client, volume_id, forced=False):
715 cinder_client.volumes.detach(volume_id)
717 print "Error:", sys.exc_info()[0]
718 cinder_client.volumes.force_delete(volume_id)
720 cinder_client.volumes.delete(volume_id)
723 print ("Error [delete_volume(cinder_client, '%s', '%s')]:" %
724 (volume_id, str(forced))), e
728 def delete_volume_type(cinder_client, volume_type):
730 cinder_client.volume_types.delete(volume_type)
733 print ("Error [delete_volume_type(cinder_client, '%s')]:" %
738 # *********************************************
740 # *********************************************
741 def get_tenants(keystone_client):
743 tenants = keystone_client.tenants.list()
746 print "Error [get_tenants(keystone_client)]:", e
750 def get_users(keystone_client):
752 users = keystone_client.users.list()
755 print "Error [get_users(keystone_client)]:", e
759 def get_tenant_id(keystone_client, tenant_name):
760 tenants = keystone_client.tenants.list()
763 if t.name == tenant_name:
769 def get_user_id(keystone_client, user_name):
770 users = keystone_client.users.list()
773 if u.name == user_name:
779 def get_role_id(keystone_client, role_name):
780 roles = keystone_client.roles.list()
783 if r.name == role_name:
789 def create_tenant(keystone_client, tenant_name, tenant_description):
791 tenant = keystone_client.tenants.create(tenant_name,
796 print ("Error [create_tenant(cinder_client, '%s', '%s')]:" %
797 (tenant_name, tenant_description)), e
801 def create_user(keystone_client, user_name, user_password,
802 user_email, tenant_id):
804 user = keystone_client.users.create(user_name, user_password,
805 user_email, tenant_id,
809 print ("Error [create_user(keystone_client, '%s', '%s', '%s'"
810 "'%s')]:" % (user_name, user_password, user_email, tenant_id),
815 def add_role_user(keystone_client, user_id, role_id, tenant_id):
817 keystone_client.roles.add_user_role(user_id, role_id, tenant_id)
820 print ("Error [add_role_user(keystone_client, '%s', '%s'"
821 "'%s')]:" % (user_id, role_id, tenant_id)), e
825 def delete_tenant(keystone_client, tenant_id):
827 keystone_client.tenants.delete(tenant_id)
830 print "Error [delete_tenant(keystone_client, '%s')]:" % tenant_id, e
834 def delete_user(keystone_client, user_id):
836 keystone_client.users.delete(user_id)
839 print "Error [delete_user(keystone_client, '%s')]:" % user_id, e