3 # Copyright (c) 2016 Cable Television Laboratories, Inc. ("CableLabs")
4 # and others. All rights reserved.
6 # Licensed under the Apache License, Version 2.0 (the "License");
7 # you may not use this file except in compliance with the License.
8 # You may obtain a copy of the License at:
10 # http://www.apache.org/licenses/LICENSE-2.0
12 # Unless required by applicable law or agreed to in writing, software
13 # distributed under the License is distributed on an "AS IS" BASIS,
14 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 # See the License for the specific language governing permissions and
16 # limitations under the License.
18 # This script is responsible for deploying virtual environments
24 from snaps import file_utils
25 from snaps.openstack.create_flavor import FlavorSettings, OpenStackFlavor
26 from snaps.openstack.create_image import ImageSettings
27 from snaps.openstack.create_instance import VmInstanceSettings
28 from snaps.openstack.create_network import PortSettings, NetworkSettings
29 from snaps.openstack.create_router import RouterSettings
30 from snaps.openstack.create_keypairs import KeypairSettings
31 from snaps.openstack.os_credentials import OSCreds, ProxySettings
32 from snaps.openstack.utils import deploy_utils
33 from snaps.provisioning import ansible_utils
35 __author__ = 'spisarski'
37 logger = logging.getLogger('deploy_venv')
39 ARG_NOT_SET = "argument not set"
42 def __get_os_credentials(os_conn_config):
44 Returns an object containing all of the information required to access OpenStack APIs
45 :param os_conn_config: The configuration holding the credentials
46 :return: an OSCreds instance
49 http_proxy = os_conn_config.get('http_proxy')
51 tokens = re.split(':', http_proxy)
52 ssh_proxy_cmd = os_conn_config.get('ssh_proxy_cmd')
53 proxy_settings = ProxySettings(tokens[0], tokens[1], ssh_proxy_cmd)
55 return OSCreds(username=os_conn_config.get('username'),
56 password=os_conn_config.get('password'),
57 auth_url=os_conn_config.get('auth_url'),
58 project_name=os_conn_config.get('project_name'),
59 proxy_settings=proxy_settings)
62 def __parse_ports_config(config):
64 Parses the "ports" configuration
65 :param config: The dictionary to parse
66 :param os_creds: The OpenStack credentials object
67 :return: a list of PortConfig objects
70 for port_config in config:
71 out.append(PortSettings(config=port_config.get('port')))
75 def __create_flavors(os_conn_config, flavors_config, cleanup=False):
77 Returns a dictionary of flavors where the key is the image name and the value is the image object
78 :param os_conn_config: The OpenStack connection credentials
79 :param flavors_config: The list of image configurations
80 :param cleanup: Denotes whether or not this is being called for cleanup or not
87 for flavor_config_dict in flavors_config:
88 flavor_config = flavor_config_dict.get('flavor')
89 if flavor_config and flavor_config.get('name'):
90 flavor_creator = OpenStackFlavor(__get_os_credentials(os_conn_config),
91 FlavorSettings(flavor_config))
92 flavor_creator.create(cleanup=cleanup)
93 flavors[flavor_config['name']] = flavor_creator
94 except Exception as e:
95 for key, flavor_creator in flavors.iteritems():
96 flavor_creator.clean()
98 logger.info('Created configured flavors')
103 def __create_images(os_conn_config, images_config, cleanup=False):
105 Returns a dictionary of images where the key is the image name and the value is the image object
106 :param os_conn_config: The OpenStack connection credentials
107 :param images_config: The list of image configurations
108 :param cleanup: Denotes whether or not this is being called for cleanup or not
115 for image_config_dict in images_config:
116 image_config = image_config_dict.get('image')
117 if image_config and image_config.get('name'):
118 images[image_config['name']] = deploy_utils.create_image(__get_os_credentials(os_conn_config),
119 ImageSettings(image_config), cleanup)
120 except Exception as e:
121 for key, image_creator in images.iteritems():
122 image_creator.clean()
124 logger.info('Created configured images')
129 def __create_networks(os_conn_config, network_confs, cleanup=False):
131 Returns a dictionary of networks where the key is the network name and the value is the network object
132 :param os_conn_config: The OpenStack connection credentials
133 :param network_confs: The list of network configurations
134 :param cleanup: Denotes whether or not this is being called for cleanup or not
141 for network_conf in network_confs:
142 net_name = network_conf['network']['name']
143 os_creds = __get_os_credentials(os_conn_config)
144 network_dict[net_name] = deploy_utils.create_network(
145 os_creds, NetworkSettings(config=network_conf['network']), cleanup)
146 except Exception as e:
147 for key, net_creator in network_dict.iteritems():
151 logger.info('Created configured networks')
156 def __create_routers(os_conn_config, router_confs, cleanup=False):
158 Returns a dictionary of networks where the key is the network name and the value is the network object
159 :param os_conn_config: The OpenStack connection credentials
160 :param router_confs: The list of router configurations
161 :param cleanup: Denotes whether or not this is being called for cleanup or not
165 os_creds = __get_os_credentials(os_conn_config)
169 for router_conf in router_confs:
170 router_name = router_conf['router']['name']
171 router_dict[router_name] = deploy_utils.create_router(
172 os_creds, RouterSettings(config=router_conf['router']), cleanup)
173 except Exception as e:
174 for key, router_creator in router_dict.iteritems():
175 router_creator.clean()
178 logger.info('Created configured networks')
183 def __create_keypairs(os_conn_config, keypair_confs, cleanup=False):
185 Returns a dictionary of keypairs where the key is the keypair name and the value is the keypair object
186 :param os_conn_config: The OpenStack connection credentials
187 :param keypair_confs: The list of keypair configurations
188 :param cleanup: Denotes whether or not this is being called for cleanup or not
194 for keypair_dict in keypair_confs:
195 keypair_config = keypair_dict['keypair']
196 kp_settings = KeypairSettings(keypair_config)
197 keypairs_dict[keypair_config['name']] = deploy_utils.create_keypair(
198 __get_os_credentials(os_conn_config), kp_settings, cleanup)
199 except Exception as e:
200 for key, keypair_creator in keypairs_dict.iteritems():
201 keypair_creator.clean()
204 logger.info('Created configured keypairs')
209 def __create_instances(os_conn_config, instances_config, image_dict, keypairs_dict, cleanup=False):
211 Returns a dictionary of instances where the key is the instance name and the value is the VM object
212 :param os_conn_config: The OpenStack connection credentials
213 :param instances_config: The list of VM instance configurations
214 :param image_dict: A dictionary of images that will probably be used to instantiate the VM instance
215 :param keypairs_dict: A dictionary of keypairs that will probably be used to instantiate the VM instance
216 :param cleanup: Denotes whether or not this is being called for cleanup or not
219 os_creds = __get_os_credentials(os_conn_config)
225 for instance_config in instances_config:
226 conf = instance_config.get('instance')
229 image_creator = image_dict.get(conf.get('imageName'))
231 instance_settings = VmInstanceSettings(config=instance_config['instance'])
232 kp_name = conf.get('keypair_name')
233 vm_dict[conf['name']] = deploy_utils.create_vm_instance(
234 os_creds, instance_settings, image_creator.image_settings,
235 keypair_creator=keypairs_dict[kp_name], cleanup=cleanup)
237 raise Exception('Image creator instance not found. Cannot instantiate')
239 raise Exception('Image dictionary is None. Cannot instantiate')
241 raise Exception('Instance configuration is None. Cannot instantiate')
242 except Exception as e:
243 logger.error('Unexpected error creating instances. Attempting to cleanup environment - ' + e.message)
244 for key, inst_creator in vm_dict.iteritems():
248 logger.info('Created configured instances')
253 def __apply_ansible_playbooks(ansible_configs, os_conn_config, vm_dict, image_dict, flavor_dict, env_file):
255 Applies ansible playbooks to running VMs with floating IPs
256 :param ansible_configs: a list of Ansible configurations
257 :param os_conn_config: the OpenStack connection configuration used to create an OSCreds instance
258 :param vm_dict: the dictionary of newly instantiated VMs where the name is the key
259 :param image_dict: the dictionary of newly instantiated images where the name is the key
260 :param flavor_dict: the dictionary of newly instantiated flavors where the name is the key
261 :param env_file: the path of the environment for setting the CWD so playbook location is relative to the deployment
263 :return: t/f - true if successful
265 logger.info("Applying Ansible Playbooks")
267 # Ensure all hosts are accepting SSH session requests
268 for vm_inst in vm_dict.values():
269 if not vm_inst.vm_ssh_active(block=True):
270 logger.warn("Timeout waiting for instance to respond to SSH requests")
273 # Set CWD so the deployment file's playbook location can leverage relative paths
274 orig_cwd = os.getcwd()
275 env_dir = os.path.dirname(env_file)
279 for ansible_config in ansible_configs:
280 os_creds = __get_os_credentials(os_conn_config)
281 __apply_ansible_playbook(ansible_config, os_creds, vm_dict, image_dict, flavor_dict)
283 # Return to original directory
289 def __apply_ansible_playbook(ansible_config, os_creds, vm_dict, image_dict, flavor_dict):
291 Applies an Ansible configuration setting
292 :param ansible_config: the configuration settings
293 :param os_creds: the OpenStack credentials object
294 :param vm_dict: the dictionary of newly instantiated VMs where the name is the key
295 :param image_dict: the dictionary of newly instantiated images where the name is the key
296 :param flavor_dict: the dictionary of newly instantiated flavors where the name is the key
299 remote_user, floating_ips, private_key_filepath, proxy_settings = __get_connection_info(ansible_config, vm_dict)
301 retval = ansible_utils.apply_playbook(
302 ansible_config['playbook_location'], floating_ips, remote_user, private_key_filepath,
303 variables=__get_variables(ansible_config.get('variables'), os_creds, vm_dict, image_dict, flavor_dict),
304 proxy_setting=proxy_settings)
306 # Not a fatal type of event
307 logger.warn('Unable to apply playbook found at location - ' + ansible_config('playbook_location'))
310 def __get_connection_info(ansible_config, vm_dict):
312 Returns a tuple of data required for connecting to the running VMs
313 (remote_user, [floating_ips], private_key_filepath, proxy_settings)
314 :param ansible_config: the configuration settings
315 :param vm_dict: the dictionary of VMs where the VM name is the key
316 :return: tuple where the first element is the user and the second is a list of floating IPs and the third is the
317 private key file location and the fourth is an instance of the snaps.ProxySettings class
318 (note: in order to work, each of the hosts need to have the same sudo_user and private key file location values)
320 if ansible_config.get('hosts'):
321 hosts = ansible_config['hosts']
323 floating_ips = list()
325 private_key_filepath = None
326 proxy_settings = None
328 vm = vm_dict.get(host)
330 fip = vm.get_floating_ip()
332 remote_user = vm.get_image_user()
335 floating_ips.append(fip.ip)
337 raise Exception('Could not find floating IP for VM - ' + vm.name)
339 private_key_filepath = vm.keypair_settings.private_filepath
340 proxy_settings = vm.get_os_creds().proxy_settings
342 logger.error('Could not locate VM with name - ' + host)
344 return remote_user, floating_ips, private_key_filepath, proxy_settings
348 def __get_variables(var_config, os_creds, vm_dict, image_dict, flavor_dict):
350 Returns a dictionary of substitution variables to be used for Ansible templates
351 :param var_config: the variable configuration settings
352 :param os_creds: the OpenStack credentials object
353 :param vm_dict: the dictionary of newly instantiated VMs where the name is the key
354 :param image_dict: the dictionary of newly instantiated images where the name is the key
355 :param flavor_dict: the dictionary of newly instantiated flavors where the name is the key
356 :return: dictionary or None
358 if var_config and vm_dict and len(vm_dict) > 0:
360 for key, value in var_config.iteritems():
361 value = __get_variable_value(value, os_creds, vm_dict, image_dict, flavor_dict)
363 variables[key] = value
364 logger.info("Set Jinga2 variable with key [" + key + "] the value [" + value + ']')
366 logger.warn('Key [' + str(key) + '] or Value [' + str(value) + '] must not be None')
371 def __get_variable_value(var_config_values, os_creds, vm_dict, image_dict, flavor_dict):
373 Returns the associated variable value for use by Ansible for substitution purposes
374 :param var_config_values: the configuration dictionary
375 :param os_creds: the OpenStack credentials object
376 :param vm_dict: the dictionary of newly instantiated VMs where the name is the key
377 :param image_dict: the dictionary of newly instantiated images where the name is the key
378 :param flavor_dict: the dictionary of newly instantiated flavors where the name is the key
381 if var_config_values['type'] == 'string':
382 return __get_string_variable_value(var_config_values)
383 if var_config_values['type'] == 'vm-attr':
384 return __get_vm_attr_variable_value(var_config_values, vm_dict)
385 if var_config_values['type'] == 'os_creds':
386 return __get_os_creds_variable_value(var_config_values, os_creds)
387 if var_config_values['type'] == 'port':
388 return __get_vm_port_variable_value(var_config_values, vm_dict)
389 if var_config_values['type'] == 'image':
390 return __get_image_variable_value(var_config_values, image_dict)
391 if var_config_values['type'] == 'flavor':
392 return __get_flavor_variable_value(var_config_values, flavor_dict)
396 def __get_string_variable_value(var_config_values):
398 Returns the associated string value
399 :param var_config_values: the configuration dictionary
400 :return: the value contained in the dictionary with the key 'value'
402 return var_config_values['value']
405 def __get_vm_attr_variable_value(var_config_values, vm_dict):
407 Returns the associated value contained on a VM instance
408 :param var_config_values: the configuration dictionary
409 :param vm_dict: the dictionary containing all VMs where the key is the VM's name
412 vm = vm_dict.get(var_config_values['vm_name'])
414 if var_config_values['value'] == 'floating_ip':
415 return vm.get_floating_ip().ip
416 if var_config_values['value'] == 'image_user':
417 return vm.get_image_user()
420 def __get_os_creds_variable_value(var_config_values, os_creds):
422 Returns the associated OS credentials value
423 :param var_config_values: the configuration dictionary
424 :param os_creds: the credentials
427 logger.info("Retrieving OS Credentials")
429 if var_config_values['value'] == 'username':
430 logger.info("Returning OS username")
431 return os_creds.username
432 elif var_config_values['value'] == 'password':
433 logger.info("Returning OS password")
434 return os_creds.password
435 elif var_config_values['value'] == 'auth_url':
436 logger.info("Returning OS auth_url")
437 return os_creds.auth_url
438 elif var_config_values['value'] == 'project_name':
439 logger.info("Returning OS project_name")
440 return os_creds.project_name
442 logger.info("Returning none")
446 def __get_vm_port_variable_value(var_config_values, vm_dict):
448 Returns the associated OS credentials value
449 :param var_config_values: the configuration dictionary
450 :param vm_dict: the dictionary containing all VMs where the key is the VM's name
453 port_name = var_config_values.get('port_name')
454 vm_name = var_config_values.get('vm_name')
456 if port_name and vm_name:
457 vm = vm_dict.get(vm_name)
459 port_value_id = var_config_values.get('port_value')
461 if port_value_id == 'mac_address':
462 return vm.get_port_mac(port_name)
463 if port_value_id == 'ip_address':
464 return vm.get_port_ip(port_name)
467 def __get_image_variable_value(var_config_values, image_dict):
469 Returns the associated image value
470 :param var_config_values: the configuration dictionary
471 :param image_dict: the dictionary containing all images where the key is the name
474 logger.info("Retrieving image values")
477 if var_config_values.get('image_name'):
478 image_creator = image_dict.get(var_config_values['image_name'])
480 if var_config_values.get('value') and var_config_values['value'] == 'id':
481 return image_creator.get_image().id
482 if var_config_values.get('value') and var_config_values['value'] == 'user':
483 return image_creator.image_settings.image_user
485 logger.info("Returning none")
489 def __get_flavor_variable_value(var_config_values, flavor_dict):
491 Returns the associated flavor value
492 :param var_config_values: the configuration dictionary
493 :param flavor_dict: the dictionary containing all flavor creators where the key is the name
494 :return: the value or None
496 logger.info("Retrieving flavor values")
499 if var_config_values.get('flavor_name'):
500 flavor_creator = flavor_dict.get(var_config_values['flavor_name'])
502 if var_config_values.get('value') and var_config_values['value'] == 'id':
503 return flavor_creator.get_flavor().id
505 logger.info("Returning none")
511 Will need to set environment variable ANSIBLE_HOST_KEY_CHECKING=False or ...
512 Create a file located in /etc/ansible/ansible/cfg or ~/.ansible.cfg containing the following content:
515 host_key_checking = False
517 CWD must be this directory where this script is located.
521 log_level = logging.INFO
522 if arguments.log_level != 'INFO':
523 log_level = logging.DEBUG
524 logging.basicConfig(level=log_level)
526 logger.info('Starting to Deploy')
527 config = file_utils.read_yaml(arguments.environment)
528 logger.info('Read configuration file - ' + arguments.environment)
531 os_config = config.get('openstack')
541 os_conn_config = os_config.get('connection')
544 flavor_dict = __create_flavors(os_conn_config, os_config.get('flavors'),
545 arguments.clean is not ARG_NOT_SET)
548 image_dict = __create_images(os_conn_config, os_config.get('images'),
549 arguments.clean is not ARG_NOT_SET)
552 network_dict = __create_networks(os_conn_config, os_config.get('networks'),
553 arguments.clean is not ARG_NOT_SET)
556 router_dict = __create_routers(os_conn_config, os_config.get('routers'),
557 arguments.clean is not ARG_NOT_SET)
560 keypairs_dict = __create_keypairs(os_conn_config, os_config.get('keypairs'),
561 arguments.clean is not ARG_NOT_SET)
564 vm_dict = __create_instances(os_conn_config, os_config.get('instances'), image_dict, keypairs_dict,
565 arguments.clean is not ARG_NOT_SET)
566 logger.info('Completed creating/retrieving all configured instances')
567 except Exception as e:
568 logger.error('Unexpected error deploying environment. Rolling back due to - ' + e.message)
569 __cleanup(vm_dict, keypairs_dict, router_dict, network_dict, image_dict, flavor_dict, True)
573 # Must enter either block
574 if arguments.clean is not ARG_NOT_SET:
575 # Cleanup Environment
576 __cleanup(vm_dict, keypairs_dict, router_dict, network_dict, image_dict, flavor_dict,
577 arguments.clean_image is not ARG_NOT_SET)
578 elif arguments.deploy is not ARG_NOT_SET:
579 logger.info('Configuring NICs where required')
580 for vm in vm_dict.itervalues():
582 logger.info('Completed NIC configuration')
585 ansible_config = config.get('ansible')
586 if ansible_config and vm_dict:
587 if not __apply_ansible_playbooks(ansible_config, os_conn_config, vm_dict, image_dict, flavor_dict,
588 arguments.environment):
589 logger.error("Problem applying ansible playbooks")
591 logger.error('Unable to read configuration file - ' + arguments.environment)
597 def __cleanup(vm_dict, keypairs_dict, router_dict, network_dict, image_dict, flavor_dict, clean_image=False):
598 for key, vm_inst in vm_dict.iteritems():
600 for key, kp_inst in keypairs_dict.iteritems():
602 for key, router_inst in router_dict.iteritems():
604 for key, net_inst in network_dict.iteritems():
607 for key, image_inst in image_dict.iteritems():
609 for key, flavor_inst in flavor_dict.iteritems():
613 if __name__ == '__main__':
614 # To ensure any files referenced via a relative path will begin from the diectory in which this file resides
615 os.chdir(os.path.dirname(os.path.realpath(__file__)))
617 parser = argparse.ArgumentParser()
618 parser.add_argument('-d', '--deploy', dest='deploy', nargs='?', default=ARG_NOT_SET,
619 help='When used, environment will be deployed and provisioned')
620 parser.add_argument('-c', '--clean', dest='clean', nargs='?', default=ARG_NOT_SET,
621 help='When used, the environment will be removed')
622 parser.add_argument('-i', '--clean-image', dest='clean_image', nargs='?', default=ARG_NOT_SET,
623 help='When cleaning, if this is set, the image will be cleaned too')
624 parser.add_argument('-e', '--env', dest='environment', required=True,
625 help='The environment configuration YAML file - REQUIRED')
626 parser.add_argument('-l', '--log-level', dest='log_level', default='INFO', help='Logging Level (INFO|DEBUG)')
627 args = parser.parse_args()
629 if args.deploy is ARG_NOT_SET and args.clean is ARG_NOT_SET:
630 print 'Must enter either -d for deploy or -c for cleaning up and environment'
632 if args.deploy is not ARG_NOT_SET and args.clean is not ARG_NOT_SET:
633 print 'Cannot enter both options -d/--deploy and -c/--clean'