Ejemplo n.º 1
0
def save_config(module, result):
    result['changed'] = True
    if not module.check_mode:
        run_commands(module, 'copy running-config startup-config\r')
    else:
        module.warn('Skipping command `copy running-config startup-config` '
                    'due to check_mode.  Configuration not copied to '
                    'non-volatile storage')
def main():
    """main entry point for module execution
    """
    argument_spec = dict(commands=dict(type='list', required=True),
                         wait_for=dict(type='list', aliases=['waitfor']),
                         match=dict(default='all', choices=['all', 'any']),
                         retries=dict(default=10, type='int'),
                         interval=dict(default=1, type='int'))

    # argument_spec.update(qnos_argument_spec)

    module = AnsibleModule(argument_spec=argument_spec,
                           supports_check_mode=True)

    warnings = list()
    result = {'changed': False, 'warnings': warnings}
    # check_args(module, warnings)
    commands = parse_commands(module, warnings)
    wait_for = module.params['wait_for'] or list()

    try:
        conditionals = [Conditional(c) for c in wait_for]
    except AttributeError as exc:
        module.fail_json(msg=to_text(exc))

    retries = module.params['retries']
    interval = module.params['interval']
    match = module.params['match']

    while retries > 0:
        responses = run_commands(module, commands)

        for item in list(conditionals):
            if item(responses):
                if match == 'any':
                    conditionals = list()
                    break
                conditionals.remove(item)

        if not conditionals:
            break

        time.sleep(interval)
        retries -= 1

    if conditionals:
        failed_conditions = [item.raw for item in conditionals]
        msg = 'One or more conditional statements have not been satisfied'
        module.fail_json(msg=msg, failed_conditions=failed_conditions)

    result.update({
        'stdout': responses,
        'stdout_lines': list(to_lines(responses))
    })

    module.exit_json(**result)
Ejemplo n.º 3
0
    def populate_interface_info(self, data, interface_type):
        intf_info = dict()
        commands = list()
        if interface_type == 'port':
            commands.append('show interface status {0}'.format(data))
            commands.append('show ip interface port {0}'.format(data))
            commands.append('show ipv6 interface port {0}'.format(data))
        elif interface_type == 'vlan':
            commands.append('show interface status {0}'.format(data))
            commands.append('show ip interface {0}'.format(data))
            commands.append('show ipv6 interface {0}'.format(data))
        elif interface_type == 'loopback':
            id = data.split('lb')[1]
            commands.append('show interface status loopback {0}'.format(id))
            commands.append('show ip interface loopback {0}'.format(id))
            commands.append('show ipv6 interface loopback {0}'.format(id))
        elif interface_type == 'port-channel':
            id = data.split('ch')[1]
            commands.append(
                'show interface status port-channel {0}'.format(id))
        else:
            commands.append('show interface status {0}'.format(data))

        value = run_commands(self.module, commands=commands, check_rc=False)
        intf_info['description'] = self.parse_description(value[0])
        intf_info['adminmode'] = self.parse_adminmode(value[0])
        intf_info['macaddress'] = self.parse_macaddress(value[0])
        intf_info['capability'] = self.parse_capability(value[0])
        intf_info['physicalmode'] = self.parse_physicalmode(value[0])
        intf_info['physicalstatus'] = self.parse_physicalstatus(value[0])
        intf_info['lacpmode'] = self.parse_lacpmode(value[0])
        intf_info['linkstatus'] = self.parse_linkstatus(value[0])
        intf_info['mediatype'] = self.parse_mediatype(value[0])

        if len(value) > 2:
            ipv4 = self.parse_ipv4(value[1])
            intf_info['ipv4'] = self.parse_ipv4(value[1])
            if ipv4:
                self.add_ip_address(ipv4, 'ipv4')

            intf_info['mtu'] = self.parse_mtu(value[1])
            intf_info['bandwidth'] = self.parse_bandwidth(value[1])
            intf_info['linkspeed'] = self.parse_linkspeed(value[1])

            intf_info['ipv6'] = self.parse_ipv6(value[2])

        return intf_info
Ejemplo n.º 4
0
 def run(self, cmd):
     return run_commands(self.module, commands=cmd, check_rc=False)
Ejemplo n.º 5
0
 def populate(self):
     self.responses = run_commands(self.module,
                                   commands=self.COMMANDS,
                                   check_rc=False)
Ejemplo n.º 6
0
def main():
    """ main entry point for module execution
    """
    backup_spec = dict(
        filename=dict(),
        dir_path=dict(type='path')
    )
    argument_spec = dict(
        src=dict(type='path'),

        lines=dict(aliases=['commands'], type='list'),
        parents=dict(type='list'),

        before=dict(type='list'),
        after=dict(type='list'),

        match=dict(default='line', choices=['line', 'strict', 'exact', 'none']),
        replace=dict(default='line', choices=['line', 'block']),
        multiline_delimiter=dict(default='@'),

        running_config=dict(aliases=['config']),
        intended_config=dict(),

        defaults=dict(type='bool', default=False),
        backup=dict(type='bool', default=False),
        backup_options=dict(type='dict', options=backup_spec),
        save_when=dict(choices=['always', 'never', 'modified', 'changed'], default='never'),

        diff_against=dict(choices=['startup', 'intended', 'running']),
        diff_ignore_lines=dict(type='list'),
    )

    # argument_spec.update(qnos_argument_spec)

    mutually_exclusive = [('lines', 'src'),
                          ('parents', 'src')]

    required_if = [('match', 'strict', ['lines']),
                   ('match', 'exact', ['lines']),
                   ('replace', 'block', ['lines']),
                   ('diff_against', 'intended', ['intended_config'])]

    module = AnsibleModule(argument_spec=argument_spec,
                           mutually_exclusive=mutually_exclusive,
                           required_if=required_if,
                           supports_check_mode=True)

    result = {'changed': False}

    warnings = list()
    check_args(module, warnings)
    result['warnings'] = warnings

    diff_ignore_lines = module.params['diff_ignore_lines']
    config = None
    contents = None
    flags = get_defaults_flag(module) if module.params['defaults'] else []
    connection = get_connection(module)

    if module.params['backup'] or (module._diff and module.params['diff_against'] == 'running'):
        contents = get_config(module, flags=flags)
        config = QnosNetworkConfig(indent=0, contents=contents)
        if module.params['backup']:
            result['__backup__'] = contents

    if any((module.params['lines'], module.params['src'])):
        match = module.params['match']
        replace = module.params['replace']
        path = module.params['parents']

        candidate = get_candidate_config(module)
        running = get_running_config(module, contents, flags=flags)
        try:
            response = connection.get_diff(candidate=candidate, running=running, diff_match=match, diff_ignore_lines=diff_ignore_lines, path=path,
                                           diff_replace=replace)
        except ConnectionError as exc:
            module.fail_json(msg=to_text(exc, errors='surrogate_then_replace'))

        config_diff = response['config_diff']

        if config_diff:
            commands = config_diff.split('\n')

            if module.params['before']:
                commands[:0] = module.params['before']

            if module.params['after']:
                commands.extend(module.params['after'])

            result['commands'] = commands
            result['updates'] = commands

            # send the configuration commands to the device and merge
            # them with the current running config
            if not module.check_mode:
                if commands:
                    edit_config_or_macro(connection, commands)

            result['changed'] = True

    running_config = module.params['running_config']
    startup_config = None

    if module.params['save_when'] == 'always':
        save_config(module, result)
    elif module.params['save_when'] == 'modified':
        output = run_commands(module, ['show running-config', 'show startup-config'])

        running_config = QnosNetworkConfig(indent=0, contents=output[0], ignore_lines=diff_ignore_lines)
        startup_config = QnosNetworkConfig(indent=0, contents=output[1], ignore_lines=diff_ignore_lines)

        if running_config.sha1 != startup_config.sha1:
            save_config(module, result)
    elif module.params['save_when'] == 'changed' and result['changed']:
        save_config(module, result)

    if module._diff:
        if not running_config:
            output = run_commands(module, 'show running-config')
            contents = output[0]
        else:
            contents = running_config

        # recreate the object in order to process diff_ignore_lines
        running_config = QnosNetworkConfig(indent=0, contents=contents, ignore_lines=diff_ignore_lines)

        if module.params['diff_against'] == 'running':
            if module.check_mode:
                module.warn("unable to perform diff against running-config due to check mode")
                contents = None
            else:
                contents = config.config_text

        elif module.params['diff_against'] == 'startup':
            if not startup_config:
                output = run_commands(module, 'show startup-config')
                contents = output[0]
            else:
                contents = startup_config.config_text

        elif module.params['diff_against'] == 'intended':
            contents = module.params['intended_config']

        if contents is not None:
            base_config = QnosNetworkConfig(indent=0, contents=contents, ignore_lines=diff_ignore_lines)

            if running_config.sha1 != base_config.sha1:
                if module.params['diff_against'] == 'intended':
                    before = running_config
                    after = base_config
                elif module.params['diff_against'] in ('startup', 'running'):
                    before = base_config
                    after = running_config

                result.update({
                    'changed': True,
                    'diff': {'before': str(before), 'after': str(after)}
                })

    module.exit_json(**result)