def _rubocop(self, serverspec_dir, debug=False, pattern='/**/*.rb', out=LOG.info, err=LOG.error): """ Executes rubocop against specified directory/pattern, and returns a :func:`sh` response object. :param serverspec_dir: A string containing the directory with files to lint. :param debug: An optional bool to toggle debug output. :param pattern: A string containing the pattern of files to lint. :param out: An optional function to process STDOUT for underlying :func:`sh` call. :param err: An optional function to process STDERR for underlying :func:`sh` call. :return: :func:`sh` response object. """ kwargs = {'_out': out, '_err': err, 'debug': debug} msg = 'Executing rubocop on *.rb files found in {}/.'.format( serverspec_dir) util.print_info(msg) match = serverspec_dir + pattern return sh.rubocop(match, **kwargs)
def _rake(self, rakefile, debug=False, out=LOG.info, err=LOG.error): """ Executes rake against specified rakefile, and returns a :func:`sh` response object. :param rakefile: A string containing path to the rakefile. :param debug: An optional bool to toggle debug output. :param out: An optional function to process STDOUT for underlying :func:`sh` call. :param err: An optional function to process STDERR for underlying :func:`sh` call. :return: :func:`sh` response object. """ kwargs = { '_out': out, '_err': err, 'trace': debug, 'rakefile': rakefile } msg = 'Executing serverspec tests found in {}/.'.format( self._serverspec_dir) util.print_info(msg) return sh.rake(**kwargs)
def execute(self, exit=True): """ Execute the actions that should run prior to a converge and return a tuple. :param exit: (Unused) Provided to complete method signature. :return: Return a tuple provided by :meth:`.AnsiblePlaybook.execute`. """ debug = self.args.get('debug') if self.molecule.state.installed_deps: return (None, None) dependency_name = self.molecule.dependency if dependency_name == 'galaxy': dd = self.molecule.config.config.get('dependency') if dd.get('requirements_file'): msg = "Downloading dependencies with '{}'...".format( dependency_name) util.print_info(msg) g = ansible_galaxy.AnsibleGalaxy( self.molecule.config.config, debug=debug) g.execute() self.molecule.state.change_state('installed_deps', True) elif dependency_name == 'shell': dd = self.molecule.config.config.get('dependency') if dd.get('command'): msg = "Downloading dependencies with '{}'...".format( dependency_name) util.print_info(msg) s = shell.Shell(self.molecule.config.config, debug=debug) s.execute() self.molecule.state.change_state('installed_deps', True) return (None, None)
def execute(self, exit=True): """ Execute the actions necessary to perform a `molecule check` and return a tuple. :param exit: (Unused) Provided to complete method signature. :return: Return a tuple provided by :meth:`.AnsiblePlaybook.execute`. """ if not self.molecule.state.created: msg = ('Instance(s) not created, `check` should be run ' 'against created instance(s).') util.print_error(msg) util.sysexit() debug = self.args.get('debug') ansible = ansible_playbook.AnsiblePlaybook( self.molecule.config.config['ansible'], self.molecule.driver.ansible_connection_params, debug=debug) ansible.add_cli_arg('check', True) util.print_info("Performing a 'Dry Run' of playbook...") return ansible.execute(hide_errors=True) return (None, None)
def _testinfra(self, tests, debug=False, env=os.environ.copy(), out=LOG.info, err=LOG.error, **kwargs): """ Runs testinfra and returns a sh response object. :param tests: List of testinfra tests :param debug: Pass debug flag to testinfra :param env: Environment to pass to underlying sh call :param out: Function to process STDOUT for underlying sh call :param err: Function to process STDERR for underlying sh call :return: sh response object """ kwargs['debug'] = debug kwargs['_env'] = env kwargs['_out'] = out kwargs['_err'] = err if 'HOME' not in kwargs['_env']: kwargs['_env']['HOME'] = os.path.expanduser('~') msg = 'Executing testinfra tests found in {}/.'.format( self._testinfra_dir) util.print_info(msg) return sh.testinfra(tests, **kwargs)
def _rake(self, rakefile, debug=False, out=util.callback_info, err=util.callback_error): """ Executes rake against specified rakefile and returns a :func:`sh` response object. :param rakefile: A string containing path to the rakefile. :param debug: An optional bool to toggle debug output. :param out: An optional function to process STDOUT for underlying :func:`sh` call. :param err: An optional function to process STDERR for underlying :func:`sh` call. :return: :func:`sh` response object. """ kwargs = { '_out': out, '_err': err, 'trace': debug, 'rakefile': rakefile } msg = 'Executing serverspec tests found in {}/...'.format( self._serverspec_dir) util.print_info(msg) try: cmd = sh.rake.bake(**kwargs) except sh.CommandNotFound: msg = 'Verifier missing, gem install rake.' util.print_error(msg) util.sysexit() return util.run_command(cmd, debug=self._debug)
def execute(self, exit=True): util.print_info( 'Idempotence test in progress (can take a few minutes)...') c = converge.Converge(self.command_args, self.args, self.molecule) status, output = c.execute(idempotent=True, exit=False, hide_errors=True) if status is not None: msg = 'Skipping due to errors during converge.' util.print_info(msg) return status, None idempotent, changed_tasks = self.molecule._parse_provisioning_output( output) if idempotent: util.print_success('Idempotence test passed.') return None, None # Display the details of the idempotence test. if changed_tasks: LOG.error( 'Idempotence test failed because of the following tasks:') LOG.error('{}'.format('\n'.join(changed_tasks))) else: # But in case the idempotence callback plugin was not found, we just display an error message. LOG.error('Idempotence test failed.') warning_msg = "The idempotence plugin was not found or did not provide the required information. " \ "Therefore the failure details cannot be displayed." LOG.warning(warning_msg) if exit: util.sysexit() return 1, None
def _rake(self, rakefile, debug=False, env=os.environ.copy(), out=LOG.info, err=LOG.error): """ Runs rake with specified rakefile. :param rakefile: Path to rakefile :param debug: Pass trace flag to rake :param env: Environment to pass to underlying sh call :param out: Function to process STDOUT for underlying sh call :param err: Function to process STDERR for underlying sh call :return: sh response object """ kwargs = {'_env': env, '_out': out, '_err': err, 'trace': debug, 'rakefile': rakefile} if 'HOME' not in kwargs['_env']: kwargs['_env']['HOME'] = os.path.expanduser('~') msg = 'Executing serverspec tests found in {}/.'.format( self._serverspec_dir) util.print_info(msg) return sh.rake(**kwargs)
def _testinfra(self, tests, debug=False, ansible_env={}, out=LOG.info, err=LOG.error, **kwargs): """ Executes testinfra against specified tests, and returns a :func:`sh` response object. :param tests: A list of testinfra tests. :param debug: An optional bool to toggle debug output. :param pattern: A string containing the pattern of files to lint. :param ansible_env: An optional environment to pass to underlying :func:`sh` call. :param out: An optional function to process STDOUT for underlying :func:`sh` call. :param err: An optional function to process STDERR for underlying :func:`sh` call. :return: :func:`sh` response object. """ kwargs['debug'] = debug kwargs['_env'] = ansible_env kwargs['_out'] = out kwargs['_err'] = err msg = 'Executing testinfra tests found in {}/.'.format( self._testinfra_dir) util.print_info(msg) return sh.testinfra(tests, **kwargs)
def _rubocop(self, serverspec_dir, debug=False, env=os.environ.copy(), pattern='/**/*.rb', out=LOG.info, err=LOG.error): """ Runs rubocop against specified directory with specified pattern. :param serverspec_dir: Directory to search for files to lint :param debug: Pass debug flag to rubocop :param pattern: Search pattern to pass to rubocop :param env: Environment to pass to underlying sh call :param out: Function to process STDOUT for underlying sh call :param err: Function to process STDERR for underlying sh call :return: sh response object """ kwargs = {'_env': env, '_out': out, '_err': err, 'debug': debug} if 'HOME' not in kwargs['_env']: kwargs['_env']['HOME'] = os.path.expanduser('~') msg = 'Executing rubocop on *.rb files found in {}/.'.format( serverspec_dir) util.print_info(msg) match = serverspec_dir + pattern return sh.rubocop(match, **kwargs)
def up(self, no_provision=True): self.molecule.state.change_state('driver', self.name) kpn = self._get_keypair() active_instances = self._openstack.list_servers() active_instance_names = { instance['name']: instance['status'] for instance in active_instances } util.print_warn('Creating openstack instances...') for instance in self.instances: if instance['name'] not in active_instance_names: msg = '\tBringing up {}...'.format(instance['name']) util.print_info(msg) server = self._openstack.create_server( name=instance['name'], image=self._openstack.get_image(instance['image']), flavor=self._openstack.get_flavor(instance['flavor']), auto_ip=True, wait=True, key_name=kpn, security_groups=instance['security_groups'] if 'security_groups' in instance else None) self._reset_known_host_key(server['interface_ip']) instance['created'] = True num_retries = 0 while not self._check_ssh_availability( server['interface_ip'], instance['sshuser'], timeout=6, sshkey_filename=self._get_keyfile( )) or num_retries == 5: util.print_info('\t Waiting for ssh availability...') num_retries += 1
def execute(self, exit=True): """ Execute the actions necessary to perform a `molecule idempotence` and return a tuple. :param exit: An optional flag to toggle the exiting of the module on command failure. :return: Return a tuple of (`exit status`, `command output`), otherwise sys.exit on command failure. """ util.print_info("Idempotence test in progress (can take a few minutes) ...") c = converge.Converge(self.command_args, self.args, self.molecule) status, output = c.execute(idempotent=True, exit=False, hide_errors=True) if status is not None: msg = "Skipping due to errors during converge." util.print_info(msg) return status, None idempotent = self._is_idempotent(output) if idempotent: util.print_success("Idempotence test passed.") return None, None else: LOG.error("Idempotence test failed because of the following tasks:") LOG.error("\n".join(self._non_idempotent_tasks(output))) if exit: util.sysexit() return 1, None
def _rake(self, rakefile, debug=False, env=os.environ.copy(), out=LOG.info, err=LOG.error): """ Executes rake against specified rakefile, and returns a :func:`sh` response object. :param rakefile: A string containing path to the rakefile. :param debug: An optional bool to toggle debug output. :param env: An optional environment to pass to underlying :func:`sh` call. :param out: An optional function to process STDOUT for underlying :func:`sh` call. :param err: An optional function to process STDERR for underlying :func:`sh` call. :return: :func:`sh` response object. """ kwargs = { '_env': env, '_out': out, '_err': err, 'trace': debug, 'rakefile': rakefile } msg = 'Executing serverspec tests found in {}/.'.format( self._serverspec_dir) util.print_info(msg) return sh.rake(**kwargs)
def execute(self, exit=True): """ Execute the actions necessary to perform a `molecule syntax` and return a tuple. :param exit: (Unused) Provided to complete method signature. :return: Return a tuple provided by :meth:`.AnsiblePlaybook.execute`. """ debug = self.args.get('debug') self.molecule.create_templates() if 'requirements_file' in self.molecule.config.config[ 'ansible'] and not self.molecule.state.installed_deps: galaxy = ansible_galaxy.AnsibleGalaxy(self.molecule.config.config, debug=debug) galaxy.execute() self.molecule.state.change_state('installed_deps', True) ansible = ansible_playbook.AnsiblePlaybook( self.molecule.config.config['ansible'], {}, debug=debug) ansible.add_cli_arg('syntax-check', True) ansible.add_cli_arg('inventory_file', 'localhost,') util.print_info('Checking playbook\'s syntax ...') return ansible.execute(hide_errors=True)
def _rubocop(self, serverspec_dir, debug=False, env=os.environ.copy(), pattern='/**/*.rb', out=LOG.info, err=LOG.error): """ Executes rubocop against specified directory/pattern, and returns a :func:`sh` response object. :param serverspec_dir: A string containing the directory with files to lint. :param debug: An optional bool to toggle debug output. :param pattern: A string containing the pattern of files to lint. :param env: An optional environment to pass to underlying :func:`sh` call. :param out: An optional function to process STDOUT for underlying :func:`sh` call. :param err: An optional function to process STDERR for underlying :func:`sh` call. :return: :func:`sh` response object. """ kwargs = {'_env': env, '_out': out, '_err': err, 'debug': debug} msg = 'Executing rubocop on *.rb files found in {}/.'.format( serverspec_dir) util.print_info(msg) match = serverspec_dir + pattern return sh.rubocop(match, **kwargs)
def execute(self, exit=True): """ Execute the actions necessary to perform a `molecule idempotence` and return a tuple. :param exit: An optional flag to toggle the exiting of the module on command failure. :return: Return a tuple of (`exit status`, `command output`), otherwise sys.exit on command failure. """ util.print_info( 'Idempotence test in progress (can take a few minutes) ...') c = converge.Converge(self.args, self.command_args, self.molecule) status, output = c.execute( idempotent=True, exit=False, hide_errors=True) if status is not None: msg = 'Skipping due to errors during converge.' util.print_info(msg) return status, None idempotent = self._is_idempotent(output) if idempotent: util.print_success('Idempotence test passed.') return None, None else: LOG.error( 'Idempotence test failed because of the following tasks:') LOG.error('\n'.join(self._non_idempotent_tasks(output))) if exit: util.sysexit() return 1, None
def _testinfra(self, tests, debug=False, ansible_env={}, out=LOG.info, err=LOG.error, **kwargs): """ Executes testinfra against specified tests and returns a :func:`sh` response object. :param tests: A list of testinfra tests. :param debug: An optional bool to toggle debug output. :param pattern: A string containing the pattern of files to lint. :param ansible_env: An optional environment to pass to underlying :func:`sh` call. :param out: An optional function to process STDOUT for underlying :func:`sh` call. :param err: An optional function to process STDERR for underlying :func:`sh` call. :return: :func:`sh` response object. """ kwargs['debug'] = debug kwargs['_env'] = ansible_env kwargs['_out'] = out kwargs['_err'] = err msg = 'Executing testinfra tests found in {}/.'.format( self._testinfra_dir) util.print_info(msg) cmd = sh.testinfra.bake(tests, **kwargs) return util.run_command(cmd, debug=self._debug)
def execute(self, exit=True): """ Execute the actions necessary to perform a `molecule create` and return a tuple. :param exit: An optional flag to toggle the exiting of the module on command failure. :return: Return a tuple of None, otherwise sys.exit on command failure. """ self.molecule.remove_inventory_file() self.molecule.create_templates() try: util.print_info('Creating instances...') self.molecule.driver.up(no_provision=True) self.molecule.state.change_state('created', True) if self.command_args.get('platform') == 'all': self.molecule.state.change_state('multiple_platforms', True) except subprocess.CalledProcessError as e: util.print_error(str(e)) if exit: util.sysexit(e.returncode) return e.returncode, e.message self.molecule.create_inventory_file() self.molecule.write_instances_state() return None, None
def _rubocop(self, serverspec_dir, debug=False, pattern='/**/*.rb', out=util.callback_info, err=util.callback_error): """ Executes rubocop against specified directory/pattern and returns a :func:`sh` response object. :param serverspec_dir: A string containing the directory with files to lint. :param debug: An optional bool to toggle debug output. :param pattern: A string containing the pattern of files to lint. :param out: An optional function to process STDOUT for underlying :func:`sh` call. :param err: An optional function to process STDERR for underlying :func:`sh` call. :return: :func:`sh` response object. """ kwargs = {'_out': out, '_err': err, 'debug': debug} msg = 'Executing rubocop on *.rb files found in {}/...'.format( serverspec_dir) util.print_info(msg) match = serverspec_dir + pattern try: cmd = sh.rubocop.bake(match, **kwargs) except sh.CommandNotFound: msg = 'Verifier missing, gem install rubocop.' util.print_error(msg) util.sysexit() return util.run_command(cmd, debug=self._debug)
def test_print_info_without_pretty(capsys): util.print_info('test', pretty=False) result, _ = capsys.readouterr() print '{}'.format('test'.rstrip()) expected, _ = capsys.readouterr() assert expected == result
def test_print_info(capsys): util.print_info('test') result, _ = capsys.readouterr() print '--> {}{}'.format(colorama.Fore.CYAN, 'test'.rstrip()) expected, _ = capsys.readouterr() assert expected == result
def test_print_info(capsys): util.print_info("test") result, _ = capsys.readouterr() print "--> {}{}".format(colorama.Fore.CYAN, "test".rstrip()) expected, _ = capsys.readouterr() assert expected == result
def test_print_info_without_pretty(capsys): util.print_info("test", pretty=False) result, _ = capsys.readouterr() print "{}".format("test".rstrip()) expected, _ = capsys.readouterr() assert expected == result
def up(self, no_provision=True, image_tag='molecule_local/{}:{}'): self.molecule.state.change_state('driver', self.name) for container in self.instances: # check global docker driver or specific container config for # overrides for molecule image creation if (container.get('build_image') or (self.molecule.config.config['docker']['build_image'] and container.get('build_image', True))): container['image_tag'] = image_tag self._build_ansible_compatible_image(container) else: container['image_tag'] = '{}:{}' privileged = container.get('privileged', False) port_bindings = container.get('port_bindings', {}) volume_mounts = container.get('volume_mounts', []) links = container.get('links', {}) network_mode = container.get('network_mode', '') cap_add = container.get('cap_add', []) cap_drop = container.get('cap_drop', []) command = container.get('command', '') environment = container.get('environment') docker_host_config = self._docker.create_host_config( privileged=privileged, port_bindings=port_bindings, binds=volume_mounts, links=links, network_mode=network_mode, cap_add=cap_add, cap_drop=cap_drop) if (container['created'] is not True): msg = ('Creating container {} ' 'with base image {}:{}...').format( container['name'], container['image'], container['image_version']) util.print_warn(msg) container = self._docker.create_container( image=container['image_tag'].format( container['image'], container['image_version']), tty=True, detach=False, name=container['name'], ports=port_bindings.keys(), host_config=docker_host_config, environment=environment, command=command) self._docker.start(container=container.get('Id')) container['created'] = True util.print_success('Container created.') else: self._docker.start(container['name']) msg = 'Starting container {}...'.format(container['name']) util.print_info(msg)
def up(self, no_provision=True): self.molecule.state.change_state('driver', self.name) kpn = self._get_keypair() active_instances = self._openstack.list_servers() active_instance_names = { instance['name']: instance['status'] for instance in active_instances } util.print_warn('Creating openstack instances...') for instance in self.instances: try: # We divide the ssh_timeout by 2, because the connect # itself takes at least a second and is followed by # a 1 sec sleep ssh_timeout = int( instance.get('ssh_timeout', self.ssh_timeout) / 2) except TypeError: util.print_error('Can not cast ssh_timeout setting "%s"' ' to int' % instance.get('ssh_timeout', self.ssh_timeout)) util.sysexit() if instance['name'] not in active_instance_names: msg = '\tBringing up {}...'.format(instance['name']) util.print_info(msg) server = self._openstack.create_server( name=instance['name'], image=self._openstack.get_image(instance['image']), flavor=self._openstack.get_flavor(instance['flavor']), auto_ip=True, wait=True, key_name=kpn, ip_pool=instance.get('ip_pool') if instance.get('ip_pool') else self.ip_pool, network=instance.get('networks', []), security_groups=instance.get('security_groups', [])) instance['created'] = True instance['reachable'] = False for _ in range(ssh_timeout): util.print_info('\t Waiting for ssh availability...') if self._check_ssh_availability( server['interface_ip'], instance['sshuser'], timeout=1, sshkey_filename=self._get_keyfile()): instance['reachable'] = True break if not instance['reachable']: util.print_error( 'Could not reach instance "%s"' ' within limit of %s seconds' % (instance['name'], instance.get('ssh_timeout', self.ssh_timeout))) util.sysexit()
def install(self): """ A wrapper to :meth:`.AnsibleGalaxy.execute`. , .. todo:: Remove in favor of simply using execute. """ util.print_info('Installing role dependencies ...') self.bake() self.execute()
def _init_new_role(self, role, role_path, driver, verifier): extra_context = self._get_cookiecutter_context(role, driver, verifier) util.print_info('Initializing role {} ...'.format(role)) for template in [ 'galaxy_init', 'playbook', 'driver/{}'.format(driver), 'verifier/{}'.format(verifier) ]: util.process_templates(template, extra_context, role_path)
def _init_existing_role(self, role, role_path, driver, verifier): extra_context = self._get_cookiecutter_context(role, driver, verifier) util.print_info('Initializing molecule in current directory...') for template in [ 'playbook', 'driver/{}'.format(driver), 'verifier/{}'.format(verifier) ]: util.process_templates(template, extra_context, role_path)
def execute(self): """ Executes ansible-lint against the configured playbook, and returns None. :return: None """ if "ansible_lint" not in self._molecule.disabled: msg = "Executing ansible-lint." util.print_info(msg) sh.ansible_lint(self._playbook, _env=self._env, _out=LOG.info, _err=LOG.error)
def execute(self): """ Executes ansible-lint against the configured playbook, and returns None. :return: None """ msg = 'Executing ansible-lint.' util.print_info(msg) sh.ansible_lint(self._playbook, _out=LOG.info, _err=LOG.error)
def execute(self): """ Executes ansible-lint against the configured playbook, and returns None. :return: None """ if 'ansible_lint' not in self._molecule.disabled: msg = 'Executing ansible-lint.' util.print_info(msg) sh.ansible_lint( self._playbook, _env=self._env, _out=LOG.info, _err=LOG.error)
def _get_temp_keypair(self): kpn = self._get_temp_keyname() if not self._openstack.search_keypairs(kpn): msg = '\tCreating openstack keypair {}...'.format(kpn) util.print_info(msg) pub_key_file = self._get_keyfile() + '.pub' self._openstack.create_keypair( kpn, open(pub_key_file, 'r').read().strip()) return kpn
def _get_temp_keypair(self): kpn = self._get_temp_keyname() if not self._openstack.search_keypairs(kpn): msg = '\tCreating openstack keypair {}...'.format(kpn) util.print_info(msg) pub_key_file = self._get_keyfile() + '.pub' self._openstack.create_keypair(kpn, open(pub_key_file, 'r').read().strip()) return kpn
def up(self, no_provision=True): self.molecule.state.change_state('driver', self.name) if self.molecule.config.config['docker']['build_image']: self._build_ansible_compatible_image() else: self.image_tag = '{}:{}' for container in self.instances: privileged = container.get('privileged', False) port_bindings = container.get('port_bindings', {}) volume_mounts = container.get('volume_mounts', []) links = container.get('links', {}) network_mode = container.get('network_mode', '') cap_add = container.get('cap_add', []) cap_drop = container.get('cap_drop', []) command = container.get('command', '') environment = container.get('environment') docker_host_config = self._docker.create_host_config( privileged=privileged, port_bindings=port_bindings, binds=volume_mounts, links=links, network_mode=network_mode, cap_add=cap_add, cap_drop=cap_drop) if (container['created'] is not True): msg = ('Creating container {} ' 'with base image {}:{}...').format( container['name'], container['image'], container['image_version']) util.print_warn(msg) container = self._docker.create_container( image=self.image_tag.format(container['image'], container['image_version']), tty=True, detach=False, name=container['name'], ports=port_bindings.keys(), host_config=docker_host_config, environment=environment, command=command) self._docker.start(container=container.get('Id')) container['created'] = True util.print_success('Container created.') else: self._docker.start(container['name']) msg = 'Starting container {}...'.format(container['name']) util.print_info(msg)
def up(self, no_provision=True): self.molecule.state.change_state('driver', self.name) if self.molecule.config.config['docker']['build_image']: self._build_ansible_compatible_image() else: self.image_tag = '{}:{}' for container in self.instances: privileged = container.get('privileged', False) port_bindings = container.get('port_bindings', {}) volume_mounts = container.get('volume_mounts', []) links = container.get('links', {}) cap_add = container.get('cap_add', []) cap_drop = container.get('cap_drop', []) command = container.get('command', '') environment = container.get('environment') docker_host_config = self._docker.create_host_config( privileged=privileged, port_bindings=port_bindings, binds=volume_mounts, links=links, cap_add=cap_add, cap_drop=cap_drop) if (container['created'] is not True): msg = ('Creating container {} ' 'with base image {}:{}...').format( container['name'], container['image'], container['image_version']) util.print_warn(msg) container = self._docker.create_container( image=self.image_tag.format(container['image'], container['image_version']), tty=True, detach=False, name=container['name'], ports=port_bindings.keys(), host_config=docker_host_config, environment=environment, command=command) self._docker.start(container=container.get('Id')) container['created'] = True util.print_success('Container created.') else: self._docker.start(container['name']) msg = 'Starting container {}...'.format(container['name']) util.print_info(msg)
def print_valid_platforms(self, porcelain=False): if not porcelain: util.print_info("AVAILABLE PLATFORMS") data = [] default_platform = self.driver.default_platform for platform in self.driver.valid_platforms: if porcelain: default = 'd' if platform['name'] == default_platform else '' else: default = ' (default)' if platform[ 'name'] == default_platform else '' data.append([platform['name'], default]) self.display_tabulate_data(data)
def _testinfra(self, tests, debug=False, ansible_env={}, out=util.callback_info, err=util.callback_error, **kwargs): """ Executes testinfra against specified tests and returns a :func:`sh` response object. :param tests: A list of testinfra tests. :param debug: An optional bool to toggle debug output. :param pattern: A string containing the pattern of files to lint. :param ansible_env: An optional environment to pass to underlying :func:`sh` call. :param out: An optional function to process STDOUT for underlying :func:`sh` call. :param err: An optional function to process STDERR for underlying :func:`sh` call. :return: :func:`sh` response object. """ kwargs['debug'] = debug kwargs['_env'] = ansible_env kwargs['_out'] = out kwargs['_err'] = err msg = 'Executing testinfra tests found in {}/...'.format( self._testinfra_dir) util.print_info(msg) verbose = 'v' verbose_flag = str() for i in range(0, 3): if kwargs.get(verbose): verbose_flag = '-{}'.format(verbose) del kwargs[verbose] if kwargs.get('verbose'): del kwargs['verbose'] break verbose = verbose + 'v' cmd = sh.testinfra.bake(tests) if verbose_flag: cmd = cmd.bake(verbose_flag) cmd = cmd.bake(**kwargs) return util.run_command(cmd, debug=self._debug)
def print_valid_providers(self, porcelain=False): if not porcelain: util.print_info("AVAILABLE PROVIDERS") data = [] default_provider = self.driver.default_provider for provider in self.driver.valid_providers: if porcelain: default = 'd' if provider['name'] == default_provider else '' else: default = ' (default)' if provider[ 'name'] == default_provider else '' data.append([provider['name'], default]) self.display_tabulate_data(data)
def _get_temp_keyfile(self): kn = self._get_temp_keyname() kl = self._get_temp_keylocation() pvtloc = kl + '/' + kn publoc = kl + '/' + kn + '.pub' if not os.path.exists(pvtloc): util.print_info('\tCreating local ssh key {}...'.format(pvtloc)) k = paramiko.RSAKey.generate(2048) k.write_private_key_file(pvtloc) # write the public key too pub = paramiko.RSAKey(filename=pvtloc) with open(publoc, 'w') as f: f.write("%s %s" % (pub.get_name(), pub.get_base64())) return pvtloc
def execute(self, exit=True): self.molecule._create_templates() if 'requirements_file' in self.molecule.config.config[ 'ansible'] and not self.molecule._state.installed_deps: galaxy = ansible_galaxy.AnsibleGalaxy(self.molecule.config.config) galaxy.install() self.molecule._state.change_state('installed_deps', True) ansible = ansible_playbook.AnsiblePlaybook(self.molecule.config.config[ 'ansible']) ansible.add_cli_arg('syntax-check', True) ansible.add_cli_arg('inventory_file', 'localhost,') util.print_info("Checking playbooks syntax ...") return ansible.execute(hide_errors=True)
def execute(self, exit=True): self.molecule._create_templates() if 'requirements_file' in self.molecule.config.config[ 'ansible'] and not self.molecule._state.installed_deps: galaxy = ansible_galaxy.AnsibleGalaxy(self.molecule.config.config) galaxy.install() self.molecule._state.change_state('installed_deps', True) ansible = ansible_playbook.AnsiblePlaybook( self.molecule.config.config['ansible']) ansible.add_cli_arg('syntax-check', True) ansible.add_cli_arg('inventory_file', 'localhost,') util.print_info("Checking playbooks syntax ...") return ansible.execute(hide_errors=True)
def _goss(self, out=util.callback_info, err=util.callback_error): """ Executes goss against specified playbook and returns a :func:`sh` response object. :param out: An optional function to process STDOUT for underlying :func:`sh` call. :param err: An optional function to process STDERR for underlying :func:`sh` call. :return: :func:`sh` response object. """ msg = 'Executing goss tests found in {}...'.format(self._playbook) util.print_info(msg) self._set_library_path() return self._ansible.execute()
def _flake8(self, tests, out=LOG.info, err=LOG.error): """ Executes flake8 against specified tests, and returns a :func:`sh` response object. :param tests: A list of testinfra tests. :param out: An optional function to process STDOUT for underlying :func:`sh` call. :param err: An optional function to process STDERR for underlying :func:`sh` call. :return: :func:`sh` response object. """ msg = 'Executing flake8 on *.py files found in {}/.'.format( self._testinfra_dir) util.print_info(msg) return sh.flake8(tests)