Exemple #1
0
    def _get_modules_directories(self):
        """Return list of ansilbe module includes directories.

        Adds modules directory from molecule and its plugins.
        """
        paths = [util.abs_path(os.path.join(self._get_plugin_directory(), "modules"))]

        for d in drivers():
            p = d.modules_dir()
            if p:
                paths.append(p)
        paths.extend(
            [
                util.abs_path(
                    os.path.join(self._config.scenario.ephemeral_directory, "library")
                ),
                util.abs_path(os.path.join(self._config.project_directory, "library")),
                util.abs_path(
                    os.path.join(
                        os.path.expanduser("~"), ".ansible", "plugins", "modules",
                    )
                ),
                "/usr/share/ansible/plugins/modules",
            ]
        )
        return paths
Exemple #2
0
    def _add_or_update_vars(self):
        """
        Creates host and/or group vars and returns None.

        :returns: None
        """
        for target in ['host_vars', 'group_vars']:
            if target == 'host_vars':
                vars_target = copy.deepcopy(self.host_vars)
                for instance_name, _ in self.host_vars.items():
                    if instance_name == 'localhost':
                        instance_key = instance_name
                    else:
                        instance_key = instance_name

                    vars_target[instance_key] = vars_target.pop(instance_name)

            elif target == 'group_vars':
                vars_target = self.group_vars

            if vars_target:
                ephemeral_directory = self._config.scenario.ephemeral_directory
                target_vars_directory = os.path.join(ephemeral_directory,
                                                     target)

                if not os.path.isdir(util.abs_path(target_vars_directory)):
                    os.mkdir(util.abs_path(target_vars_directory))

                for target in vars_target.keys():
                    target_var_content = vars_target[target]
                    path = os.path.join(
                        util.abs_path(target_vars_directory), target)
                    util.write_file(path, util.safe_dump(target_var_content))
Exemple #3
0
    def _get_modules_directories(self) -> List[str]:
        """Return list of ansilbe module includes directories.

        Adds modules directory from molecule and its plugins.
        """
        paths: List[Optional[str]] = []
        if os.environ.get("ANSIBLE_LIBRARY"):
            paths = list(
                map(util.abs_path, os.environ["ANSIBLE_LIBRARY"].split(":")))

        paths.append(
            util.abs_path(os.path.join(self._get_plugin_directory(),
                                       "modules")))

        for d in drivers():
            p = d.modules_dir()
            if p:
                paths.append(p)
        paths.extend([
            util.abs_path(
                os.path.join(self._config.scenario.ephemeral_directory,
                             "library")),
            util.abs_path(
                os.path.join(self._config.project_directory, "library")),
            util.abs_path(
                os.path.join(
                    os.path.expanduser("~"),
                    ".ansible",
                    "plugins",
                    "modules",
                )),
            "/usr/share/ansible/plugins/modules",
        ])

        return [path for path in paths if path is not None]
Exemple #4
0
    def _add_or_update_vars(self):
        """
        Creates host and/or group vars and returns None.

        :returns: None
        """
        for target in ['host_vars', 'group_vars']:
            if target == 'host_vars':
                vars_target = copy.deepcopy(self.host_vars)
                for instance_name, _ in self.host_vars.items():
                    if instance_name == 'localhost':
                        instance_key = instance_name
                    else:
                        instance_key = instance_name

                    vars_target[instance_key] = vars_target.pop(instance_name)

            elif target == 'group_vars':
                vars_target = self.group_vars

            if vars_target:
                ephemeral_directory = self._config.scenario.ephemeral_directory
                target_vars_directory = os.path.join(ephemeral_directory,
                                                     target)

                if not os.path.isdir(util.abs_path(target_vars_directory)):
                    os.mkdir(util.abs_path(target_vars_directory))

                for target in vars_target.keys():
                    target_var_content = vars_target[target]
                    path = os.path.join(util.abs_path(target_vars_directory),
                                        target)
                    util.write_file(path, util.safe_dump(target_var_content))
Exemple #5
0
    def _add_or_update_vars(self):
        """
        Create host and/or group vars and returns None.

        :returns: None
        """
        # Create the hosts extra inventory source (only if not empty)
        hosts_file = os.path.join(self.inventory_directory, "hosts")
        if self.hosts:
            util.write_file(hosts_file, util.safe_dump(self.hosts))
        # Create the host_vars and group_vars directories
        for target in ["host_vars", "group_vars"]:
            if target == "host_vars":
                vars_target = copy.deepcopy(self.host_vars)
                for instance_name, _ in self.host_vars.items():
                    instance_key = instance_name
                    vars_target[instance_key] = vars_target.pop(instance_name)

            elif target == "group_vars":
                vars_target = self.group_vars

            if vars_target:
                target_vars_directory = os.path.join(self.inventory_directory, target)

                if not os.path.isdir(util.abs_path(target_vars_directory)):
                    os.mkdir(util.abs_path(target_vars_directory))

                for target in vars_target.keys():
                    target_var_content = vars_target[target]
                    path = os.path.join(util.abs_path(target_vars_directory), target)
                    util.write_file(path, util.safe_dump(target_var_content))
Exemple #6
0
    def default_env(self):
        env = util.merge_dicts(
            os.environ,
            {
                "ANSIBLE_CONFIG":
                self._config.provisioner.config_file,
                "ANSIBLE_ROLES_PATH":
                ":".join([
                    util.abs_path(
                        os.path.join(self._config.scenario.ephemeral_directory,
                                     "roles")),
                    util.abs_path(
                        os.path.join(self._config.project_directory,
                                     os.path.pardir)),
                    util.abs_path(
                        os.path.join(os.path.expanduser("~"), ".ansible",
                                     "roles")),
                    "/usr/share/ansible/roles",
                    "/etc/ansible/roles",
                ]),
                "ANSIBLE_LIBRARY":
                ":".join([
                    self._get_modules_directory(),
                    util.abs_path(
                        os.path.join(self._config.scenario.ephemeral_directory,
                                     "library")),
                    util.abs_path(
                        os.path.join(self._config.project_directory,
                                     "library")),
                    util.abs_path(
                        os.path.join(
                            os.path.expanduser("~"),
                            ".ansible",
                            "plugins",
                            "modules",
                        )),
                    "/usr/share/ansible/plugins/modules",
                ]),
                "ANSIBLE_FILTER_PLUGINS":
                ":".join([
                    self._get_filter_plugin_directory(),
                    util.abs_path(
                        os.path.join(
                            self._config.scenario.ephemeral_directory,
                            "plugins",
                            "filter",
                        )),
                    util.abs_path(
                        os.path.join(self._config.project_directory, "plugins",
                                     "filter")),
                    util.abs_path(
                        os.path.join(os.path.expanduser("~"), ".ansible",
                                     "plugins", "filter")),
                    "/usr/share/ansible/plugins/filter",
                ]),
            },
        )
        env = util.merge_dicts(env, self._config.env)

        return env
Exemple #7
0
    def default_env(self):
        env = util.merge_dicts(
            os.environ,
            {
                'ANSIBLE_CONFIG':
                self._config.provisioner.config_file,
                'ANSIBLE_ROLES_PATH':
                ':'.join([
                    util.abs_path(
                        os.path.join(self._config.scenario.ephemeral_directory,
                                     'roles')),
                    util.abs_path(
                        os.path.join(self._config.project_directory,
                                     os.path.pardir)),
                    util.abs_path(
                        os.path.join(os.path.expanduser('~'), '.ansible',
                                     'roles')),
                    '/usr/share/ansible/roles',
                    '/etc/ansible/roles',
                ]),
                'ANSIBLE_LIBRARY':
                ':'.join([
                    self._get_modules_directory(),
                    util.abs_path(
                        os.path.join(self._config.scenario.ephemeral_directory,
                                     'library')),
                    util.abs_path(
                        os.path.join(self._config.project_directory,
                                     'library')),
                    util.abs_path(
                        os.path.join(
                            os.path.expanduser('~'),
                            '.ansible',
                            'plugins',
                            'modules',
                        )),
                    '/usr/share/ansible/plugins/modules',
                ]),
                'ANSIBLE_FILTER_PLUGINS':
                ':'.join([
                    self._get_filter_plugin_directory(),
                    util.abs_path(
                        os.path.join(
                            self._config.scenario.ephemeral_directory,
                            'plugins',
                            'filter',
                        )),
                    util.abs_path(
                        os.path.join(self._config.project_directory, 'plugins',
                                     'filter')),
                    util.abs_path(
                        os.path.join(os.path.expanduser('~'), '.ansible',
                                     'plugins', 'filter')),
                    '/usr/share/ansible/plugins/filter',
                ]),
            },
        )
        env = util.merge_dicts(env, self._config.env)

        return env
Exemple #8
0
def get_configs(args, command_args):
    """
    Glob the current directory for Molecule config files, instantiate config
    objects, and returns a list.

    :param args: A dict of options, arguments and commands from the CLI.
    :param command_args: A dict of options passed to the subcommand from
     the CLI.
    :return: list
    """
    configs = [
        config.Config(molecule_file=util.abs_path(c),
                      args=args,
                      command_args=command_args)
        for c in glob.glob(MOLECULE_GLOB)
    ]

    scenario_name = command_args.get('scenario_name')
    if scenario_name:
        configs = _filter_configs_for_scenario(scenario_name, configs)
        _verify_scenario_name(configs, scenario_name)

    _verify_configs(configs)

    return configs
Exemple #9
0
def _init_new_scenario(command_args):
    """
    Initialize a new scenario:

    >>> molecule init scenario --scenario-name default --role-name foo
    """
    scenario_name = command_args['scenario_name']
    role_name = os.getcwd().split(os.sep)[-1]
    role_directory = util.abs_path(os.path.join(os.getcwd(), os.pardir))

    LOG.info('Initializing new scenario {}...'.format(scenario_name))
    molecule_directory = config.molecule_directory(
        os.path.join(role_directory, role_name))
    scenario_directory = os.path.join(molecule_directory, scenario_name)
    scenario_base_directory = os.path.dirname(scenario_directory)

    if os.path.isdir(scenario_directory):
        msg = ('The directory molecule/{} exists. '
               'Cannot create new scenario.').format(scenario_name)
        util.sysexit_with_message(msg)

    scenario_base_directory = os.path.join(role_directory, role_name)
    templates = [
        'scenario/driver/{driver_name}'.format(**command_args),
        'scenario/verifier/{verifier_name}'.format(**command_args)
    ]
    for template in templates:
        _process_templates(template, command_args, scenario_base_directory)

    role_directory = os.path.join(role_directory, role_name)
    msg = 'Initialized scenario in {} successfully.'.format(scenario_directory)
    LOG.success(msg)
Exemple #10
0
def test_env(config_instance):
    config_instance.args = {'env_file': '.env'}
    x = {
        'MOLECULE_DEBUG': 'False',
        'MOLECULE_FILE': config_instance.config_file,
        'MOLECULE_ENV_FILE':
        util.abs_path(config_instance.args.get('env_file')),
        'MOLECULE_INVENTORY_FILE': config_instance.provisioner.inventory_file,
        'MOLECULE_EPHEMERAL_DIRECTORY':
        config_instance.scenario.ephemeral_directory,
        'MOLECULE_SCENARIO_DIRECTORY': config_instance.scenario.directory,
        'MOLECULE_PROJECT_DIRECTORY': config_instance.project_directory,
        'MOLECULE_INSTANCE_CONFIG': config_instance.driver.instance_config,
        'MOLECULE_DEPENDENCY_NAME': 'galaxy',
        'MOLECULE_DRIVER_NAME': 'docker',
        'MOLECULE_LINT_NAME': 'yamllint',
        'MOLECULE_PROVISIONER_NAME': 'ansible',
        'MOLECULE_PROVISIONER_LINT_NAME': 'ansible-lint',
        'MOLECULE_SCENARIO_NAME': 'default',
        'MOLECULE_STATE_FILE': config_instance.state.state_file,
        'MOLECULE_VERIFIER_NAME': 'testinfra',
        'MOLECULE_VERIFIER_LINT_NAME': 'flake8',
        'MOLECULE_VERIFIER_TEST_DIRECTORY': config_instance.verifier.directory,
    }

    assert x == config_instance.env
Exemple #11
0
def test_vagrant_root(temp_dir, scenario):
    options = {"scenario_name": scenario}

    scenario_directory = os.path.join(os.path.dirname(util.abs_path(__file__)),
                                      os.path.pardir, "scenarios")

    with change_dir_to(scenario_directory):
        cmd = sh.molecule.bake("test", **options)
        run_command(cmd)
def metadata_lint_update(role_directory):
    ansible_lint_src = os.path.join(os.path.dirname(util.abs_path(__file__)),
                                    ".ansible-lint")

    shutil.copy(ansible_lint_src, role_directory)

    with change_dir_to(role_directory):
        cmd = ["ansible-lint", "."]
    pytest.helpers.run_command(cmd)
Exemple #13
0
    def execute(self):
        """
        Execute the actions necessary to perform a `molecule init scenario` and \
        returns None.

        :return: None
        """
        scenario_name = self._command_args["scenario_name"]
        role_name = os.getcwd().split(os.sep)[-1]
        role_directory = util.abs_path(os.path.join(os.getcwd(), os.pardir))

        msg = "Initializing new scenario {}...".format(scenario_name)
        LOG.info(msg)
        molecule_directory = config.molecule_directory(
            os.path.join(role_directory, role_name)
        )
        scenario_directory = os.path.join(molecule_directory, scenario_name)

        if os.path.isdir(scenario_directory):
            msg = (
                "The directory molecule/{} exists. " "Cannot create new scenario."
            ).format(scenario_name)
            util.sysexit_with_message(msg)

        driver_template = api.drivers()[
            self._command_args["driver_name"]
        ].template_dir()
        if "driver_template" in self._command_args:
            self._validate_template_dir(self._command_args["driver_template"])
            cli_driver_template = "{driver_template}/{driver_name}".format(
                **self._command_args
            )
            if os.path.isdir(cli_driver_template):
                driver_template = cli_driver_template
            else:
                LOG.warning(
                    "Driver not found in custom template directory({}), "
                    "using the default template instead".format(cli_driver_template)
                )
        scenario_base_directory = os.path.join(role_directory, role_name)
        templates = [
            driver_template,
            api.verifiers()[self._command_args["verifier_name"]].template_dir(),
        ]
        self._process_templates("molecule", self._command_args, role_directory)
        for template in templates:
            self._process_templates(
                template, self._command_args, scenario_base_directory
            )

        role_directory = os.path.join(role_directory, role_name)
        msg = "Initialized scenario in {} successfully.".format(scenario_directory)
        LOG.success(msg)
Exemple #14
0
def test_env_appends_env_property(_instance):

    # molecule could decide to add extra paths, so we only want to check
    # that those that we need are kept inside the list
    roles_path_list = _instance.env["ANSIBLE_ROLES_PATH"].split(":")
    for x in [
            util.abs_path(
                os.path.join(_instance._config.scenario.ephemeral_directory,
                             "roles")),
            util.abs_path(
                os.path.join(_instance._config.project_directory,
                             os.path.pardir)),
            util.abs_path(
                os.path.join(os.path.expanduser("~"), ".ansible", "roles")),
            "/usr/share/ansible/roles",
            "/etc/ansible/roles",
            util.abs_path(
                os.path.join(_instance._config.scenario.directory, "foo",
                             "bar")),
    ]:
        assert x in roles_path_list

    x = _instance._get_modules_directories()
    x.append(
        util.abs_path(
            os.path.join(_instance._config.scenario.directory, "foo", "bar")))
    assert x == _instance.env["ANSIBLE_LIBRARY"].split(":")

    x = [
        _instance._get_filter_plugin_directory(),
        util.abs_path(
            os.path.join(_instance._config.scenario.ephemeral_directory,
                         "plugins", "filter")),
        util.abs_path(
            os.path.join(_instance._config.project_directory, "plugins",
                         "filter")),
        util.abs_path(
            os.path.join(os.path.expanduser("~"), ".ansible", "plugins",
                         "filter")),
        "/usr/share/ansible/plugins/filter",
        util.abs_path(
            os.path.join(_instance._config.scenario.directory, "foo", "bar")),
    ]
    assert x == _instance.env["ANSIBLE_FILTER_PLUGINS"].split(":")
Exemple #15
0
def test_vagrant_root(temp_dir, scenario):

    env = os.environ
    if not os.path.exists("/dev/kvm"):
        env.update({"VIRT_DRIVER": "'qemu'"})

    scenario_directory = os.path.join(os.path.dirname(util.abs_path(__file__)),
                                      os.path.pardir, "scenarios")

    with change_dir_to(scenario_directory):
        cmd = ["molecule", "test", "--scenario-name", scenario]
        result = run_command(cmd)
        assert result.returncode == 0
Exemple #16
0
def with_scenario(request, scenario_to_test, driver_name, scenario_name):
    scenario_directory = os.path.join(os.path.dirname(util.abs_path(__file__)),
                                      "scenarios", scenario_to_test)

    with change_dir_to(scenario_directory):
        yield
        if scenario_name:
            msg = "CLEANUP: Destroying instances for all scenario(s)"
            LOG.info(msg)
            cmd = [
                "molecule", "destroy", "--driver-name", driver_name, "--all"
            ]
            assert run_command(cmd).returncode == 0
Exemple #17
0
    def execute(self):
        """
        Execute the actions necessary to perform a `molecule init scenario` and
        returns None.

        :return: None
        """
        scenario_name = self._command_args['scenario_name']
        role_name = os.getcwd().split(os.sep)[-1]
        role_directory = util.abs_path(os.path.join(os.getcwd(), os.pardir))

        msg = 'Initializing new scenario {}...'.format(scenario_name)
        LOG.info(msg)
        molecule_directory = config.molecule_directory(
            os.path.join(role_directory, role_name)
        )
        scenario_directory = os.path.join(molecule_directory, scenario_name)

        if os.path.isdir(scenario_directory):
            msg = (
                'The directory molecule/{} exists. ' 'Cannot create new scenario.'
            ).format(scenario_name)
            util.sysexit_with_message(msg)

        driver_template = 'scenario/driver/{driver_name}'.format(**self._command_args)
        if 'driver_template' in self._command_args:
            self._validate_template_dir(self._command_args['driver_template'])
            cli_driver_template = '{driver_template}/{driver_name}'.format(
                **self._command_args
            )
            if os.path.isdir(cli_driver_template):
                driver_template = cli_driver_template
            else:
                LOG.warn(
                    "Driver not found in custom template directory({}), "
                    "using the default template instead".format(cli_driver_template)
                )
        scenario_base_directory = os.path.join(role_directory, role_name)
        templates = [
            driver_template,
            'scenario/verifier/{verifier_name}'.format(**self._command_args),
        ]
        for template in templates:
            self._process_templates(
                template, self._command_args, scenario_base_directory
            )
        self._process_templates('molecule', self._command_args, role_directory)

        role_directory = os.path.join(role_directory, role_name)
        msg = 'Initialized scenario in {} successfully.'.format(scenario_directory)
        LOG.success(msg)
Exemple #18
0
def test_env_appends_env_property(ansible_instance):
    x = [
        util.abs_path(
            os.path.join(ansible_instance._config.scenario.ephemeral_directory,
                         'roles')),
        util.abs_path(
            os.path.join(ansible_instance._config.project_directory,
                         os.path.pardir)),
        util.abs_path(
            os.path.join(ansible_instance._config.scenario.directory, 'foo',
                         'bar')),
    ]
    assert x == ansible_instance.env['ANSIBLE_ROLES_PATH'].split(':')

    x = [
        ansible_instance._get_libraries_directory(),
        util.abs_path(
            os.path.join(ansible_instance._config.scenario.ephemeral_directory,
                         'library')),
        util.abs_path(
            os.path.join(ansible_instance._config.project_directory,
                         'library')),
        util.abs_path(
            os.path.join(ansible_instance._config.scenario.directory, 'foo',
                         'bar')),
    ]
    assert x == ansible_instance.env['ANSIBLE_LIBRARY'].split(':')

    x = [
        ansible_instance._get_filter_plugin_directory(),
        util.abs_path(
            os.path.join(ansible_instance._config.scenario.ephemeral_directory,
                         'plugins', 'filters')),
        util.abs_path(
            os.path.join(ansible_instance._config.project_directory, 'plugins',
                         'filters')),
        util.abs_path(
            os.path.join(ansible_instance._config.scenario.directory, 'foo',
                         'bar')),
    ]
    assert x == ansible_instance.env['ANSIBLE_FILTER_PLUGINS'].split(':')
Exemple #19
0
def with_scenario(request, scenario_to_test, driver_name, scenario_name, skip_test):
    scenario_directory = os.path.join(
        os.path.dirname(util.abs_path(__file__)),
        os.path.pardir,
        'scenarios',
        scenario_to_test,
    )

    with change_dir_to(scenario_directory):
        yield
        if scenario_name:
            msg = 'CLEANUP: Destroying instances for all scenario(s)'
            LOG.out(msg)
            options = {'driver_name': driver_name, 'all': True}
            cmd = sh.molecule.bake('destroy', **options)
            pytest.helpers.run_command(cmd)
Exemple #20
0
    def default_env(self):
        env = util.merge_dicts(os.environ.copy(), self._config.env)
        env = util.merge_dicts(
            env,
            {
                'ANSIBLE_CONFIG': self._config.provisioner.config_file,
                'ANSIBLE_ROLES_PATH': ':'.join(
                    [
                        util.abs_path(
                            os.path.join(
                                self._config.scenario.ephemeral_directory, 'roles'
                            )
                        ),
                        util.abs_path(
                            os.path.join(self._config.project_directory, os.path.pardir)
                        ),
                    ]
                ),
                'ANSIBLE_LIBRARY': ':'.join(
                    [
                        self._get_libraries_directory(),
                        util.abs_path(
                            os.path.join(
                                self._config.scenario.ephemeral_directory, 'library'
                            )
                        ),
                        util.abs_path(
                            os.path.join(self._config.project_directory, 'library')
                        ),
                    ]
                ),
                'ANSIBLE_FILTER_PLUGINS': ':'.join(
                    [
                        self._get_filter_plugin_directory(),
                        util.abs_path(
                            os.path.join(
                                self._config.scenario.ephemeral_directory,
                                'plugins',
                                'filters',
                            )
                        ),
                        util.abs_path(
                            os.path.join(
                                self._config.project_directory, 'plugins', 'filters'
                            )
                        ),
                    ]
                ),
            },
        )
        env = util.merge_dicts(env, self._config.env)

        return env
Exemple #21
0
def test_env_appends_env_property(_instance):
    x = [
        util.abs_path(
            os.path.join(_instance._config.scenario.ephemeral_directory,
                         "roles")),
        util.abs_path(
            os.path.join(_instance._config.project_directory, os.path.pardir)),
        util.abs_path(
            os.path.join(os.path.expanduser("~"), ".ansible", "roles")),
        "/usr/share/ansible/roles",
        "/etc/ansible/roles",
        util.abs_path(
            os.path.join(_instance._config.scenario.directory, "foo", "bar")),
    ]
    assert x == _instance.env["ANSIBLE_ROLES_PATH"].split(":")

    x = _instance._get_modules_directories()
    x.append(
        util.abs_path(
            os.path.join(_instance._config.scenario.directory, "foo", "bar")))
    assert x == _instance.env["ANSIBLE_LIBRARY"].split(":")

    x = [
        _instance._get_filter_plugin_directory(),
        util.abs_path(
            os.path.join(_instance._config.scenario.ephemeral_directory,
                         "plugins", "filter")),
        util.abs_path(
            os.path.join(_instance._config.project_directory, "plugins",
                         "filter")),
        util.abs_path(
            os.path.join(os.path.expanduser("~"), ".ansible", "plugins",
                         "filter")),
        "/usr/share/ansible/plugins/filter",
        util.abs_path(
            os.path.join(_instance._config.scenario.directory, "foo", "bar")),
    ]
    assert x == _instance.env["ANSIBLE_FILTER_PLUGINS"].split(":")
Exemple #22
0
def with_scenario(request, scenario_to_test, driver_name, scenario_name,
                  skip_test):
    scenario_directory = os.path.join(
        os.path.dirname(util.abs_path(__file__)),
        os.path.pardir,
        "scenarios",
        scenario_to_test,
    )

    with change_dir_to(scenario_directory):
        yield
        if scenario_name:
            msg = "CLEANUP: Destroying instances for all scenario(s)"
            LOG.out(msg)
            cmd = [
                "molecule", "destroy", "--driver-name", driver_name, "--all"
            ]
            pytest.helpers.run_command(cmd)
Exemple #23
0
def metadata_lint_update(role_directory):
    # By default, ansible-lint will fail on newly-created roles because the
    # fields in this file have not been changed from their defaults. This is
    # good because molecule should create this file using the defaults, and
    # users should receive feedback to change these defaults. However, this
    # blocks the testing of 'molecule init' itself, so ansible-lint should
    # be configured to ignore these metadata lint errors.
    ansible_lint_src = os.path.join(os.path.dirname(util.abs_path(__file__)),
                                    '.ansible-lint')
    shutil.copy(ansible_lint_src, role_directory)

    # Explicitly lint here to catch any unexpected lint errors before
    # continuining functional testing. Ansible lint is run at the root
    # of the role directory and pointed at the role directory to ensure
    # the customize ansible-lint config is used.
    with change_dir_to(role_directory):
        cmd = sh.ansible_lint.bake('.')
    pytest.helpers.run_command(cmd)
Exemple #24
0
def with_scenario(request, scenario_to_test, driver_name, scenario_name,
                  skip_test):
    scenario_directory = os.path.join(
        os.path.dirname(util.abs_path(__file__)), os.path.pardir, 'scenarios',
        scenario_to_test)

    os.chdir(scenario_directory)

    def cleanup():
        if scenario_name:
            msg = 'CLEANUP: Destroying instances for all scenario(s)'
            LOG.out(msg)
            options = {
                'driver_name': driver_name,
                'all': True,
            }
            cmd = sh.molecule.bake('destroy', **options)
            run_command(cmd)

    request.addfinalizer(cleanup)
Exemple #25
0
def with_scenario(request, scenario_to_test, driver_name, scenario_name,
                  skip_test):
    scenario_directory = os.path.join(os.path.dirname(util.abs_path(__file__)),
                                      os.path.pardir, 'scenarios',
                                      scenario_to_test)

    os.chdir(scenario_directory)

    def cleanup():
        if scenario_name:
            msg = 'CLEANUP: Destroying instances for all scenario(s)'
            LOG.out(msg)
            options = {
                'driver_name': driver_name,
                'all': True,
            }
            cmd = sh.molecule.bake('destroy', **options)
            run_command(cmd)

    request.addfinalizer(cleanup)
Exemple #26
0
def test_env(config_instance):
    config_instance.args = {"env_file": ".env"}
    x = {
        "MOLECULE_DEBUG": "False",
        "MOLECULE_FILE": config_instance.config_file,
        "MOLECULE_ENV_FILE": util.abs_path(config_instance.args.get("env_file")),
        "MOLECULE_INVENTORY_FILE": config_instance.provisioner.inventory_file,
        "MOLECULE_EPHEMERAL_DIRECTORY": config_instance.scenario.ephemeral_directory,
        "MOLECULE_SCENARIO_DIRECTORY": config_instance.scenario.directory,
        "MOLECULE_PROJECT_DIRECTORY": config_instance.project_directory,
        "MOLECULE_INSTANCE_CONFIG": config_instance.driver.instance_config,
        "MOLECULE_DEPENDENCY_NAME": "galaxy",
        "MOLECULE_DRIVER_NAME": "delegated",
        "MOLECULE_PROVISIONER_NAME": "ansible",
        "MOLECULE_SCENARIO_NAME": "default",
        "MOLECULE_STATE_FILE": config_instance.state.state_file,
        "MOLECULE_VERIFIER_NAME": "ansible",
        "MOLECULE_VERIFIER_TEST_DIRECTORY": config_instance.verifier.directory,
    }

    assert x == config_instance.env
Exemple #27
0
    def execute(self):
        """
        Execute the actions necessary to perform a `molecule init scenario` and
        returns None.

        :return: None
        """
        scenario_name = self._command_args['scenario_name']
        role_name = os.getcwd().split(os.sep)[-1]
        role_directory = util.abs_path(os.path.join(os.getcwd(), os.pardir))

        msg = 'Initializing new scenario {}...'.format(scenario_name)
        LOG.info(msg)
        molecule_directory = config.molecule_directory(
            os.path.join(role_directory, role_name)
        )
        scenario_directory = os.path.join(molecule_directory, scenario_name)
        scenario_base_directory = os.path.dirname(scenario_directory)

        if os.path.isdir(scenario_directory):
            msg = (
                'The directory molecule/{} exists. ' 'Cannot create new scenario.'
            ).format(scenario_name)
            util.sysexit_with_message(msg)

        scenario_base_directory = os.path.join(role_directory, role_name)
        templates = [
            'scenario/driver/{driver_name}'.format(**self._command_args),
            'scenario/verifier/{verifier_name}'.format(**self._command_args),
        ]
        for template in templates:
            self._process_templates(
                template, self._command_args, scenario_base_directory
            )
        self._process_templates('molecule', self._command_args, role_directory)

        role_directory = os.path.join(role_directory, role_name)
        msg = 'Initialized scenario in {} successfully.'.format(scenario_directory)
        LOG.success(msg)
Exemple #28
0
def get_configs(args, command_args, ansible_args=()):
    """
    Glob the current directory for Molecule config files, instantiate config
    objects, and returns a list.

    :param args: A dict of options, arguments and commands from the CLI.
    :param command_args: A dict of options passed to the subcommand from
     the CLI.
    :param ansible_args: An optional tuple of arguments provided to the
     `ansible-playbook` command.
    :return: list
    """
    configs = [
        config.Config(
            molecule_file=util.abs_path(c),
            args=args,
            command_args=command_args,
            ansible_args=ansible_args, ) for c in glob.glob(MOLECULE_GLOB)
    ]
    _verify_configs(configs)

    return configs
Exemple #29
0
    def execute(self):
        """
        Execute the actions necessary to perform a `molecule init scenario` and
        returns None.

        :return: None
        """
        scenario_name = self._command_args['scenario_name']
        role_name = os.getcwd().split(os.sep)[-1]
        role_directory = util.abs_path(os.path.join(os.getcwd(), os.pardir))

        msg = 'Initializing new scenario {}...'.format(scenario_name)
        LOG.info(msg)
        molecule_directory = config.molecule_directory(
            os.path.join(role_directory, role_name))
        scenario_directory = os.path.join(molecule_directory, scenario_name)
        scenario_base_directory = os.path.dirname(scenario_directory)

        if os.path.isdir(scenario_directory):
            msg = ('The directory molecule/{} exists. '
                   'Cannot create new scenario.').format(scenario_name)
            util.sysexit_with_message(msg)

        scenario_base_directory = os.path.join(role_directory, role_name)
        templates = [
            'scenario/driver/{driver_name}'.format(**self._command_args),
            'scenario/verifier/{verifier_name}'.format(**self._command_args),
        ]
        for template in templates:
            self._process_templates(template, self._command_args,
                                    scenario_base_directory)
        self._process_templates('molecule', self._command_args,
                                scenario_base_directory)

        role_directory = os.path.join(role_directory, role_name)
        msg = 'Initialized scenario in {} successfully.'.format(
            scenario_directory)
        LOG.success(msg)
Exemple #30
0
def get_configs(args, command_args, ansible_args=(), glob_str=MOLECULE_GLOB):
    """
    Glob the current directory for Molecule config files, instantiate config \
    objects, and returns a list.

    :param args: A dict of options, arguments and commands from the CLI.
    :param command_args: A dict of options passed to the subcommand from
     the CLI.
    :param ansible_args: An optional tuple of arguments provided to the
     `ansible-playbook` command.
    :return: list
    """
    configs = [
        config.Config(
            molecule_file=util.abs_path(c),
            args=args,
            command_args=command_args,
            ansible_args=ansible_args,
        ) for c in glob.glob(glob_str)
    ]
    _verify_configs(configs, glob_str)

    return configs
Exemple #31
0
    def default_env(self):
        env = self._config.merge_dicts(os.environ.copy(), self._config.env)
        env = self._config.merge_dicts(env, {
            'ANSIBLE_CONFIG':
            self._config.provisioner.config_file,
            'ANSIBLE_ROLES_PATH':
            ':'.join([
                util.abs_path(
                    os.path.join(self._config.project_directory,
                                 os.path.pardir)),
                util.abs_path(
                    os.path.join(self._config.scenario.ephemeral_directory,
                                 'roles'))
            ]),
            'ANSIBLE_LIBRARY':
            ':'.join([
                self._get_libraries_directory(),
                util.abs_path(
                    os.path.join(self._config.project_directory, 'library')),
                util.abs_path(
                    os.path.join(self._config.scenario.ephemeral_directory,
                                 'library')),
            ]),
            'ANSIBLE_FILTER_PLUGINS':
            ':'.join([
                self._get_filter_plugin_directory(),
                util.abs_path(
                    os.path.join(self._config.project_directory, 'plugins',
                                 'filters')),
                util.abs_path(
                    os.path.join(self._config.scenario.ephemeral_directory,
                                 'plugins', 'filters')),
            ]),
        })
        env = self._config.merge_dicts(env, self._config.env)

        return env
Exemple #32
0
 def env_file(self):
     return util.abs_path(self.args.get('env_file'))
Exemple #33
0
def test_abs_path_with_none_path():
    assert util.abs_path(None) is None
Exemple #34
0
def test_abs_path(temp_dir):
    x = os.path.abspath(os.path.join(os.getcwd(), os.path.pardir, "foo",
                                     "bar"))

    assert x == util.abs_path(os.path.join(os.path.pardir, "foo", "bar"))
Exemple #35
0
 def _get_playbook_directory(self):
     return util.abs_path(
         os.path.join(self._config.provisioner.directory, 'playbooks'))
Exemple #36
0
 def get_abs_path(self, path):
     return util.abs_path(
         os.path.join(self._config.scenario.directory, path))
Exemple #37
0
 def _get_libraries_directory(self):
     return util.abs_path(
         os.path.join(self._get_plugin_directory(), 'libraries'))
Exemple #38
0
 def _get_filter_plugin_directory(self):
     return util.abs_path(
         os.path.join(self._get_plugin_directory(), 'filters'))
Exemple #39
0
def test_abs_path(temp_dir):
    x = os.path.abspath(
        os.path.join(os.getcwd(), os.path.pardir, 'foo', 'bar'))

    assert x == util.abs_path(os.path.join(os.path.pardir, 'foo', 'bar'))