示例#1
0
    def setUpClass(cls):
        cls.os = 'ios'
        cls.options_file = os.path.join(
            os.path.dirname(os.path.realpath(__file__)),
            'files',
            'test_options_ios.yml',
        )
        cls.tags_file = os.path.join(
            os.path.dirname(os.path.realpath(__file__)),
            'files',
            'test_tags_ios.yml',
        )
        cls.running_cfg = os.path.join(
            os.path.dirname(os.path.realpath(__file__)),
            'files',
            'running_config.conf',
        )
        cls.compiled_cfg = os.path.join(
            os.path.dirname(os.path.realpath(__file__)),
            'files',
            'compiled_config.conf',
        )

        with open(cls.tags_file) as f:
            cls.tags = yaml.safe_load(f.read())

        with open(cls.options_file) as f:
            cls.options = yaml.safe_load(f.read())

        cls.host_a = Host('example1.rtr', cls.os, cls.options)
        cls.host_b = Host('example2.rtr', cls.os, cls.options)
示例#2
0
    def __init__(self, hostname=None, os=None, options=None, host=None):
        if all([i is not None for i in (hostname, os, options)]):
            from hier_config.host import Host
            from warnings import warn
            self._host = Host(hostname, os, options)
            warning_message = """
            hostname, os, and options variables are being deprecated in version 2.0.0.
            Use the Host object going forward.
            Example:
                from hier_config.host import Host
                import yaml
                options = yaml.load(open('./tests/files/test_options_ios.yml'))
                host = Host({}, {}, options)
                hier = HConfig(host=host)""".format(hostname, os)
            warn(warning_message, SyntaxWarning)
        elif host is not None:
            assert hasattr(host, 'hostname')
            assert hasattr(host, 'os')
            assert hasattr(host, 'hconfig_options')
            self._host = host
        else:
            raise AttributeError('Error determining host object')

        self._options = self.host.hconfig_options
        self._text = str()
        self._logs = list()
        self.children = []
        self.children_dict = {}
示例#3
0
    def setUpClass(cls):
        cls.os = 'comware5'
        cls.options_file = os.path.join(
            os.path.dirname(os.path.realpath(__file__)),
            'files',
            'test_options_negate_with_undo.yml',
        )
        cls.running_cfg = 'test_for_undo\nundo test_for_redo\n'
        cls.compiled_cfg = 'undo test_for_undo\ntest_for_redo\n'
        cls.remediation = 'undo test_for_undo\ntest_for_redo\n'

        with open(cls.options_file) as f:
            cls.options = yaml.safe_load(f.read())

        cls.host_a = Host('example1.rtr', cls.os, cls.options)
示例#4
0
class TestNegateWithUndo:
    @pytest.fixture(autouse=True)
    def setUpClass(self, options_negate_with_undo):
        self.os = "comware5"
        self.running_config = "test_for_undo\nundo test_for_redo"
        self.generated_config = "undo test_for_undo\ntest_for_redo"
        self.remediation = "undo test_for_undo\ntest_for_redo"
        self.host = Host("example1.rtr", self.os, options_negate_with_undo)

    def test_merge(self):
        self.host.load_running_config(self.running_config)
        self.host.load_generated_config(self.generated_config)
        self.host.remediation_config()
        assert self.remediation == str(self.host.remediation_config())
示例#5
0
    def setUpClass(cls):
        cls.running_file = os.path.join(
            os.path.dirname(os.path.realpath(__file__)), 'files',
            'running_config.conf')
        cls.compiled_file = os.path.join(
            os.path.dirname(os.path.realpath(__file__)), 'files',
            'compiled_config.conf')
        cls.options_file = os.path.join(
            os.path.dirname(os.path.realpath(__file__)), 'files',
            'test_options_ios.yml')
        cls.tags_file = os.path.join(
            os.path.dirname(os.path.realpath(__file__)), 'files',
            'test_tags_ios.yml')
        cls.hconfig_tags = yaml.load(open(cls.tags_file))
        cls.hconfig_options = yaml.load(open(cls.options_file))
        cls.host = Host('example.rtr', 'ios', cls.hconfig_options)

        with open(cls.compiled_file) as f:
            cls.compiled_string = f.read()
示例#6
0
 def setup(self, options_ios):
     self.host = Host("example.rtr", "ios", options_ios)
示例#7
0
class TestHost:
    @pytest.fixture(autouse=True)
    def setup(self, options_ios):
        self.host = Host("example.rtr", "ios", options_ios)

    def test_load_config_from(self, running_config, generated_config):
        self.host.load_running_config(running_config)
        self.host.load_generated_config(generated_config)

        assert len(self.host.generated_config) > 0
        assert len(self.host.running_config) > 0

    def test_load_remediation(self, running_config, generated_config):
        self.host.load_running_config(running_config)
        self.host.load_generated_config(generated_config)
        self.host.remediation_config()

        assert len(self.host.remediation_config().children) > 0

    def test_load_tags(self, tags_ios):
        self.host.load_tags(tags_ios)
        assert len(self.host.hconfig_tags) > 0

    def test_filter_remediation(self, running_config, generated_config,
                                tags_ios):
        self.host.load_running_config(running_config)
        self.host.load_generated_config(generated_config)
        self.host.load_tags(tags_ios)

        rem1 = self.host.remediation_config_filtered_text(set(), set())
        rem2 = self.host.remediation_config_filtered_text({"safe"}, set())

        assert rem1 != rem2
示例#8
0
def main():
    module = AnsibleModule(
        argument_spec=dict(
            hostname=dict(required=True),
            compiled_config=dict(required=True),
            running_config=dict(required=True),
            remediation_config=dict(required=True),
            os_role=dict(required=True),
            include_tags=dict(required=False, type='list'),
            exclude_tags=dict(required=False, type='list'),
        ),
        required_together=(
            ['hostname',
             'compiled_config',
             'running_config',
             'remediation_config',
             'os_role']
        ),
        supports_check_mode=False
    )

    hostname = str(module.params['hostname'])
    compiled_config = str(module.params['compiled_config'])
    running_config = str(module.params['running_config'])
    remediation_config = str(module.params['remediation_config'])
    os_role = str(module.params['os_role'])
    operating_system = os_role.strip('os_')

    if module.params['include_tags']:
        include_tags = list(module.params['include_tags'])
    else:
        include_tags = list()

    if module.params['exclude_tags']:
        exclude_tags = list(module.params['exclude_tags'])
    else:
        exclude_tags = list()

    hier_files = ['hierarchical_configuration_options.yml',
                  'hierarchical_configuration_tags.yml']

    for item in hier_files:
        if not os.path.isfile('roles/{}/vars/{}'.format(
                os_role, item)):
            module.fail_json(msg="Error opening {}.".format(item))

    hier_options = yaml.safe_load(open('roles/{}/vars/{}'.format(
        os_role,
        'hierarchical_configuration_options.yml')))

    hier_tags = yaml.safe_load(open('roles/{}/vars/{}'.format(
        os_role,
        'hierarchical_configuration_tags.yml')))

    host = Host(hostname, operating_system, hier_options)

    if os.path.isfile(running_config):
        host.load_config_from(config_type="running", name=running_config)
    else:
        module.fail_json(msg="Error opening {}.".format(running_config))

    if os.path.isfile(compiled_config):
        host.load_config_from(config_type="compiled", name=compiled_config)
    else:
        module.fail_json(msg="Error opening {}.".format(compiled_config))

    host.load_tags(hier_tags, file=False)
    host.load_remediation()

    if include_tags or exclude_tags:
        host.filter_remediation(include_tags=include_tags, exclude_tags=exclude_tags)

    with open(remediation_config, 'w') as f:
        f.write(host.facts['remediation_config_raw'])

    with open(remediation_config) as f:
        remediation_config = f.read()

    results = dict()
    results['response'] = remediation_config

    if remediation_config:
        module.exit_json(changed=True, **results)
    else:
        module.exit_json(changed=False)
def main():
    module = AnsibleModule(
        argument_spec=dict(
            hostname=dict(required=True, type="str"),
            generated_config=dict(required=False, type="str"),
            generated_config_string=dict(required=False, type="str"),
            running_config=dict(required=False, type="str"),
            running_config_string=dict(required=False, type="str"),
            remediation_config=dict(required=False, type="str"),
            os_role=dict(required=True, type="str"),
            options_file=dict(required=False, type="str"),
            tags_file=dict(required=False, type="str"),
            include_tags=dict(required=False, type="list"),
            exclude_tags=dict(required=False, type="list"),
        ),
        required_one_of=[
            ["generated_config", "generated_config_string"],
            ["running_config", "running_config_string"],
        ],
        mutually_exclusive=[
            ["generated_config", "generated_config_string"],
            ["running_config", "running_config_string"],
        ],
        supports_check_mode=False,
    )
    changed = False
    hostname = module.params["hostname"]
    remediation_config = module.params["remediation_config"]
    os_role = module.params["os_role"]
    operating_system = os_role.strip("os_")
    include_tags = (module.params["include_tags"]
                    if module.params["include_tags"] else None)
    exclude_tags = (module.params["exclude_tags"]
                    if module.params["exclude_tags"] else None)
    hier_options = _load_hier("options", os_role=os_role, module=module)
    hier_tags = _load_hier("tags", os_role=os_role, module=module)

    host = Host(hostname, operating_system, hier_options)
    if module.params["running_config"]:
        host.load_running_config_from_file(
            file=module.params["running_config"])
    else:
        host.load_running_config(
            config_text=module.params["running_config_string"])

    if module.params["generated_config"]:
        host.load_generated_config_from_file(
            file=module.params["generated_config"])
    else:
        host.load_generated_config(
            config_text=module.params["generated_config_string"])

    host.load_tags(hier_tags)
    host.remediation_config()
    remediation_obj = host.remediation_config_filtered_text(
        include_tags=include_tags, exclude_tags=exclude_tags)

    remediation_config_string = "".join([line for line in remediation_obj])

    if remediation_config is not None:
        md5_original = None
        if os.path.isfile(remediation_config):
            md5_original = hashlib.md5(
                open(remediation_config).read().encode("utf-8")).hexdigest()

        with open(remediation_config, "w") as tmp:
            tmp.write(remediation_config_string)

        md5_new = hashlib.md5(
            open(remediation_config).read().encode("utf-8")).hexdigest()

        if len({md5_new, md5_original}) > 1:
            changed = True
    else:
        if remediation_config_string:
            changed = True

    module.exit_json(changed=changed, response=remediation_config_string)
示例#10
0
 def setUpClass(self, options_negate_with_undo):
     self.os = "comware5"
     self.running_config = "test_for_undo\nundo test_for_redo"
     self.generated_config = "undo test_for_undo\ntest_for_redo"
     self.remediation = "undo test_for_undo\ntest_for_redo"
     self.host = Host("example1.rtr", self.os, options_negate_with_undo)