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.
44 # Unfortunately, each of the OpenStack client will request slightly
45 # different entries in their credentials dict.
46 if service.lower() in ("nova", "cinder"):
51 tenant = "tenant_name"
53 # The most common way to pass these info to the script is to do it through
54 # environment variables.
56 "username": os.environ.get('OS_USERNAME', "admin"),
57 password: os.environ.get("OS_PASSWORD", 'admin'),
58 "auth_url": os.environ.get("OS_AUTH_URL",
59 "http://192.168.20.71:5000/v2.0"),
60 tenant: os.environ.get("OS_TENANT_NAME", "admin"),
62 cacert = os.environ.get("OS_CACERT")
63 if cacert is not None:
64 # each openstack client uses differnt kwargs for this
65 creds.update({"cacert": cacert,
67 "https_ca_cert": cacert,
68 "https_cacert": cacert,
70 creds.update({"insecure": "True", "https_insecure": "True"})
71 if not os.path.isfile(cacert):
72 print ("WARNING: The 'OS_CACERT' environment variable is " +
73 "set to %s but the file does not exist." % cacert)
77 def source_credentials(rc_file):
78 pipe = subprocess.Popen(". %s; env" % rc_file, stdout=subprocess.PIPE,
80 output = pipe.communicate()[0]
81 env = dict((line.split("=", 1) for line in output.splitlines()))
82 os.environ.update(env)
86 # *********************************************
88 # *********************************************
89 def get_instances(nova_client):
91 instances = nova_client.servers.list(search_opts={'all_tenants': 1})
94 print "Error [get_instances(nova_client)]:", e
98 def get_instance_status(nova_client, instance):
100 instance = nova_client.servers.get(instance.id)
101 return instance.status
103 # print ("Error [get_instance_status(nova_client, '%s')]:" %
108 def get_instance_by_name(nova_client, instance_name):
110 instance = nova_client.servers.find(name=instance_name)
113 print ("Error [get_instance_by_name(nova_client, '%s')]:" %
118 def get_flavor_id(nova_client, flavor_name):
119 flavors = nova_client.flavors.list(detailed=True)
122 if f.name == flavor_name:
128 def get_flavor_id_by_ram_range(nova_client, min_ram, max_ram):
129 flavors = nova_client.flavors.list(detailed=True)
132 if min_ram <= f.ram and f.ram <= max_ram:
138 def get_floating_ips(nova_client):
140 floating_ips = nova_client.floating_ips.list()
143 print "Error [get_floating_ips(nova_client)]:", e
147 def create_flavor(nova_client, flavor_name, ram, disk, vcpus):
149 flavor = nova_client.flavors.create(flavor_name, ram, vcpus, disk)
151 print ("Error [create_flavor(nova_client, '%s', '%s', '%s', "
152 "'%s')]:" % (flavor_name, ram, disk, vcpus)), e
157 def create_floating_ip(neutron_client):
158 extnet_id = get_external_net_id(neutron_client)
159 props = {'floating_network_id': extnet_id}
161 ip_json = neutron_client.create_floatingip({'floatingip': props})
162 fip_addr = ip_json['floatingip']['floating_ip_address']
163 fip_id = ip_json['floatingip']['id']
165 print "Error [create_floating_ip(neutron_client)]:", e
167 return {'fip_addr': fip_addr, 'fip_id': fip_id}
170 def add_floating_ip(nova_client, server_id, floatingip_id):
172 nova_client.servers.add_floating_ip(server_id, floatingip_id)
175 print ("Error [add_floating_ip(nova_client, '%s', '%s')]:" %
176 (server_id, floatingip_id)), e
180 def delete_instance(nova_client, instance_id):
182 nova_client.servers.force_delete(instance_id)
185 print "Error [delete_instance(nova_client, '%s')]:" % instance_id, e
189 def delete_floating_ip(nova_client, floatingip_id):
191 nova_client.floating_ips.delete(floatingip_id)
194 print ("Error [delete_floating_ip(nova_client, '%s')]:" %
199 # *********************************************
201 # *********************************************
202 def get_network_list(neutron_client):
203 network_list = neutron_client.list_networks()['networks']
204 if len(network_list) == 0:
210 def get_router_list(neutron_client):
211 router_list = neutron_client.list_routers()['routers']
212 if len(router_list) == 0:
218 def get_port_list(neutron_client):
219 port_list = neutron_client.list_ports()['ports']
220 if len(port_list) == 0:
226 def get_network_id(neutron_client, network_name):
227 networks = neutron_client.list_networks()['networks']
230 if n['name'] == network_name:
236 def get_subnet_id(neutron_client, subnet_name):
237 subnets = neutron_client.list_subnets()['subnets']
240 if s['name'] == subnet_name:
246 def get_router_id(neutron_client, router_name):
247 routers = neutron_client.list_routers()['routers']
250 if r['name'] == router_name:
256 def get_private_net(neutron_client):
257 # Checks if there is an existing shared private network
258 networks = neutron_client.list_networks()['networks']
259 if len(networks) == 0:
262 if (net['router:external'] is False) and (net['shared'] is True):
267 def get_external_net(neutron_client):
268 for network in neutron_client.list_networks()['networks']:
269 if network['router:external']:
270 return network['name']
274 def get_external_net_id(neutron_client):
275 for network in neutron_client.list_networks()['networks']:
276 if network['router:external']:
281 def check_neutron_net(neutron_client, net_name):
282 for network in neutron_client.list_networks()['networks']:
283 if network['name'] == net_name:
284 for subnet in network['subnets']:
289 def create_neutron_net(neutron_client, name):
290 json_body = {'network': {'name': name,
291 'admin_state_up': True}}
293 network = neutron_client.create_network(body=json_body)
294 network_dict = network['network']
295 return network_dict['id']
297 print "Error [create_neutron_net(neutron_client, '%s')]:" % name, e
301 def create_neutron_subnet(neutron_client, name, cidr, net_id):
302 json_body = {'subnets': [{'name': name, 'cidr': cidr,
303 'ip_version': 4, 'network_id': net_id}]}
305 subnet = neutron_client.create_subnet(body=json_body)
306 return subnet['subnets'][0]['id']
308 print ("Error [create_neutron_subnet(neutron_client, '%s', '%s', "
309 "'%s')]:" % (name, cidr, net_id)), e
313 def create_neutron_router(neutron_client, name):
314 json_body = {'router': {'name': name, 'admin_state_up': True}}
316 router = neutron_client.create_router(json_body)
317 return router['router']['id']
319 print "Error [create_neutron_router(neutron_client, '%s')]:" % name, e
323 def create_neutron_port(neutron_client, name, network_id, ip):
324 json_body = {'port': {
325 'admin_state_up': True,
327 'network_id': network_id,
328 'fixed_ips': [{"ip_address": ip}]
331 port = neutron_client.create_port(body=json_body)
332 return port['port']['id']
334 print ("Error [create_neutron_port(neutron_client, '%s', '%s', "
335 "'%s')]:" % (name, network_id, ip)), e
339 def update_neutron_net(neutron_client, network_id, shared=False):
340 json_body = {'network': {'shared': shared}}
342 neutron_client.update_network(network_id, body=json_body)
345 print ("Error [update_neutron_net(neutron_client, '%s', '%s')]:" %
346 (network_id, str(shared))), e
350 def update_neutron_port(neutron_client, port_id, device_owner):
351 json_body = {'port': {
352 'device_owner': device_owner,
355 port = neutron_client.update_port(port=port_id,
357 return port['port']['id']
359 print ("Error [update_neutron_port(neutron_client, '%s', '%s')]:" %
360 (port_id, device_owner)), e
364 def add_interface_router(neutron_client, router_id, subnet_id):
365 json_body = {"subnet_id": subnet_id}
367 neutron_client.add_interface_router(router=router_id, body=json_body)
370 print ("Error [add_interface_router(neutron_client, '%s', '%s')]:" %
371 (router_id, subnet_id)), e
375 def add_gateway_router(neutron_client, router_id):
376 ext_net_id = get_external_net_id(neutron_client)
377 router_dict = {'network_id': ext_net_id}
379 neutron_client.add_gateway_router(router_id, router_dict)
382 print ("Error [add_gateway_router(neutron_client, '%s')]:" %
387 def delete_neutron_net(neutron_client, network_id):
389 neutron_client.delete_network(network_id)
392 print ("Error [delete_neutron_net(neutron_client, '%s')]:" %
397 def delete_neutron_subnet(neutron_client, subnet_id):
399 neutron_client.delete_subnet(subnet_id)
402 print ("Error [delete_neutron_subnet(neutron_client, '%s')]:" %
407 def delete_neutron_router(neutron_client, router_id):
409 neutron_client.delete_router(router=router_id)
412 print ("Error [delete_neutron_router(neutron_client, '%s')]:" %
417 def delete_neutron_port(neutron_client, port_id):
419 neutron_client.delete_port(port_id)
422 print "Error [delete_neutron_port(neutron_client, '%s')]:" % port_id, e
426 def remove_interface_router(neutron_client, router_id, subnet_id):
427 json_body = {"subnet_id": subnet_id}
429 neutron_client.remove_interface_router(router=router_id,
433 print ("Error [remove_interface_router(neutron_client, '%s', '%s')]:" %
434 (router_id, subnet_id)), e
438 def remove_gateway_router(neutron_client, router_id):
440 neutron_client.remove_gateway_router(router_id)
443 print ("Error [remove_gateway_router(neutron_client, '%s')]:" %
448 def create_network_full(logger,
455 # Check if the network already exists
456 network_id = get_network_id(neutron_client, net_name)
457 subnet_id = get_subnet_id(neutron_client, subnet_name)
458 router_id = get_router_id(neutron_client, router_name)
460 if network_id != '' and subnet_id != '' and router_id != '':
461 logger.info("A network with name '%s' already exists..." % net_name)
463 neutron_client.format = 'json'
464 logger.info('Creating neutron network %s...' % net_name)
465 network_id = create_neutron_net(neutron_client, net_name)
470 logger.debug("Network '%s' created successfully" % network_id)
471 logger.debug('Creating Subnet....')
472 subnet_id = create_neutron_subnet(neutron_client, subnet_name,
477 logger.debug("Subnet '%s' created successfully" % subnet_id)
478 logger.debug('Creating Router...')
479 router_id = create_neutron_router(neutron_client, router_name)
484 logger.debug("Router '%s' created successfully" % router_id)
485 logger.debug('Adding router to subnet...')
487 if not add_interface_router(neutron_client, router_id, subnet_id):
490 logger.debug("Interface added successfully.")
492 logger.debug('Adding gateway to router...')
493 if not add_gateway_router(neutron_client, router_id):
496 logger.debug("Gateway added successfully.")
498 network_dic = {'net_id': network_id,
499 'subnet_id': subnet_id,
500 'router_id': router_id}
504 # *********************************************
506 # *********************************************
507 def get_security_groups(neutron_client):
509 security_groups = neutron_client.list_security_groups()[
511 return security_groups
513 print "Error [get_security_groups(neutron_client)]:", e
517 def get_security_group_id(neutron_client, sg_name):
518 security_groups = get_security_groups(neutron_client)
520 for sg in security_groups:
521 if sg['name'] == sg_name:
527 def create_security_group(neutron_client, sg_name, sg_description):
528 json_body = {'security_group': {'name': sg_name,
529 'description': sg_description}}
531 secgroup = neutron_client.create_security_group(json_body)
532 return secgroup['security_group']
534 print ("Error [create_security_group(neutron_client, '%s', '%s')]:" %
535 (sg_name, sg_description)), e
539 def create_secgroup_rule(neutron_client, sg_id, direction, protocol,
540 port_range_min=None, port_range_max=None):
541 if port_range_min is None and port_range_max is None:
542 json_body = {'security_group_rule': {'direction': direction,
543 'security_group_id': sg_id,
544 'protocol': protocol}}
545 elif port_range_min is not None and port_range_max is not None:
546 json_body = {'security_group_rule': {'direction': direction,
547 'security_group_id': sg_id,
548 'port_range_min': port_range_min,
549 'port_range_max': port_range_max,
550 'protocol': protocol}}
552 print ("Error [create_secgroup_rule(neutron_client, '%s', '%s', "
553 "'%s', '%s', '%s', '%s')]:" % (neutron_client, sg_id, direction,
554 port_range_min, port_range_max,
556 " Invalid values for port_range_min, port_range_max")
559 neutron_client.create_security_group_rule(json_body)
562 print ("Error [create_secgroup_rule(neutron_client, '%s', '%s', "
563 "'%s', '%s', '%s', '%s')]:" % (neutron_client, sg_id, direction,
564 port_range_min, port_range_max,
569 def add_secgroup_to_instance(nova_client, instance_id, secgroup_id):
571 nova_client.servers.add_security_group(instance_id, secgroup_id)
574 print ("Error [add_secgroup_to_instance(nova_client, '%s', '%s')]: " %
575 (instance_id, secgroup_id)), e
579 def update_sg_quota(neutron_client, tenant_id, sg_quota, sg_rule_quota):
580 json_body = {"quota": {
581 "security_group": sg_quota,
582 "security_group_rule": sg_rule_quota
586 neutron_client.update_quota(tenant_id=tenant_id,
590 print ("Error [update_sg_quota(neutron_client, '%s', '%s', "
591 "'%s')]:" % (tenant_id, sg_quota, sg_rule_quota)), e
595 def delete_security_group(neutron_client, secgroup_id):
597 neutron_client.delete_security_group(secgroup_id)
600 print ("Error [delete_security_group(neutron_client, '%s')]:" %
605 # *********************************************
607 # *********************************************
608 def get_images(nova_client):
610 images = nova_client.images.list()
613 print "Error [get_images]:", e
617 def get_image_id(glance_client, image_name):
618 images = glance_client.images.list()
621 if i.name == image_name:
627 def create_glance_image(glance_client, image_name, file_path, public=True):
628 if not os.path.isfile(file_path):
629 print "Error: file " + file_path + " does not exist."
632 with open(file_path) as fimage:
633 image = glance_client.images.create(name=image_name,
636 container_format="bare",
640 print ("Error [create_glance_image(glance_client, '%s', '%s', "
641 "'%s')]:" % (image_name, file_path, str(public))), e
645 def delete_glance_image(nova_client, image_id):
647 nova_client.images.delete(image_id)
650 print ("Error [delete_glance_image(nova_client, '%s')]:" % image_id), e
654 # *********************************************
656 # *********************************************
657 def get_volumes(cinder_client):
659 volumes = cinder_client.volumes.list(search_opts={'all_tenants': 1})
662 print "Error [get_volumes(cinder_client)]:", e
666 def list_volume_types(cinder_client, public=True, private=True):
668 volume_types = cinder_client.volume_types.list()
670 volume_types = [vt for vt in volume_types if not vt.is_public]
672 volume_types = [vt for vt in volume_types if vt.is_public]
675 print "Error [list_volume_types(cinder_client)]:", e
679 def create_volume_type(cinder_client, name):
681 volume_type = cinder_client.volume_types.create(name)
684 print "Error [create_volume_type(cinder_client, '%s')]:" % name, e
688 def update_cinder_quota(cinder_client, tenant_id, vols_quota,
689 snapshots_quota, gigabytes_quota):
690 quotas_values = {"volumes": vols_quota,
691 "snapshots": snapshots_quota,
692 "gigabytes": gigabytes_quota}
695 cinder_client.quotas.update(tenant_id, **quotas_values)
698 print ("Error [update_cinder_quota(cinder_client, '%s', '%s', '%s'"
699 "'%s')]:" % (tenant_id, vols_quota,
700 snapshots_quota, gigabytes_quota)), e
704 def delete_volume(cinder_client, volume_id, forced=False):
708 cinder_client.volumes.detach(volume_id)
710 print "Error:", sys.exc_info()[0]
711 cinder_client.volumes.force_delete(volume_id)
713 cinder_client.volumes.delete(volume_id)
716 print ("Error [delete_volume(cinder_client, '%s', '%s')]:" %
717 (volume_id, str(forced))), e
721 def delete_volume_type(cinder_client, volume_type):
723 cinder_client.volume_types.delete(volume_type)
726 print ("Error [delete_volume_type(cinder_client, '%s')]:" %
731 # *********************************************
733 # *********************************************
734 def get_tenants(keystone_client):
736 tenants = keystone_client.tenants.list()
739 print "Error [get_tenants(keystone_client)]:", e
743 def get_users(keystone_client):
745 users = keystone_client.users.list()
748 print "Error [get_users(keystone_client)]:", e
752 def get_tenant_id(keystone_client, tenant_name):
753 tenants = keystone_client.tenants.list()
756 if t.name == tenant_name:
762 def get_user_id(keystone_client, user_name):
763 users = keystone_client.users.list()
766 if u.name == user_name:
772 def get_role_id(keystone_client, role_name):
773 roles = keystone_client.roles.list()
776 if r.name == role_name:
782 def create_tenant(keystone_client, tenant_name, tenant_description):
784 tenant = keystone_client.tenants.create(tenant_name,
789 print ("Error [create_tenant(cinder_client, '%s', '%s')]:" %
790 (tenant_name, tenant_description)), e
794 def create_user(keystone_client, user_name, user_password,
795 user_email, tenant_id):
797 user = keystone_client.users.create(user_name, user_password,
798 user_email, tenant_id,
802 print ("Error [create_user(keystone_client, '%s', '%s', '%s'"
803 "'%s')]:" % (user_name, user_password, user_email, tenant_id),
808 def add_role_user(keystone_client, user_id, role_id, tenant_id):
810 keystone_client.roles.add_user_role(user_id, role_id, tenant_id)
813 print ("Error [add_role_user(keystone_client, '%s', '%s'"
814 "'%s')]:" % (user_id, role_id, tenant_id)), e
818 def delete_tenant(keystone_client, tenant_id):
820 keystone_client.tenants.delete(tenant_id)
823 print "Error [delete_tenant(keystone_client, '%s')]:" % tenant_id, e
827 def delete_user(keystone_client, user_id):
829 keystone_client.users.delete(user_id)
832 print "Error [delete_user(keystone_client, '%s')]:" % user_id, e