3 # Copyright (c) 2017 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, OpenStackImage
27 from snaps.openstack.create_instance import VmInstanceSettings
28 from snaps.openstack.create_keypairs import KeypairSettings
29 from snaps.openstack.create_network import PortSettings, NetworkSettings
30 from snaps.openstack.create_router import RouterSettings
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
46 :param os_conn_config: The configuration holding the credentials
47 :return: an OSCreds instance
50 http_proxy = os_conn_config.get('http_proxy')
52 tokens = re.split(':', http_proxy)
53 ssh_proxy_cmd = os_conn_config.get('ssh_proxy_cmd')
54 proxy_settings = ProxySettings(host=tokens[0], port=tokens[1],
55 ssh_proxy_cmd=ssh_proxy_cmd)
57 os_conn_config['proxy_settings'] = proxy_settings
59 return OSCreds(**os_conn_config)
62 def __parse_ports_config(config):
64 Parses the "ports" configuration
65 :param config: The dictionary to parse
66 :return: a list of PortConfig objects
69 for port_config in config:
70 out.append(PortSettings(**port_config.get('port')))
74 def __create_flavors(os_conn_config, flavors_config, cleanup=False):
76 Returns a dictionary of flavors where the key is the image name and the
77 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
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(
91 __get_os_credentials(os_conn_config),
92 FlavorSettings(**flavor_config))
93 flavor_creator.create(cleanup=cleanup)
94 flavors[flavor_config['name']] = flavor_creator
95 except Exception as e:
96 for key, flavor_creator in flavors.items():
97 flavor_creator.clean()
99 logger.info('Created configured flavors')
104 def __create_images(os_conn_config, images_config, cleanup=False):
106 Returns a dictionary of images where the key is the image name and the
107 value is the image object
108 :param os_conn_config: The OpenStack connection credentials
109 :param images_config: The list of image configurations
110 :param cleanup: Denotes whether or not this is being called for cleanup
117 for image_config_dict in images_config:
118 image_config = image_config_dict.get('image')
119 if image_config and image_config.get('name'):
120 images[image_config['name']] = deploy_utils.create_image(
121 __get_os_credentials(os_conn_config),
122 ImageSettings(**image_config), cleanup)
123 except Exception as e:
124 for key, image_creator in images.items():
125 image_creator.clean()
127 logger.info('Created configured images')
132 def __create_networks(os_conn_config, network_confs, cleanup=False):
134 Returns a dictionary of networks where the key is the network name and the
135 value is the network object
136 :param os_conn_config: The OpenStack connection credentials
137 :param network_confs: The list of network configurations
138 :param cleanup: Denotes whether or not this is being called for cleanup
145 for network_conf in network_confs:
146 net_name = network_conf['network']['name']
147 os_creds = __get_os_credentials(os_conn_config)
148 network_dict[net_name] = deploy_utils.create_network(
149 os_creds, NetworkSettings(**network_conf['network']),
151 except Exception as e:
152 for key, net_creator in network_dict.items():
156 logger.info('Created configured networks')
161 def __create_routers(os_conn_config, router_confs, cleanup=False):
163 Returns a dictionary of networks where the key is the network name and the
164 value is the network object
165 :param os_conn_config: The OpenStack connection credentials
166 :param router_confs: The list of router configurations
167 :param cleanup: Denotes whether or not this is being called for cleanup
171 os_creds = __get_os_credentials(os_conn_config)
175 for router_conf in router_confs:
176 router_name = router_conf['router']['name']
177 router_dict[router_name] = deploy_utils.create_router(
178 os_creds, RouterSettings(**router_conf['router']), cleanup)
179 except Exception as e:
180 for key, router_creator in router_dict.items():
181 router_creator.clean()
184 logger.info('Created configured networks')
189 def __create_keypairs(os_conn_config, keypair_confs, cleanup=False):
191 Returns a dictionary of keypairs where the key is the keypair name and the
192 value is the keypair object
193 :param os_conn_config: The OpenStack connection credentials
194 :param keypair_confs: The list of keypair configurations
195 :param cleanup: Denotes whether or not this is being called for cleanup
201 for keypair_dict in keypair_confs:
202 keypair_config = keypair_dict['keypair']
203 kp_settings = KeypairSettings(**keypair_config)
205 keypair_config['name']] = deploy_utils.create_keypair(
206 __get_os_credentials(os_conn_config), kp_settings, cleanup)
207 except Exception as e:
208 for key, keypair_creator in keypairs_dict.items():
209 keypair_creator.clean()
212 logger.info('Created configured keypairs')
217 def __create_instances(os_conn_config, instances_config, image_dict,
218 keypairs_dict, cleanup=False):
220 Returns a dictionary of instances where the key is the instance name and
221 the value is the VM object
222 :param os_conn_config: The OpenStack connection credentials
223 :param instances_config: The list of VM instance configurations
224 :param image_dict: A dictionary of images that will probably be used to
225 instantiate the VM instance
226 :param keypairs_dict: A dictionary of keypairs that will probably be used
227 to instantiate the VM instance
228 :param cleanup: Denotes whether or not this is being called for cleanup
231 os_creds = __get_os_credentials(os_conn_config)
237 for instance_config in instances_config:
238 conf = instance_config.get('instance')
241 image_creator = image_dict.get(conf.get('imageName'))
243 instance_settings = VmInstanceSettings(
244 **instance_config['instance'])
245 kp_name = conf.get('keypair_name')
247 'name']] = deploy_utils.create_vm_instance(
248 os_creds, instance_settings,
249 image_creator.image_settings,
250 keypair_creator=keypairs_dict[kp_name],
253 raise Exception('Image creator instance not found.'
254 ' Cannot instantiate')
256 raise Exception('Image dictionary is None. Cannot '
259 raise Exception('Instance configuration is None. Cannot '
261 except Exception as e:
262 logger.error('Unexpected error creating instances. Attempting to '
263 'cleanup environment - %s', e)
264 for key, inst_creator in vm_dict.items():
268 logger.info('Created configured instances')
272 def __apply_ansible_playbooks(ansible_configs, os_conn_config, vm_dict,
273 image_dict, flavor_dict, env_file):
275 Applies ansible playbooks to running VMs with floating IPs
276 :param ansible_configs: a list of Ansible configurations
277 :param os_conn_config: the OpenStack connection configuration used to
278 create an OSCreds instance
279 :param vm_dict: the dictionary of newly instantiated VMs where the name is
281 :param image_dict: the dictionary of newly instantiated images where the
283 :param flavor_dict: the dictionary of newly instantiated flavors where the
285 :param env_file: the path of the environment for setting the CWD so
286 playbook location is relative to the deployment file
287 :return: t/f - true if successful
289 logger.info("Applying Ansible Playbooks")
291 # Ensure all hosts are accepting SSH session requests
292 for vm_inst in list(vm_dict.values()):
293 if not vm_inst.vm_ssh_active(block=True):
295 "Timeout waiting for instance to respond to SSH requests")
298 # Set CWD so the deployment file's playbook location can leverage
300 orig_cwd = os.getcwd()
301 env_dir = os.path.dirname(env_file)
305 for ansible_config in ansible_configs:
306 os_creds = __get_os_credentials(os_conn_config)
307 __apply_ansible_playbook(ansible_config, os_creds, vm_dict,
308 image_dict, flavor_dict)
310 # Return to original directory
316 def __apply_ansible_playbook(ansible_config, os_creds, vm_dict, image_dict,
319 Applies an Ansible configuration setting
320 :param ansible_config: the configuration settings
321 :param os_creds: the OpenStack credentials object
322 :param vm_dict: the dictionary of newly instantiated VMs where the name is
324 :param image_dict: the dictionary of newly instantiated images where the
326 :param flavor_dict: the dictionary of newly instantiated flavors where the
330 (remote_user, floating_ips, private_key_filepath,
331 proxy_settings) = __get_connection_info(
332 ansible_config, vm_dict)
334 retval = ansible_utils.apply_playbook(
335 ansible_config['playbook_location'], floating_ips, remote_user,
336 private_key_filepath,
337 variables=__get_variables(ansible_config.get('variables'),
338 os_creds, vm_dict, image_dict,
340 proxy_setting=proxy_settings)
342 # Not a fatal type of event
344 'Unable to apply playbook found at location - ' +
345 ansible_config('playbook_location'))
348 def __get_connection_info(ansible_config, vm_dict):
350 Returns a tuple of data required for connecting to the running VMs
351 (remote_user, [floating_ips], private_key_filepath, proxy_settings)
352 :param ansible_config: the configuration settings
353 :param vm_dict: the dictionary of VMs where the VM name is the key
354 :return: tuple where the first element is the user and the second is a list
355 of floating IPs and the third is the
356 private key file location and the fourth is an instance of the
357 snaps.ProxySettings class
358 (note: in order to work, each of the hosts need to have the same sudo_user
359 and private key file location values)
361 if ansible_config.get('hosts'):
362 hosts = ansible_config['hosts']
364 floating_ips = list()
367 proxy_settings = None
369 vm = vm_dict.get(host)
371 fip = vm.get_floating_ip()
373 remote_user = vm.get_image_user()
376 floating_ips.append(fip.ip)
379 'Could not find floating IP for VM - ' +
382 pk_file = vm.keypair_settings.private_filepath
383 proxy_settings = vm.get_os_creds().proxy_settings
385 logger.error('Could not locate VM with name - ' + host)
387 return remote_user, floating_ips, pk_file, proxy_settings
391 def __get_variables(var_config, os_creds, vm_dict, image_dict, flavor_dict):
393 Returns a dictionary of substitution variables to be used for Ansible
395 :param var_config: the variable configuration settings
396 :param os_creds: the OpenStack credentials object
397 :param vm_dict: the dictionary of newly instantiated VMs where the name is
399 :param image_dict: the dictionary of newly instantiated images where the
401 :param flavor_dict: the dictionary of newly instantiated flavors where the
403 :return: dictionary or None
405 if var_config and vm_dict and len(vm_dict) > 0:
407 for key, value in var_config.items():
408 value = __get_variable_value(value, os_creds, vm_dict, image_dict,
411 variables[key] = value
413 "Set Jinga2 variable with key [%s] the value [%s]",
416 logger.warning('Key [%s] or Value [%s] must not be None',
417 str(key), str(value))
422 def __get_variable_value(var_config_values, os_creds, vm_dict, image_dict,
425 Returns the associated variable value for use by Ansible for substitution
427 :param var_config_values: the configuration dictionary
428 :param os_creds: the OpenStack credentials object
429 :param vm_dict: the dictionary of newly instantiated VMs where the name is
431 :param image_dict: the dictionary of newly instantiated images where the
433 :param flavor_dict: the dictionary of newly instantiated flavors where the
437 if var_config_values['type'] == 'string':
438 return __get_string_variable_value(var_config_values)
439 if var_config_values['type'] == 'vm-attr':
440 return __get_vm_attr_variable_value(var_config_values, vm_dict)
441 if var_config_values['type'] == 'os_creds':
442 return __get_os_creds_variable_value(var_config_values, os_creds)
443 if var_config_values['type'] == 'port':
444 return __get_vm_port_variable_value(var_config_values, vm_dict)
445 if var_config_values['type'] == 'image':
446 return __get_image_variable_value(var_config_values, image_dict)
447 if var_config_values['type'] == 'flavor':
448 return __get_flavor_variable_value(var_config_values, flavor_dict)
452 def __get_string_variable_value(var_config_values):
454 Returns the associated string value
455 :param var_config_values: the configuration dictionary
456 :return: the value contained in the dictionary with the key 'value'
458 return var_config_values['value']
461 def __get_vm_attr_variable_value(var_config_values, vm_dict):
463 Returns the associated value contained on a VM instance
464 :param var_config_values: the configuration dictionary
465 :param vm_dict: the dictionary containing all VMs where the key is the VM's
469 vm = vm_dict.get(var_config_values['vm_name'])
471 if var_config_values['value'] == 'floating_ip':
472 return vm.get_floating_ip().ip
473 if var_config_values['value'] == 'image_user':
474 return vm.get_image_user()
477 def __get_os_creds_variable_value(var_config_values, os_creds):
479 Returns the associated OS credentials value
480 :param var_config_values: the configuration dictionary
481 :param os_creds: the credentials
484 logger.info("Retrieving OS Credentials")
486 if var_config_values['value'] == 'username':
487 logger.info("Returning OS username")
488 return os_creds.username
489 elif var_config_values['value'] == 'password':
490 logger.info("Returning OS password")
491 return os_creds.password
492 elif var_config_values['value'] == 'auth_url':
493 logger.info("Returning OS auth_url")
494 return os_creds.auth_url
495 elif var_config_values['value'] == 'project_name':
496 logger.info("Returning OS project_name")
497 return os_creds.project_name
499 logger.info("Returning none")
503 def __get_vm_port_variable_value(var_config_values, vm_dict):
505 Returns the associated OS credentials value
506 :param var_config_values: the configuration dictionary
507 :param vm_dict: the dictionary containing all VMs where the key is the VM's
511 port_name = var_config_values.get('port_name')
512 vm_name = var_config_values.get('vm_name')
514 if port_name and vm_name:
515 vm = vm_dict.get(vm_name)
517 port_value_id = var_config_values.get('port_value')
519 if port_value_id == 'mac_address':
520 return vm.get_port_mac(port_name)
521 if port_value_id == 'ip_address':
522 return vm.get_port_ip(port_name)
525 def __get_image_variable_value(var_config_values, image_dict):
527 Returns the associated image value
528 :param var_config_values: the configuration dictionary
529 :param image_dict: the dictionary containing all images where the key is
533 logger.info("Retrieving image values")
536 if var_config_values.get('image_name'):
537 image_creator = image_dict.get(var_config_values['image_name'])
539 if var_config_values.get('value') and \
540 var_config_values['value'] == 'id':
541 return image_creator.get_image().id
542 if var_config_values.get('value') and \
543 var_config_values['value'] == 'user':
544 return image_creator.image_settings.image_user
546 logger.info("Returning none")
550 def __get_flavor_variable_value(var_config_values, flavor_dict):
552 Returns the associated flavor value
553 :param var_config_values: the configuration dictionary
554 :param flavor_dict: the dictionary containing all flavor creators where the
556 :return: the value or None
558 logger.info("Retrieving flavor values")
561 if var_config_values.get('flavor_name'):
562 flavor_creator = flavor_dict.get(var_config_values['flavor_name'])
564 if var_config_values.get('value') and \
565 var_config_values['value'] == 'id':
566 return flavor_creator.get_flavor().id
571 Will need to set environment variable ANSIBLE_HOST_KEY_CHECKING=False or
572 Create a file located in /etc/ansible/ansible/cfg or ~/.ansible.cfg
573 containing the following content:
576 host_key_checking = False
578 CWD must be this directory where this script is located.
582 log_level = logging.INFO
583 if arguments.log_level != 'INFO':
584 log_level = logging.DEBUG
585 logging.basicConfig(level=log_level)
587 logger.info('Starting to Deploy')
588 config = file_utils.read_yaml(arguments.environment)
589 logger.debug('Read configuration file - ' + arguments.environment)
592 os_config = config.get('openstack')
594 os_conn_config = None
598 flavors_dict = dict()
602 os_conn_config = os_config.get('connection')
605 flavors_dict = __create_flavors(
606 os_conn_config, os_config.get('flavors'),
607 arguments.clean is not ARG_NOT_SET)
608 creators.append(flavors_dict)
611 images_dict = __create_images(
612 os_conn_config, os_config.get('images'),
613 arguments.clean is not ARG_NOT_SET)
614 creators.append(images_dict)
617 creators.append(__create_networks(
618 os_conn_config, os_config.get('networks'),
619 arguments.clean is not ARG_NOT_SET))
622 creators.append(__create_routers(
623 os_conn_config, os_config.get('routers'),
624 arguments.clean is not ARG_NOT_SET))
627 keypairs_dict = __create_keypairs(
628 os_conn_config, os_config.get('keypairs'),
629 arguments.clean is not ARG_NOT_SET)
630 creators.append(keypairs_dict)
633 vm_dict = __create_instances(
634 os_conn_config, os_config.get('instances'),
635 images_dict, keypairs_dict,
636 arguments.clean is not ARG_NOT_SET)
637 creators.append(vm_dict)
639 'Completed creating/retrieving all configured instances')
640 except Exception as e:
642 'Unexpected error deploying environment. Rolling back due'
647 # Must enter either block
648 if arguments.clean is not ARG_NOT_SET:
649 # Cleanup Environment
650 __cleanup(creators, arguments.clean_image is not ARG_NOT_SET)
651 elif arguments.deploy is not ARG_NOT_SET:
652 logger.info('Configuring NICs where required')
653 for vm in vm_dict.values():
655 logger.info('Completed NIC configuration')
658 ansible_config = config.get('ansible')
659 if ansible_config and vm_dict:
660 if not __apply_ansible_playbooks(ansible_config,
661 os_conn_config, vm_dict,
662 images_dict, flavors_dict,
663 arguments.environment):
664 logger.error("Problem applying ansible playbooks")
667 'Unable to read configuration file - ' + arguments.environment)
673 def __cleanup(creators, clean_image=False):
674 for creator_dict in reversed(creators):
675 for key, creator in creator_dict.items():
676 if (isinstance(creator, OpenStackImage) and clean_image) or \
677 not isinstance(creator, OpenStackImage):
680 except Exception as e:
681 logger.warning('Error cleaning component - %s', e)
684 if __name__ == '__main__':
685 # To ensure any files referenced via a relative path will begin from the
686 # directory in which this file resides
687 os.chdir(os.path.dirname(os.path.realpath(__file__)))
689 parser = argparse.ArgumentParser()
691 '-d', '--deploy', dest='deploy', nargs='?', default=ARG_NOT_SET,
692 help='When used, environment will be deployed and provisioned')
694 '-c', '--clean', dest='clean', nargs='?', default=ARG_NOT_SET,
695 help='When used, the environment will be removed')
697 '-i', '--clean-image', dest='clean_image', nargs='?',
699 help='When cleaning, if this is set, the image will be cleaned too')
701 '-e', '--env', dest='environment', required=True,
702 help='The environment configuration YAML file - REQUIRED')
704 '-l', '--log-level', dest='log_level', default='INFO',
705 help='Logging Level (INFO|DEBUG)')
706 args = parser.parse_args()
708 if args.deploy is ARG_NOT_SET and args.clean is ARG_NOT_SET:
710 'Must enter either -d for deploy or -c for cleaning up and '
713 if args.deploy is not ARG_NOT_SET and args.clean is not ARG_NOT_SET:
714 print('Cannot enter both options -d/--deploy and -c/--clean')