2 from novaclient import client as novaclient
3 from neutronclient.v2_0 import client as neutronclient
6 def get_credentials(service): # pragma: no cover
7 """Returns a creds dictionary filled with the following keys:
9 * password/api_key (depending on the service)
10 * tenant_name/project_id (depending on the service)
12 :param service: a string indicating the name of the service
13 requesting the credentials.
16 # Unfortunately, each of the OpenStack client will request slightly
17 # different entries in their credentials dict.
18 if service.lower() in ("nova", "cinder"):
23 tenant = "tenant_name"
25 # The most common way to pass these info to the script is to do it through
26 # environment variables.
28 "username": os.environ.get('OS_USERNAME', "admin"),
29 password: os.environ.get("OS_PASSWORD", 'admin'),
30 "auth_url": os.environ.get("OS_AUTH_URL"),
31 tenant: os.environ.get("OS_TENANT_NAME", "admin"),
33 cacert = os.environ.get("OS_CACERT")
34 if cacert is not None:
35 # each openstack client uses differnt kwargs for this
36 creds.update({"cacert": cacert,
38 "https_ca_cert": cacert,
39 "https_cacert": cacert,
41 creds.update({"insecure": "True", "https_insecure": "True"})
42 if not os.path.isfile(cacert):
43 print ("WARNING: The 'OS_CACERT' environment variable is " +
44 "set to %s but the file does not exist." % cacert)
48 def get_instances(nova_client): # pragma: no cover
50 instances = nova_client.servers.list(search_opts={'all_tenants': 1})
53 print "Error [get_instances(nova_client)]:", e
57 def get_SFs(nova_client): # pragma: no cover
59 instances = get_instances(nova_client)
61 for instance in instances:
62 if "sfc_test" not in instance.name:
66 print "Error [get_SFs(nova_client)]:", e
70 def get_external_net_id(neutron_client): # pragma: no cover
71 for network in neutron_client.list_networks()['networks']:
72 if network['router:external']:
77 def create_floating_ips(neutron_client): # pragma: no cover
78 extnet_id = get_external_net_id(neutron_client)
80 props = {'floating_network_id': extnet_id}
83 ip_json = neutron_client.create_floatingip({'floatingip': props})
84 fip_addr = ip_json['floatingip']['floating_ip_address']
87 print "Error [create_floating_ip(neutron_client)]:", e
92 def floatIPtoSFs(SFs, floatips): # pragma: no cover
96 SF.add_floating_ip(floatips[i])
100 print ("Error [add_floating_ip(nova_client, '%s', '%s')]:" %
101 (SF, floatips[i]), e)
105 def get_an_IP(): # pragma: no cover
107 creds_nova = get_credentials("nova")
108 nova_client = novaclient.Client(version='2', **creds_nova)
109 creds_neutron = get_credentials("neutron")
110 neutron_client = neutronclient.Client(**creds_neutron)
111 SFs = get_SFs(nova_client)
112 floatips = create_floating_ips(neutron_client)
113 floatIPtoSFs(SFs, floatips)
116 if __name__ == '__main__': # pragma: no cover