コード例 #1
0
ファイル: junos_netconf.py プロジェクト: vharishgup/ansible-1
def main():
    """main entry point for module execution
    """
    argument_spec = dict(
        netconf_port=dict(type='int', default=830, aliases=['listens_on']),
        state=dict(default='present', choices=['present', 'absent']),
    )

    argument_spec.update(junos_argument_spec)

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

    warnings = list()
    check_args(module, warnings)

    result = {'changed': False, 'warnings': warnings}

    want = map_params_to_obj(module)
    have = map_config_to_obj(module)

    commands = map_obj_to_commands((want, have), module)
    result['commands'] = commands

    if commands:
        commit = not module.check_mode
        diff = load_config(module, commands, commit=commit)
        if diff:
            if module._diff:
                result['diff'] = {'prepared': diff}
            result['changed'] = True

    module.exit_json(**result)
コード例 #2
0
ファイル: junos_netconf.py プロジェクト: ernstp/ansible
def main():
    """main entry point for module execution
    """
    argument_spec = dict(
        netconf_port=dict(type='int', default=830, aliases=['listens_on']),
        state=dict(default='present', choices=['present', 'absent']),
    )

    argument_spec.update(junos_argument_spec)

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

    warnings = list()
    check_args(module, warnings)

    result = {'changed': False, 'warnings': warnings}

    want = map_params_to_obj(module)
    have = map_config_to_obj(module)

    commands = map_obj_to_commands((want, have), module)
    result['commands'] = commands

    if commands:
        commit = not module.check_mode
        diff = load_config(module, commands, commit=commit)
        if diff:
            if module._diff:
                result['diff'] = {'prepared': diff}
            result['changed'] = True

    module.exit_json(**result)
コード例 #3
0
def main():
    """ main entry point for module execution
    """
    argument_spec = dict(
        name=dict(required=True),
        description=dict(),
        rd=dict(type='list'),
        interfaces=dict(type='list'),
        target=dict(type='list'),
        aggregate=dict(type='list'),
        purge=dict(default=False, type='bool'),
        state=dict(default='present', choices=['present', 'absent']),
        active=dict(default=True, type='bool')
    )

    argument_spec.update(junos_argument_spec)

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

    warnings = list()
    check_args(module, warnings)

    result = {'changed': False}

    if warnings:
        result['warnings'] = warnings

    top = 'routing-instances/instance'

    param_to_xpath_map = collections.OrderedDict()
    param_to_xpath_map.update([
        ('name', {'xpath': 'name', 'is_key': True}),
        ('description', 'description'),
        ('type', 'instance-type'),
        ('rd', 'route-distinguisher/rd-type'),
        ('interfaces', 'interface/name'),
        ('target', 'vrf-target/community'),
    ])

    module.params['type'] = 'vrf'

    want = map_params_to_obj(module, param_to_xpath_map)
    ele = map_obj_to_ele(module, want, top)

    with locked_config(module):
        diff = load_config(module, tostring(ele), warnings, action='replace')

        commit = not module.check_mode
        if diff:
            if commit:
                commit_configuration(module)
            else:
                discard_changes(module)
            result['changed'] = True

            if module._diff:
                result['diff'] = {'prepared': diff}

    module.exit_json(**result)
コード例 #4
0
ファイル: junos_lldp.py プロジェクト: ernstp/ansible
def main():
    """ main entry point for module execution
    """
    argument_spec = dict(
        interval=dict(type='int'),
        transmit_delay=dict(type='int'),
        hold_multiplier=dict(type='int'),
        state=dict(default='present', choices=['present', 'absent', 'enabled', 'disabled']),
        active=dict(default=True, type='bool')
    )

    argument_spec.update(junos_argument_spec)

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

    warnings = list()
    check_args(module, warnings)

    result = {'changed': False}

    if warnings:
        result['warnings'] = warnings

    top = 'protocols/lldp'

    param_to_xpath_map = collections.OrderedDict()
    param_to_xpath_map.update([
        ('interval', {'xpath': 'advertisement-interval', 'leaf_only': True}),
        ('transmit_delay', {'xpath': 'transmit-delay', 'leaf_only': True}),
        ('hold_multiplier', {'xpath': 'hold-multiplier', 'leaf_only': True}),
        ('disable', {'xpath': 'disable', 'tag_only': True, 'is_key': True})
    ])

    item = module.params.copy()
    state = item.get('state')

    item['disable'] = True if state in ('disabled', 'absent') else False

    if state in ('enabled', 'disabled'):
        item['state'] = 'present'

    want = map_params_to_obj(module, param_to_xpath_map, param=item)
    ele = map_obj_to_ele(module, want, top, param=item)

    with locked_config(module):
        diff = load_config(module, tostring(ele), warnings, action='merge')

        commit = not module.check_mode
        if diff:
            if commit:
                commit_configuration(module)
            else:
                discard_changes(module)
            result['changed'] = True

            if module._diff:
                result['diff'] = {'prepared': diff}

    module.exit_json(**result)
コード例 #5
0
def main():
    """ main entry point for module execution
    """
    argument_spec = dict(
        name=dict(),
        aggregate=dict(type='list'),
        purge=dict(default=False, type='bool'),
        state=dict(default='present',
                   choices=['present', 'absent', 'enabled', 'disabled']),
        active=dict(default=True, type='bool'))

    argument_spec.update(junos_argument_spec)

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

    warnings = list()
    check_args(module, warnings)

    result = {'changed': False}

    if warnings:
        result['warnings'] = warnings

    top = 'protocols/lldp/interface'

    param_to_xpath_map = collections.OrderedDict()
    param_to_xpath_map.update([('name', {
        'xpath': 'name',
        'is_key': True
    }), ('disable', {
        'xpath': 'disable',
        'tag_only': True
    })])

    item = module.params.copy()
    state = item.get('state')
    item['disable'] = True if state in ('disabled', 'absent') else False

    if state in ('enabled', 'disabled'):
        item['state'] = 'present'

    want = map_params_to_obj(module, param_to_xpath_map)
    ele = map_obj_to_ele(module, want, top)

    with locked_config(module):
        diff = load_config(module, tostring(ele), warnings, action='replace')

        commit = not module.check_mode
        if diff:
            if commit:
                commit_configuration(module)
            else:
                discard_changes(module)
            result['changed'] = True

            if module._diff:
                result['diff'] = {'prepared': diff}

    module.exit_json(**result)
コード例 #6
0
def main():
    """ main entry point for module execution
    """
    element_spec = dict(name=dict(),
                        full_name=dict(),
                        role=dict(choices=ROLES, default='unauthorized'),
                        sshkey=dict(),
                        state=dict(choices=['present', 'absent'],
                                   default='present'),
                        active=dict(default=True, type='bool'))

    argument_spec = dict(aggregate=dict(type='list',
                                        elements='dict',
                                        options=element_spec,
                                        aliases=['collection', 'users']),
                         purge=dict(default=False, type='bool'))

    argument_spec.update(element_spec)
    argument_spec.update(junos_argument_spec)

    required_one_of = [['aggregate', 'name']]
    mutually_exclusive = [['aggregate', 'name'], ['aggregate', 'full_name'],
                          ['aggregate', 'sshkey'], ['aggregate', 'state'],
                          ['aggregate', 'active']]

    argument_spec.update(junos_argument_spec)

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

    warnings = list()
    check_args(module, warnings)

    result = {'changed': False, 'warnings': warnings}

    want = map_params_to_obj(module)
    ele = map_obj_to_ele(want)

    kwargs = {}
    if module.params['purge']:
        kwargs['action'] = 'replace'

    with locked_config(module):
        diff = load_config(module, tostring(ele), warnings, **kwargs)

        commit = not module.check_mode
        if diff:
            if commit:
                commit_configuration(module)
            else:
                discard_changes(module)
            result['changed'] = True

            if module._diff:
                result['diff'] = {'prepared': diff}

    module.exit_json(**result)
コード例 #7
0
def main():
    """ main entry point for module execution
    """
    argument_spec = dict(
        name=dict(required=True),
        vlan_id=dict(required=True, type='int'),
        description=dict(),
        interfaces=dict(),
        collection=dict(),
        purge=dict(default=False, type='bool'),
        state=dict(default='present',
                   choices=['present', 'absent', 'active', 'suspend']))

    argument_spec.update(junos_argument_spec)

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

    warnings = list()
    check_args(module, warnings)

    result = {'changed': False}

    if warnings:
        result['warnings'] = warnings

    top = 'vlans/vlan'

    param_to_xpath_map = collections.OrderedDict()
    param_to_xpath_map.update({
        'name': {
            'xpath': 'name',
            'is_key': True
        },
        'vlan_id': 'vlan-id',
        'description': 'description'
    })

    validate_param_values(module, param_to_xpath_map)

    want = list()
    want.append(map_params_to_obj(module, param_to_xpath_map))
    ele = map_obj_to_ele(module, want, top)

    kwargs = {'commit': not module.check_mode}
    kwargs['action'] = 'replace'

    diff = load_config(module, tostring(ele), warnings, **kwargs)

    if diff:
        result.update({
            'changed': True,
            'diff': {
                'prepared': diff
            },
            'rpc': tostring(ele)
        })

    module.exit_json(**result)
コード例 #8
0
ファイル: junos_banner.py プロジェクト: tiwood/ansible
def main():
    """ main entry point for module execution
    """
    argument_spec = dict(
        banner=dict(required=True, choices=['login', 'motd']),
        text=dict(),
        state=dict(default='present',
                   choices=['present', 'absent', 'active', 'suspend']))

    argument_spec.update(junos_argument_spec)

    required_if = [('state', 'present', ('text', ))]

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

    warnings = list()
    check_args(module, warnings)

    result = {'changed': False}

    if warnings:
        result['warnings'] = warnings

    top = 'system/login'

    param_to_xpath_map = collections.OrderedDict()

    param_to_xpath_map.update({
        'text': {
            'xpath': 'message'
            if module.params['banner'] == 'login' else 'announcement',
            'leaf_only': True
        }
    })

    validate_param_values(module, param_to_xpath_map)

    want = list()
    want.append(map_params_to_obj(module, param_to_xpath_map))
    ele = map_obj_to_ele(module, want, top)

    kwargs = {'commit': not module.check_mode}
    kwargs['action'] = 'replace'

    diff = load_config(module, tostring(ele), warnings, **kwargs)

    if diff:
        result.update({
            'changed': True,
            'diff': {
                'prepared': diff
            },
            'rpc': tostring(ele)
        })

    module.exit_json(**result)
コード例 #9
0
ファイル: junos_rpc.py プロジェクト: ernstp/ansible
def main():
    """main entry point for Ansible module
    """
    argument_spec = dict(
        rpc=dict(required=True),
        args=dict(type='dict'),
        output=dict(default='xml', choices=['xml', 'json', 'text']),
    )

    argument_spec.update(junos_argument_spec)

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

    warnings = list()
    check_args(module, warnings)

    result = {'changed': False, 'warnings': warnings}

    rpc = str(module.params['rpc']).replace('_', '-')

    if all((module.check_mode, not rpc.startswith('get'))):
        module.fail_json(msg='invalid rpc for running in check_mode')

    args = module.params['args'] or {}

    xattrs = {'format': module.params['output']}

    element = Element(module.params['rpc'], xattrs)

    for key, value in iteritems(args):
        key = str(key).replace('_', '-')
        if isinstance(value, list):
            for item in value:
                child = SubElement(element, key)
                if item is not True:
                    child.text = item
        else:
            child = SubElement(element, key)
            if value is not True:
                child.text = value

    reply = send_request(module, element)

    result['xml'] = str(tostring(reply))

    if module.params['output'] == 'text':
        data = reply.find('.//output')
        result['output'] = data.text.strip()
        result['output_lines'] = result['output'].split('\n')

    elif module.params['output'] == 'json':
        result['output'] = module.from_json(reply.text.strip())

    else:
        result['output'] = str(tostring(reply)).split('\n')

    module.exit_json(**result)
コード例 #10
0
ファイル: junos_l3_interface.py プロジェクト: zdoop/ansible
def main():
    """ main entry point for module execution
    """
    argument_spec = dict(
        name=dict(required=True),
        ipv4=dict(),
        ipv6=dict(),
        unit=dict(default=0, type='int'),
        aggregate=dict(),
        purge=dict(default=False, type='bool'),
        state=dict(default='present', choices=['present', 'absent']),
        active=dict(default=True, type='bool')
    )

    argument_spec.update(junos_argument_spec)

    required_one_of = [['ipv4', 'ipv6']]

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

    warnings = list()
    check_args(module, warnings)

    result = {'changed': False}

    if warnings:
        result['warnings'] = warnings

    top = 'interfaces/interface'

    param_to_xpath_map = collections.OrderedDict()
    param_to_xpath_map.update([
        ('name', {'xpath': 'name', 'parent_attrib': False, 'is_key': True}),
        ('unit', {'xpath': 'name', 'top': 'unit', 'parent_attrib': False, 'is_key': True}),
        ('ipv4', {'xpath': 'inet/address/name', 'top': 'unit/family', 'is_key': True}),
        ('ipv6', {'xpath': 'inet6/address/name', 'top': 'unit/family', 'is_key': True})
    ])

    want = map_params_to_obj(module, param_to_xpath_map)
    ele = map_obj_to_ele(module, want, top)

    with locked_config(module):
        diff = load_config(module, tostring(ele), warnings, action='replace')

        commit = not module.check_mode
        if diff:
            if commit:
                commit_configuration(module)
            else:
                discard_changes(module)
            result['changed'] = True

            if module._diff:
                result['diff'] = {'prepared': diff}

    module.exit_json(**result)
コード例 #11
0
ファイル: junos_rpc.py プロジェクト: lancerenteria/doFlask
def main():
    """main entry point for Ansible module
    """
    argument_spec = dict(
        rpc=dict(required=True),
        args=dict(type='dict'),
        output=dict(default='xml', choices=['xml', 'json', 'text']),
    )

    argument_spec.update(junos_argument_spec)

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

    warnings = list()
    check_args(module, warnings)

    result = {'changed': False, 'warnings': warnings}

    rpc = str(module.params['rpc']).replace('_', '-')

    if all((module.check_mode, not rpc.startswith('get'))):
        module.fail_json(msg='invalid rpc for running in check_mode')

    args = module.params['args'] or {}

    xattrs = {'format': module.params['output']}

    element = Element(module.params['rpc'], xattrs)

    for key, value in iteritems(args):
        key = str(key).replace('_', '-')
        if isinstance(value, list):
            for item in value:
                child = SubElement(element, key)
                if item is not True:
                    child.text = item
        else:
            child = SubElement(element, key)
            if value is not True:
                child.text = value

    reply = send_request(module, element)

    result['xml'] = str(tostring(reply))

    if module.params['output'] == 'text':
        data = reply.find('.//output')
        result['output'] = data.text.strip()
        result['output_lines'] = result['output'].split('\n')

    elif module.params['output'] == 'json':
        result['output'] = module.from_json(reply.text.strip())

    else:
        result['output'] = str(tostring(reply)).split('\n')

    module.exit_json(**result)
コード例 #12
0
def main():
    """ main entry point for module execution
    """
    argument_spec = dict(banner=dict(required=True, choices=['login', 'motd']),
                         text=dict(),
                         state=dict(default='present',
                                    choices=['present', 'absent']),
                         active=dict(default=True, type='bool'))

    argument_spec.update(junos_argument_spec)

    required_if = [('state', 'present', ('text', ))]

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

    warnings = list()
    check_args(module, warnings)

    result = {'changed': False}

    if warnings:
        result['warnings'] = warnings

    top = 'system/login'

    param_to_xpath_map = collections.OrderedDict()

    param_to_xpath_map.update([('text', {
        'xpath':
        'message' if module.params['banner'] == 'login' else 'announcement',
        'leaf_only':
        True
    })])

    validate_param_values(module, param_to_xpath_map)

    want = map_params_to_obj(module, param_to_xpath_map)
    ele = map_obj_to_ele(module, want, top)

    with locked_config(module):
        diff = load_config(module, tostring(ele), warnings, action='replace')

        commit = not module.check_mode
        if diff:
            if commit:
                commit_configuration(module)
            else:
                discard_changes(module)
            result['changed'] = True

            if module._diff:
                result['diff'] = {'prepared': diff}

    module.exit_json(**result)
コード例 #13
0
ファイル: junos_banner.py プロジェクト: ernstp/ansible
def main():
    """ main entry point for module execution
    """
    argument_spec = dict(
        banner=dict(required=True, choices=['login', 'motd']),
        text=dict(),
        state=dict(default='present', choices=['present', 'absent']),
        active=dict(default=True, type='bool')
    )

    argument_spec.update(junos_argument_spec)

    required_if = [('state', 'present', ('text',))]

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

    warnings = list()
    check_args(module, warnings)

    result = {'changed': False}

    if warnings:
        result['warnings'] = warnings

    top = 'system/login'

    param_to_xpath_map = collections.OrderedDict()

    param_to_xpath_map.update([
        ('text', {'xpath': 'message' if module.params['banner'] == 'login' else 'announcement', 'leaf_only': True})
    ])

    validate_param_values(module, param_to_xpath_map)

    want = map_params_to_obj(module, param_to_xpath_map)
    ele = map_obj_to_ele(module, want, top)

    with locked_config(module):
        diff = load_config(module, tostring(ele), warnings, action='merge')

        commit = not module.check_mode
        if diff:
            if commit:
                commit_configuration(module)
            else:
                discard_changes(module)
            result['changed'] = True

            if module._diff:
                result['diff'] = {'prepared': diff}

    module.exit_json(**result)
コード例 #14
0
ファイル: _junos_template.py プロジェクト: zdoop/ansible
def main():

    argument_spec = dict(
        src=dict(required=True, type='path'),
        confirm=dict(default=0, type='int'),
        comment=dict(default=DEFAULT_COMMENT),
        action=dict(default='merge', choices=['merge', 'overwrite',
                                              'replace']),
        config_format=dict(choices=['text', 'set', 'xml'], default='text'),
        backup=dict(default=False, type='bool'),
    )

    argument_spec.update(junos_argument_spec)

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

    warnings = list()
    check_args(module, warnings)

    result = {'changed': False, 'warnings': warnings}

    commit = not module.check_mode
    action = module.params['action']
    src = module.params['src']
    fmt = module.params['config_format']

    if action == 'overwrite' and fmt == 'set':
        module.fail_json(
            msg=
            "overwrite cannot be used when format is set per junos-pyez documentation"
        )

    if module.params['backup']:
        reply = get_configuration(module, format='set')
        match = reply.find('.//configuration-set')
        if match is None:
            module.fail_json(msg='unable to retrieve device configuration')
        result['__backup__'] = str(match.text).strip()

    with locked_config(module):
        diff = load_config(module, src, warnings, action=action, format=fmt)
        if diff:
            if commit:
                commit_configuration(module)
            else:
                discard_changes(module)
            result['changed'] = True

            if module._diff:
                result['diff'] = {'prepared': diff}

    module.exit_json(**result)
コード例 #15
0
def main():
    """ main entry point for module execution
    """
    argument_spec = dict(
        users=dict(type='list', aliases=['collection']),
        name=dict(),

        full_name=dict(),
        role=dict(choices=ROLES, default='unauthorized'),
        sshkey=dict(),

        purge=dict(type='bool'),

        state=dict(choices=['present', 'absent'], default='present'),
        active=dict(default=True, type='bool')
    )

    mutually_exclusive = [('users', 'name')]

    argument_spec.update(junos_argument_spec)

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

    warnings = list()
    check_args(module, warnings)

    result = {'changed': False, 'warnings': warnings}

    want = map_params_to_obj(module)
    ele = map_obj_to_ele(want)

    kwargs = {'commit': not module.check_mode}
    if module.params['purge']:
        kwargs['action'] = 'replace'

    diff = load_config(module, tostring(ele), warnings, **kwargs)

    if diff:
        result.update({
            'changed': True,
            'diff': diff
        })

    module.exit_json(**result)
コード例 #16
0
def main():

    argument_spec = dict(
        src=dict(required=True, type='path'),
        confirm=dict(default=0, type='int'),
        comment=dict(default=DEFAULT_COMMENT),
        action=dict(default='merge', choices=['merge', 'overwrite',
                                              'replace']),
        config_format=dict(choices=['text', 'set', 'xml']),
        backup=dict(default=False, type='bool'),
    )

    argument_spec.update(junos_argument_spec)

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

    check_transport(module)

    warnings = list()
    check_args(module, warnings)

    result = {'changed': False, 'warnings': warnings}

    comment = module.params['comment']
    confirm = module.params['confirm']
    commit = not module.check_mode
    action = module.params['action']
    src = module.params['src']
    fmt = module.params['config_format']

    if action == 'overwrite' and fmt == 'set':
        module.fail_json(msg="overwrite cannot be used when format is "
                         "set per junos-pyez documentation")

    if module.params['backup']:
        result['__backup__'] = text_type(get_configuration(module))

    diff = load(module, src, action=action, commit=commit, format=fmt)
    if diff:
        result['changed'] = True
        if module._diff:
            result['diff'] = {'prepared': diff}

    module.exit_json(**result)
コード例 #17
0
ファイル: junos_isis_test.py プロジェクト: ManasaSai/ansible
def main():

    argument_spec = dict(
        commands=dict(type='list', required=True),
        display=dict(choices=['text', 'json', 'xml', 'set'],
                     aliases=['format', 'output']),
        src=dict(type='path'),
        src_format=dict(choices=['xml', 'text', 'set', 'json']),
        lines=dict(type='list'),
        # update operations
        update=dict(default='merge',
                    choices=['merge', 'override', 'replace', 'update']),
    )

    argument_spec.update(junos_argument_spec)

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

    warnings = list()
    check_args(module, warnings)
    result = {'changed': False}

    items = list()
    items.extend(parse_commands(module, warnings))
    responses = rpc(module, items)
    regex = "Down"
    m = re.search(regex, responses[0])
    if m:
        obj = int_remediate(module, warnings, responses[0])
        obj.action()
        result.update({'remediation': 'Done'})
    else:
        result.update({'remediation': 'Not Needed'})
    time.sleep(10)
    responses = rpc(module, items)
    result.update({
        'changed': False,
        'warnings': warnings,
        'stdout_lines': to_lines(responses)
    })
    module.exit_json(**result)
コード例 #18
0
def main():

    argument_spec = dict(
        commands=dict(type='list', required=True),
        display=dict(choices=['text', 'json', 'xml', 'set'],
                     aliases=['format', 'output']),
    )

    argument_spec.update(junos_argument_spec)

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

    warnings = list()
    check_args(module, warnings)
    result = {'changed': False}

    items = list()
    items.extend(parse_commands(module, warnings))
    command = module.params['commands']
    if (command[0] == 'show isis interface'):
        responses = rpc(module, items)
    else:
        module.fail_json(
            msg='invalid show command(please give show isis interface)')
    regex = "([a-z0-9./-]+)\s+([0-9]+)\s+([\w]+)\s+(\w+)\s+(Down)\s+(\w+)"
    res = responses[0].split('\n')
    for response in res:
        m = re.match(regex, response)
        if m:
            interface = m.group(1)
            remediate = action_remediate(module, warnings, interface)
    result.update({
        'changed': False,
        'warnings': warnings,
        'stdout': responses,
        'stdout_lines': to_lines(responses)
    })

    module.exit_json(**result)
コード例 #19
0
ファイル: junos_linkagg.py プロジェクト: zdoop/ansible
def main():
    """ main entry point for module execution
    """
    argument_spec = dict(name=dict(required=True),
                         mode=dict(default='on',
                                   type='str',
                                   choices=['on', 'off', 'active', 'passive']),
                         members=dict(type='list'),
                         min_links=dict(type='int'),
                         device_count=dict(type='int'),
                         description=dict(default=DEFAULT_COMMENT),
                         collection=dict(type='list'),
                         purge=dict(type='bool'),
                         state=dict(
                             default='present',
                             choices=['present', 'absent', 'up', 'down']),
                         active=dict(default=True, type='bool'))

    argument_spec.update(junos_argument_spec)
    required_one_of = [['name', 'collection']]
    mutually_exclusive = [['name', 'collection']]

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

    warnings = list()
    check_args(module, warnings)

    result = {'changed': False}

    if warnings:
        result['warnings'] = warnings

    state = module.params.get('state')
    module.params['disable'] = True if state == 'down' else False

    if state in ('present', 'up', 'down'):
        module.params['state'] = 'present'

    else:
        module.params['disable'] = True

    if module.params.get('mode') == 'off':
        module.params['mode'] = ''
    elif module.params.get('mode') == 'on':
        module.params['mode'] = 'passive'

    with locked_config(module):
        diff = configure_lag_params(module, warnings)
        diff = configure_member_params(module, warnings, diff)

        commit = not module.check_mode
        if diff:
            if commit:
                commit_configuration(module)
            else:
                discard_changes(module)
            result['changed'] = True

            if module._diff:
                result['diff'] = {'prepared': diff}

    module.exit_json(**result)
コード例 #20
0
def main():
    """ Main entry point for AnsibleModule
    """
    argument_spec = dict(
        gather_subset=dict(default=['!config'], type='list'),
        config_format=dict(default='text',
                           choices=['xml', 'text', 'set', 'json']),
    )

    argument_spec.update(junos_argument_spec)

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

    warnings = list()
    check_args(module, warnings)

    gather_subset = module.params['gather_subset']

    runable_subsets = set()
    exclude_subsets = set()

    for subset in gather_subset:
        if subset == 'all':
            runable_subsets.update(VALID_SUBSETS)
            continue

        if subset.startswith('!'):
            subset = subset[1:]
            if subset == 'all':
                exclude_subsets.update(VALID_SUBSETS)
                continue
            exclude = True
        else:
            exclude = False

        if subset not in VALID_SUBSETS:
            module.fail_json(msg='Subset must be one of [%s], got %s' %
                             (', '.join(VALID_SUBSETS), subset))

        if exclude:
            exclude_subsets.add(subset)
        else:
            runable_subsets.add(subset)

    if not runable_subsets:
        runable_subsets.update(VALID_SUBSETS)

    runable_subsets.difference_update(exclude_subsets)
    runable_subsets.add('default')

    facts = dict()
    facts['gather_subset'] = list(runable_subsets)

    instances = list()
    for key in runable_subsets:
        instances.append(FACT_SUBSETS[key](module))

    for inst in instances:
        inst.populate()
        facts.update(inst.facts)

    ansible_facts = dict()
    for key, value in iteritems(facts):
        key = 'ansible_net_%s' % key
        ansible_facts[key] = value

    module.exit_json(ansible_facts=ansible_facts, warnings=warnings)
コード例 #21
0
ファイル: junos_interface.py プロジェクト: ernstp/ansible
def main():
    """ main entry point for module execution
    """
    neighbors_spec = dict(
        host=dict(),
        port=dict()
    )

    element_spec = dict(
        name=dict(),
        description=dict(),
        enabled=dict(default=True, type='bool'),
        speed=dict(),
        mtu=dict(type='int'),
        duplex=dict(choices=['full', 'half', 'auto']),
        tx_rate=dict(),
        rx_rate=dict(),
        neighbors=dict(type='list', elements='dict', options=neighbors_spec),
        delay=dict(default=10, type='int'),
        state=dict(default='present', choices=['present', 'absent', 'up', 'down']),
        active=dict(default=True, type='bool')
    )

    aggregate_spec = deepcopy(element_spec)
    aggregate_spec['name'] = dict(required=True)

    # remove default in aggregate spec, to handle common arguments
    remove_default_spec(aggregate_spec)

    argument_spec = dict(
        aggregate=dict(type='list', elements='dict', options=aggregate_spec),
    )

    argument_spec.update(element_spec)
    argument_spec.update(junos_argument_spec)

    required_one_of = [['name', 'aggregate']]
    mutually_exclusive = [['name', 'aggregate']]

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

    warnings = list()
    check_args(module, warnings)

    result = {'changed': False}

    if warnings:
        result['warnings'] = warnings

    top = 'interfaces/interface'

    param_to_xpath_map = collections.OrderedDict()
    param_to_xpath_map.update([
        ('name', {'xpath': 'name', 'is_key': True}),
        ('description', 'description'),
        ('speed', 'speed'),
        ('mtu', 'mtu'),
        ('duplex', 'link-mode'),
        ('disable', {'xpath': 'disable', 'tag_only': True})
    ])

    choice_to_value_map = {
        'link-mode': {'full': 'full-duplex', 'half': 'half-duplex', 'auto': 'automatic'}
    }

    params = to_param_list(module)

    requests = list()
    for param in params:
        # if key doesn't exist in the item, get it from module.params
        for key in param:
            if param.get(key) is None:
                param[key] = module.params[key]

        item = param.copy()
        state = item.get('state')
        item['disable'] = True if not item.get('enabled') else False

        if state in ('present', 'up', 'down'):
            item['state'] = 'present'

        validate_param_values(module, param_to_xpath_map, param=item)
        want = map_params_to_obj(module, param_to_xpath_map, param=item)
        requests.append(map_obj_to_ele(module, want, top, value_map=choice_to_value_map, param=item))

    diff = None
    with locked_config(module):
        for req in requests:
            diff = load_config(module, tostring(req), warnings, action='merge')

        # issue commit after last configuration change is done
        commit = not module.check_mode
        if diff:
            if commit:
                commit_configuration(module)
            else:
                discard_changes(module)
            result['changed'] = True

            if module._diff:
                result['diff'] = {'prepared': diff}

    failed_conditions = []
    neighbors = None
    for item in params:
        state = item.get('state')
        tx_rate = item.get('tx_rate')
        rx_rate = item.get('rx_rate')
        want_neighbors = item.get('neighbors')

        if state not in ('up', 'down') and tx_rate is None and rx_rate is None and want_neighbors is None:
            continue

        element = Element('get-interface-information')
        intf_name = SubElement(element, 'interface-name')
        intf_name.text = item.get('name')

        if result['changed']:
            sleep(item.get('delay'))

        reply = send_request(module, element, ignore_warning=False)

        if state in ('up', 'down'):
            admin_status = reply.xpath('interface-information/physical-interface/admin-status')
            if not admin_status or not conditional(state, admin_status[0].text.strip()):
                failed_conditions.append('state ' + 'eq(%s)' % state)

        if tx_rate:
            output_bps = reply.xpath('interface-information/physical-interface/traffic-statistics/output-bps')
            if not output_bps or not conditional(tx_rate, output_bps[0].text.strip(), cast=int):
                failed_conditions.append('tx_rate ' + tx_rate)

        if rx_rate:
            input_bps = reply.xpath('interface-information/physical-interface/traffic-statistics/input-bps')
            if not input_bps or not conditional(rx_rate, input_bps[0].text.strip(), cast=int):
                failed_conditions.append('rx_rate ' + rx_rate)

        if want_neighbors:
            if neighbors is None:
                element = Element('get-lldp-interface-neighbors')
                intf_name = SubElement(element, 'interface-device')
                intf_name.text = item.get('name')

                reply = send_request(module, element, ignore_warning=False)
                have_host = [item.text for item in reply.xpath('lldp-neighbors-information/lldp-neighbor-information/lldp-remote-system-name')]
                have_port = [item.text for item in reply.xpath('lldp-neighbors-information/lldp-neighbor-information/lldp-remote-port-id')]

            for neighbor in want_neighbors:
                host = neighbor.get('host')
                port = neighbor.get('port')
                if host and host not in have_host:
                    failed_conditions.append('host ' + host)
                if port and port not in have_port:
                    failed_conditions.append('port ' + port)
    if failed_conditions:
        msg = 'One or more conditional statements have not be satisfied'
        module.fail_json(msg=msg, failed_conditions=failed_conditions)

    module.exit_json(**result)
コード例 #22
0
def main():
    """ main entry point for module execution
    """
    argument_spec = dict(address=dict(required=True,
                                      type='str',
                                      aliases=['prefix']),
                         next_hop=dict(type='str'),
                         preference=dict(type='int',
                                         aliases=['admin_distance']),
                         qualified_next_hop=dict(type='str'),
                         qualified_preference=dict(type='int'),
                         collection=dict(type='list'),
                         purge=dict(type='bool'),
                         state=dict(default='present',
                                    choices=['present', 'absent']),
                         active=dict(default=True, type='bool'))

    argument_spec.update(junos_argument_spec)
    required_one_of = [['collection', 'address']]
    mutually_exclusive = [['collection', 'address']]

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

    warnings = list()
    check_args(module, warnings)

    if module.params['state'] == 'present':
        if not module.params['address'] and module.params['next_hop']:
            module.fail_json(
                msg="parameters are required together: ['address', 'next_hop']"
            )

    result = {'changed': False}

    if warnings:
        result['warnings'] = warnings

    top = 'routing-options/static/route'

    param_to_xpath_map = collections.OrderedDict()
    param_to_xpath_map.update([('address', {
        'xpath': 'name',
        'is_key': True
    }), ('next_hop', 'next-hop'), ('preference', 'preference/metric-value'),
                               ('qualified_next_hop', {
                                   'xpath': 'name',
                                   'top': 'qualified-next-hop'
                               }),
                               ('qualified_preference', {
                                   'xpath': 'preference',
                                   'top': 'qualified-next-hop'
                               })])

    validate_param_values(module, param_to_xpath_map)

    want = list()
    want.append(map_params_to_obj(module, param_to_xpath_map))
    ele = map_obj_to_ele(module, want, top)

    kwargs = {'commit': not module.check_mode}
    kwargs['action'] = 'replace'

    diff = load_config(module, tostring(ele), warnings, **kwargs)

    if diff:
        result.update({
            'changed': True,
            'diff': diff,
        })

    module.exit_json(**result)
コード例 #23
0
def main():
    """ main entry point for module execution
    """
    element_spec = dict(
        address=dict(type='str', aliases=['prefix']),
        next_hop=dict(type='str'),
        preference=dict(type='int', aliases=['admin_distance']),
        qualified_next_hop=dict(type='str'),
        qualified_preference=dict(type='int'),
        state=dict(default='present', choices=['present', 'absent']),
        active=dict(default=True, type='bool')
    )

    aggregate_spec = copy(element_spec)
    aggregate_spec['address'] = dict(required=True)

    argument_spec = dict(
        aggregate=dict(type='list', elements='dict', options=aggregate_spec),
        purge=dict(default=False, type='bool')
    )

    argument_spec.update(element_spec)
    argument_spec.update(junos_argument_spec)

    required_one_of = [['aggregate', 'address']]
    mutually_exclusive = [['aggregate', 'address'],
                          ['aggregate', 'next_hop'],
                          ['aggregate', 'preference'],
                          ['aggregate', 'qualified_next_hop'],
                          ['aggregate', 'qualified_preference'],
                          ['aggregate', 'state'],
                          ['aggregate', 'active']]

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

    warnings = list()
    check_args(module, warnings)

    result = {'changed': False}

    if warnings:
        result['warnings'] = warnings

    top = 'routing-options/static/route'

    param_to_xpath_map = collections.OrderedDict()
    param_to_xpath_map.update([
        ('address', {'xpath': 'name', 'is_key': True}),
        ('next_hop', 'next-hop'),
        ('preference', 'preference/metric-value'),
        ('qualified_next_hop', {'xpath': 'name', 'top': 'qualified-next-hop'}),
        ('qualified_preference', {'xpath': 'preference', 'top': 'qualified-next-hop'})
    ])

    params = to_param_list(module)
    requests = list()

    for param in params:
        item = copy(param)
        if item['state'] == 'present':
            if not item['address'] and item['next_hop']:
                module.fail_json(msg="parameters are required together: ['address', 'next_hop']")

        want = map_params_to_obj(module, param_to_xpath_map, param=item)
        requests.append(map_obj_to_ele(module, want, top, param=item))

    with locked_config(module):
        for req in requests:
            diff = load_config(module, tostring(req), warnings, action='replace')

        commit = not module.check_mode
        if diff:
            if commit:
                commit_configuration(module)
            else:
                discard_changes(module)
            result['changed'] = True

            if module._diff:
                result['diff'] = {'prepared': diff}

    module.exit_json(**result)
コード例 #24
0
ファイル: junos_static_route.py プロジェクト: ernstp/ansible
def main():
    """ main entry point for module execution
    """
    element_spec = dict(
        address=dict(aliases=['prefix']),
        next_hop=dict(),
        preference=dict(type='int', aliases=['admin_distance']),
        qualified_next_hop=dict(type='str'),
        qualified_preference=dict(type='int'),
        state=dict(default='present', choices=['present', 'absent']),
        active=dict(default=True, type='bool')
    )

    aggregate_spec = deepcopy(element_spec)
    aggregate_spec['address'] = dict(required=True)

    # remove default in aggregate spec, to handle common arguments
    remove_default_spec(aggregate_spec)

    argument_spec = dict(
        aggregate=dict(type='list', elements='dict', options=aggregate_spec),
        purge=dict(default=False, type='bool')
    )

    argument_spec.update(element_spec)
    argument_spec.update(junos_argument_spec)

    required_one_of = [['aggregate', 'address']]
    mutually_exclusive = [['aggregate', 'address']]

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

    warnings = list()
    check_args(module, warnings)

    result = {'changed': False}

    if warnings:
        result['warnings'] = warnings

    top = 'routing-options/static/route'

    param_to_xpath_map = collections.OrderedDict()
    param_to_xpath_map.update([
        ('address', {'xpath': 'name', 'is_key': True}),
        ('next_hop', 'next-hop'),
        ('preference', 'preference/metric-value'),
        ('qualified_next_hop', {'xpath': 'name', 'top': 'qualified-next-hop'}),
        ('qualified_preference', {'xpath': 'preference', 'top': 'qualified-next-hop'})
    ])

    params = to_param_list(module)
    requests = list()

    for param in params:
        # if key doesn't exist in the item, get it from module.params
        for key in param:
            if param.get(key) is None:
                param[key] = module.params[key]

        item = param.copy()
        if item['state'] == 'present':
            if not item['address'] and item['next_hop']:
                module.fail_json(msg="parameters are required together: ['address', 'next_hop']")

        want = map_params_to_obj(module, param_to_xpath_map, param=item)
        requests.append(map_obj_to_ele(module, want, top, param=item))

    with locked_config(module):
        for req in requests:
            diff = load_config(module, tostring(req), warnings, action='merge')

        commit = not module.check_mode
        if diff:
            if commit:
                commit_configuration(module)
            else:
                discard_changes(module)
            result['changed'] = True

            if module._diff:
                result['diff'] = {'prepared': diff}

    module.exit_json(**result)
コード例 #25
0
ファイル: junos_logging.py プロジェクト: jdeer0618/ansible-1
def main():
    """ main entry point for module execution
    """
    argument_spec = dict(
        dest=dict(choices=['console', 'host', 'file', 'user']),
        name=dict(),
        facility=dict(),
        level=dict(),
        rotate_frequency=dict(type='int'),
        size=dict(type='int'),
        files=dict(type='int'),
        src_addr=dict(),
        collection=dict(),
        purge=dict(default=False, type='bool'),
        state=dict(default='present', choices=['present', 'absent']),
        active=dict(default=True, type='bool'))

    argument_spec.update(junos_argument_spec)

    required_if = [('dest', 'host', ['name', 'facility', 'level']),
                   ('dest', 'file', ['name', 'facility', 'level']),
                   ('dest', 'user', ['name', 'facility', 'level']),
                   ('dest', 'console', ['facility', 'level'])]

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

    warnings = list()
    check_args(module, warnings)

    result = {'changed': False}

    if warnings:
        result['warnings'] = warnings

    dest = module.params.get('dest')
    if dest == 'console' and module.params.get('name'):
        module.fail_json(msg="%s and %s are mutually exclusive" %
                         ('console', 'name'))

    top = 'system/syslog'
    is_facility_key = False
    field_top = None
    if dest:
        if dest == 'console':
            field_top = dest
            is_facility_key = True
        else:
            field_top = dest + '/contents'
            is_facility_key = False

    param_to_xpath_map = collections.OrderedDict()
    param_to_xpath_map.update([
        ('name', {
            'xpath': 'name',
            'is_key': True,
            'top': dest
        }),
        ('facility', {
            'xpath': 'name',
            'is_key': is_facility_key,
            'top': field_top
        }),
        ('level', {
            'xpath': module.params.get('level'),
            'tag_only': True,
            'top': field_top
        }),
        ('size', {
            'xpath': 'size',
            'leaf_only': True,
            'is_key': True,
            'top': 'archive'
        }),
        ('files', {
            'xpath': 'files',
            'leaf_only': True,
            'is_key': True,
            'top': 'archive'
        }),
        ('rotate_frequency', {
            'xpath': 'log-rotate-frequency',
            'leaf_only': True
        }),
    ])

    validate_param_values(module, param_to_xpath_map)

    want = list()
    want.append(map_params_to_obj(module, param_to_xpath_map))
    ele = map_obj_to_ele(module, want, top)

    kwargs = {'commit': not module.check_mode}
    kwargs['action'] = 'replace'

    diff = load_config(module, tostring(ele), warnings, **kwargs)

    if diff:
        result.update({
            'changed': True,
            'diff': diff,
        })

    module.exit_json(**result)
コード例 #26
0
ファイル: junos_command.py プロジェクト: ernstp/ansible
def main():
    """entry point for module execution
    """
    argument_spec = dict(
        commands=dict(type='list'),
        rpcs=dict(type='list'),

        display=dict(choices=['text', 'json', 'xml', 'set'], aliases=['format', 'output']),

        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(junos_argument_spec)

    required_one_of = [('commands', 'rpcs')]

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

    warnings = list()
    check_args(module, warnings)

    if module.params['provider'] and module.params['provider']['transport'] == 'cli':
        if any((module.params['wait_for'], module.params['match'], module.params['rpcs'])):
            module.warn('arguments wait_for, match, rpcs are not supported when using transport=cli')
        commands = module.params['commands']
        conn = Connection(module)
        output = list()
        for cmd in commands:
            output.append(conn.get(cmd))
        lines = [out.split('\n') for out in output]
        result = {'changed': False, 'stdout': output, 'stdout_lines': lines}
        module.exit_json(**result)

    items = list()
    items.extend(parse_commands(module, warnings))
    items.extend(parse_rpcs(module))

    wait_for = module.params['wait_for'] or list()
    conditionals = [Conditional(c) for c in wait_for]

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

    while retries > 0:
        responses = rpc(module, items)
        transformed = list()
        output = list()
        for item, resp in zip(items, responses):
            if item['xattrs']['format'] == 'xml':
                if not HAS_JXMLEASE:
                    module.fail_json(msg='jxmlease is required but does not appear to be installed. '
                                         'It can be installed using `pip install jxmlease`')

                try:
                    json_resp = jxmlease.parse(resp)
                    transformed.append(json_resp)
                    output.append(json_resp)
                except:
                    raise ValueError(resp)
            else:
                transformed.append(resp)

        for item in list(conditionals):
            try:
                if item(transformed):
                    if match == 'any':
                        conditionals = list()
                        break
                    conditionals.remove(item)
            except FailedConditionalError:
                pass

        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 be satisfied'
        module.fail_json(msg=msg, failed_conditions=failed_conditions)

    result = {
        'changed': False,
        'warnings': warnings,
        'stdout': responses,
        'stdout_lines': to_lines(responses)
    }

    if output:
        result['output'] = output

    module.exit_json(**result)
コード例 #27
0
def main():
    """ main entry point for module execution
    """
    element_spec = dict(name=dict(),
                        full_name=dict(),
                        role=dict(choices=ROLES),
                        sshkey=dict(),
                        state=dict(choices=['present', 'absent'],
                                   default='present'),
                        active=dict(type='bool', default=True))

    aggregate_spec = deepcopy(element_spec)
    aggregate_spec['name'] = dict(required=True)

    # remove default in aggregate spec, to handle common arguments
    remove_default_spec(aggregate_spec)

    argument_spec = dict(aggregate=dict(type='list',
                                        elements='dict',
                                        options=aggregate_spec,
                                        aliases=['collection', 'users']),
                         purge=dict(default=False, type='bool'))

    argument_spec.update(element_spec)
    argument_spec.update(junos_argument_spec)

    mutually_exclusive = [['aggregate', 'name']]

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

    warnings = list()
    check_args(module, warnings)

    result = {'changed': False, 'warnings': warnings}

    want = map_params_to_obj(module)
    ele = map_obj_to_ele(module, want)

    purge_request = None
    if module.params['purge']:
        purge_request = handle_purge(module, want)

    with locked_config(module):
        if purge_request:
            load_config(module,
                        tostring(purge_request),
                        warnings,
                        action='replace')
        diff = load_config(module, tostring(ele), warnings, action='merge')

        commit = not module.check_mode
        if diff:
            if commit:
                commit_configuration(module)
            else:
                discard_changes(module)
            result['changed'] = True

            if module._diff:
                result['diff'] = {'prepared': diff}

    module.exit_json(**result)
コード例 #28
0
ファイル: junos_vrf.py プロジェクト: ernstp/ansible
def main():
    """ main entry point for module execution
    """
    element_spec = dict(
        name=dict(),
        description=dict(),
        rd=dict(type='list'),
        interfaces=dict(type='list'),
        target=dict(type='list'),
        state=dict(default='present', choices=['present', 'absent']),
        active=dict(default=True, type='bool'),
        table_label=dict(default=True, type='bool')
    )

    aggregate_spec = deepcopy(element_spec)
    aggregate_spec['name'] = dict(required=True)

    # remove default in aggregate spec, to handle common arguments
    remove_default_spec(aggregate_spec)

    argument_spec = dict(
        aggregate=dict(type='list', elements='dict', options=aggregate_spec),
    )

    argument_spec.update(element_spec)
    argument_spec.update(junos_argument_spec)

    required_one_of = [['aggregate', 'name']]
    mutually_exclusive = [['aggregate', 'name']]

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

    warnings = list()
    check_args(module, warnings)

    result = {'changed': False}

    if warnings:
        result['warnings'] = warnings

    top = 'routing-instances/instance'

    param_to_xpath_map = collections.OrderedDict()
    param_to_xpath_map.update([
        ('name', {'xpath': 'name', 'is_key': True}),
        ('description', 'description'),
        ('type', 'instance-type'),
        ('rd', 'route-distinguisher/rd-type'),
        ('interfaces', 'interface/name'),
        ('target', 'vrf-target/community'),
        ('table_label', {'xpath': 'vrf-table-label', 'tag_only': True}),
    ])

    params = to_param_list(module)
    requests = list()

    for param in params:
        # if key doesn't exist in the item, get it from module.params
        for key in param:
            if param.get(key) is None:
                param[key] = module.params[key]

        item = param.copy()
        item['type'] = 'vrf'

        want = map_params_to_obj(module, param_to_xpath_map, param=item)
        requests.append(map_obj_to_ele(module, want, top, param=item))

    with locked_config(module):
        for req in requests:
            diff = load_config(module, tostring(req), warnings, action='merge')

        commit = not module.check_mode
        if diff:
            if commit:
                commit_configuration(module)
            else:
                discard_changes(module)
            result['changed'] = True

            if module._diff:
                result['diff'] = {'prepared': diff}

    module.exit_json(**result)
コード例 #29
0
def main():
    """ main entry point for module execution
    """
    element_spec = dict(dest=dict(choices=['console', 'host', 'file', 'user']),
                        name=dict(),
                        facility=dict(),
                        level=dict(),
                        rotate_frequency=dict(type='int'),
                        size=dict(type='int'),
                        files=dict(type='int'),
                        src_addr=dict(),
                        state=dict(default='present',
                                   choices=['present', 'absent']),
                        active=dict(default=True, type='bool'))

    aggregate_spec = deepcopy(element_spec)

    # remove default in aggregate spec, to handle common arguments
    remove_default_spec(aggregate_spec)

    argument_spec = dict(aggregate=dict(type='list',
                                        elements='dict',
                                        options=aggregate_spec), )

    argument_spec.update(element_spec)
    argument_spec.update(junos_argument_spec)

    required_if = [('dest', 'host', ['name', 'facility', 'level']),
                   ('dest', 'file', ['name', 'facility', 'level']),
                   ('dest', 'user', ['name', 'facility', 'level']),
                   ('dest', 'console', ['facility', 'level'])]

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

    warnings = list()
    check_args(module, warnings)

    result = {'changed': False}

    if warnings:
        result['warnings'] = warnings

    params = to_param_list(module)

    requests = list()
    for param in params:
        # if key doesn't exist in the item, get it from module.params
        for key in param:
            if param.get(key) is None:
                param[key] = module.params[key]

        module._check_required_if(required_if, param)

        item = param.copy()
        dest = item.get('dest')
        if dest == 'console' and item.get('name'):
            module.fail_json(msg="%s and %s are mutually exclusive" %
                             ('console', 'name'))

        top = 'system/syslog'
        is_facility_key = False
        field_top = None
        if dest:
            if dest == 'console':
                field_top = dest
                is_facility_key = True
            else:
                field_top = dest + '/contents'
                is_facility_key = False

        param_to_xpath_map = collections.OrderedDict()
        param_to_xpath_map.update([
            ('name', {
                'xpath': 'name',
                'is_key': True,
                'top': dest
            }),
            ('facility', {
                'xpath': 'name',
                'is_key': is_facility_key,
                'top': field_top
            }),
            ('size', {
                'xpath': 'size',
                'leaf_only': True,
                'is_key': True,
                'top': 'archive'
            }),
            ('files', {
                'xpath': 'files',
                'leaf_only': True,
                'is_key': True,
                'top': 'archive'
            }),
            ('rotate_frequency', {
                'xpath': 'log-rotate-frequency',
                'leaf_only': True
            }),
        ])

        if item.get('level'):
            param_to_xpath_map['level'] = {
                'xpath': item.get('level'),
                'tag_only': True,
                'top': field_top
            }

        validate_param_values(module, param_to_xpath_map, param=item)

        want = map_params_to_obj(module, param_to_xpath_map, param=item)
        requests.append(map_obj_to_ele(module, want, top, param=item))

    diff = None
    with locked_config(module):
        for req in requests:
            diff = load_config(module,
                               tostring(req),
                               warnings,
                               action='replace')

        commit = not module.check_mode
        if diff:
            if commit:
                commit_configuration(module)
            else:
                discard_changes(module)
            result['changed'] = True

            if module._diff:
                result['diff'] = {'prepared': diff}

    module.exit_json(**result)
コード例 #30
0
ファイル: junos_facts.py プロジェクト: ernstp/ansible
def main():
    """ Main entry point for AnsibleModule
    """
    argument_spec = dict(
        gather_subset=dict(default=['!config'], type='list'),
        config_format=dict(default='text', choices=['xml', 'text', 'set', 'json']),
    )

    argument_spec.update(junos_argument_spec)

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

    warnings = list()
    check_args(module, warnings)

    gather_subset = module.params['gather_subset']
    ofacts = False

    runable_subsets = set()
    exclude_subsets = set()

    for subset in gather_subset:
        if subset == 'all':
            runable_subsets.update(VALID_SUBSETS)
            ofacts = True
            continue

        if subset.startswith('!'):
            subset = subset[1:]
            if subset == 'all':
                exclude_subsets.update(VALID_SUBSETS)
                ofacts = False
                continue
            exclude = True
        else:
            exclude = False

        if subset not in VALID_SUBSETS:
            module.fail_json(msg='Subset must be one of [%s], got %s' %
                             (', '.join(VALID_SUBSETS), subset))

        if exclude:
            exclude_subsets.add(subset)
        else:
            runable_subsets.add(subset)

    if not runable_subsets:
        runable_subsets.update(VALID_SUBSETS)

    runable_subsets.difference_update(exclude_subsets)
    runable_subsets.add('default')

    facts = dict()
    facts['gather_subset'] = list(runable_subsets)

    instances = list()
    for key in runable_subsets:
        instances.append(FACT_SUBSETS[key](module))

    for inst in instances:
        inst.populate()
        facts.update(inst.facts)

    ansible_facts = dict()
    for key, value in iteritems(facts):
        key = 'ansible_net_%s' % key
        ansible_facts[key] = value

    if ofacts:
        if HAS_PYEZ:
            ansible_facts.update(Facts(module).populate())
        else:
            warnings += ['junos-eznc is required to gather old style facts but does not appear to be installed. '
                         'It can be installed using `pip  install junos-eznc`']

    module.exit_json(ansible_facts=ansible_facts, warnings=warnings)
コード例 #31
0
def main():
    """ main entry point for module execution
    """
    argument_spec = dict(name=dict(required=True),
                         description=dict(),
                         enabled=dict(),
                         speed=dict(),
                         mtu=dict(type='int'),
                         duplex=dict(choices=['full', 'half', 'auto']),
                         tx_rate=dict(),
                         rx_rate=dict(),
                         collection=dict(),
                         purge=dict(default=False, type='bool'),
                         state=dict(
                             default='present',
                             choices=['present', 'absent', 'up', 'down']),
                         active=dict(default=True, type='bool'))

    argument_spec.update(junos_argument_spec)

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

    warnings = list()
    check_args(module, warnings)

    result = {'changed': False}

    if warnings:
        result['warnings'] = warnings

    top = 'interfaces/interface'

    param_to_xpath_map = collections.OrderedDict()
    param_to_xpath_map.update([('name', {
        'xpath': 'name',
        'is_key': True
    }), ('description', 'description'), ('speed', 'speed'), ('mtu', 'mtu'),
                               ('duplex', 'link-mode'),
                               ('disable', {
                                   'xpath': 'disable',
                                   'tag_only': True
                               })])

    state = module.params.get('state')
    module.params['disable'] = True if state == 'down' else False

    if state in ('present', 'up', 'down'):
        module.params['state'] = 'present'

    else:
        module.params['disable'] = True

    choice_to_value_map = {
        'link-mode': {
            'full': 'full-duplex',
            'half': 'half-duplex',
            'auto': 'automatic'
        }
    }

    validate_param_values(module, param_to_xpath_map)

    want = map_params_to_obj(module, param_to_xpath_map)
    ele = map_obj_to_ele(module, want, top, choice_to_value_map)

    with locked_config(module):
        diff = load_config(module, tostring(ele), warnings, action='replace')

        commit = not module.check_mode
        if diff:
            if commit:
                commit_configuration(module)
            else:
                discard_changes(module)
            result['changed'] = True

            if module._diff:
                result['diff'] = {'prepared': diff}

    module.exit_json(**result)
コード例 #32
0
def main():
    """ main entry point for module execution
    """
    element_spec = dict(
        name=dict(),
        description=dict(),
        enabled=dict(default=True, type='bool'),
        speed=dict(),
        mtu=dict(type='int'),
        duplex=dict(choices=['full', 'half', 'auto']),
        tx_rate=dict(),
        rx_rate=dict(),
        delay=dict(default=10, type='int'),
        state=dict(default='present', choices=['present', 'absent', 'up', 'down']),
        active=dict(default=True, type='bool')
    )

    aggregate_spec = deepcopy(element_spec)
    aggregate_spec['name'] = dict(required=True)

    # remove default in aggregate spec, to handle common arguments
    remove_default_spec(aggregate_spec)

    argument_spec = dict(
        aggregate=dict(type='list', elements='dict', options=aggregate_spec),
    )

    argument_spec.update(element_spec)
    argument_spec.update(junos_argument_spec)

    required_one_of = [['name', 'aggregate']]
    mutually_exclusive = [['name', 'aggregate']]

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

    warnings = list()
    check_args(module, warnings)

    result = {'changed': False}

    if warnings:
        result['warnings'] = warnings

    top = 'interfaces/interface'

    param_to_xpath_map = collections.OrderedDict()
    param_to_xpath_map.update([
        ('name', {'xpath': 'name', 'is_key': True}),
        ('description', 'description'),
        ('speed', 'speed'),
        ('mtu', 'mtu'),
        ('duplex', 'link-mode'),
        ('disable', {'xpath': 'disable', 'tag_only': True})
    ])

    choice_to_value_map = {
        'link-mode': {'full': 'full-duplex', 'half': 'half-duplex', 'auto': 'automatic'}
    }

    params = to_param_list(module)

    requests = list()
    for param in params:
        # if key doesn't exist in the item, get it from module.params
        for key in param:
            if param.get(key) is None:
                param[key] = module.params[key]

        item = param.copy()
        state = item.get('state')
        item['disable'] = True if not item.get('enabled') else False

        if state in ('present', 'up', 'down'):
            item['state'] = 'present'

        validate_param_values(module, param_to_xpath_map, param=item)
        want = map_params_to_obj(module, param_to_xpath_map, param=item)
        requests.append(map_obj_to_ele(module, want, top, value_map=choice_to_value_map, param=item))

    diff = None
    with locked_config(module):
        for req in requests:
            diff = load_config(module, tostring(req), warnings, action='merge')

        # issue commit after last configuration change is done
        commit = not module.check_mode
        if diff:
            if commit:
                commit_configuration(module)
            else:
                discard_changes(module)
            result['changed'] = True

            if module._diff:
                result['diff'] = {'prepared': diff}

    failed_conditions = []
    for item in params:
        state = item.get('state')
        tx_rate = item.get('tx_rate')
        rx_rate = item.get('rx_rate')

        if state not in ('up', 'down') and tx_rate is None and rx_rate is None:
            continue

        element = Element('get-interface-information')
        intf_name = SubElement(element, 'interface-name')
        intf_name.text = item.get('name')

        if result['changed']:
            sleep(item.get('delay'))

        reply = send_request(module, element, ignore_warning=False)

        if state in ('up', 'down'):
            admin_status = reply.xpath('interface-information/physical-interface/admin-status')
            if not admin_status or not conditional(state, admin_status[0].text.strip()):
                failed_conditions.append('state ' + 'eq(%s)' % state)

        if tx_rate:
            output_bps = reply.xpath('interface-information/physical-interface/traffic-statistics/output-bps')
            if not output_bps or not conditional(tx_rate, output_bps[0].text.strip(), cast=int):
                failed_conditions.append('tx_rate ' + tx_rate)

        if rx_rate:
            input_bps = reply.xpath('interface-information/physical-interface/traffic-statistics/input-bps')
            if not input_bps or not conditional(rx_rate, input_bps[0].text.strip(), cast=int):
                failed_conditions.append('rx_rate ' + rx_rate)

    if failed_conditions:
        msg = 'One or more conditional statements have not be satisfied'
        module.fail_json(msg=msg, failed_conditions=failed_conditions)

    module.exit_json(**result)
コード例 #33
0
ファイル: junos_system.py プロジェクト: ernstp/ansible
def main():
    """ main entry point for module execution
    """
    argument_spec = dict(
        hostname=dict(),
        domain_name=dict(),
        domain_search=dict(type='list'),
        name_servers=dict(type='list'),
        state=dict(choices=['present', 'absent'], default='present'),
        active=dict(default=True, type='bool')
    )

    argument_spec.update(junos_argument_spec)

    params = ['hostname', 'domain_name', 'domain_search', 'name_servers']
    required_if = [('state', 'present', params, True),
                   ('state', 'absent', params, True),
                   ('state', 'active', params, True),
                   ('state', 'suspend', params, True)]

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

    warnings = list()
    check_args(module, warnings)

    result = {'changed': False}

    if warnings:
        result['warnings'] = warnings

    top = 'system'

    param_to_xpath_map = collections.OrderedDict()
    param_to_xpath_map.update([
        ('hostname', {'xpath': 'host-name', 'leaf_only': True}),
        ('domain_name', {'xpath': 'domain-name', 'leaf_only': True}),
        ('domain_search', {'xpath': 'domain-search', 'leaf_only': True, 'value_req': True}),
        ('name_servers', {'xpath': 'name-server/name', 'is_key': True})
    ])

    validate_param_values(module, param_to_xpath_map)

    want = map_params_to_obj(module, param_to_xpath_map)
    ele = map_obj_to_ele(module, want, top)

    with locked_config(module):
        diff = load_config(module, tostring(ele), warnings, action='merge')

        commit = not module.check_mode
        if diff:
            if commit:
                commit_configuration(module)
            else:
                discard_changes(module)
            result['changed'] = True

            if module._diff:
                result['diff'] = {'prepared': diff}

    module.exit_json(**result)
コード例 #34
0
def main():
    """entry point for module execution
    """
    argument_spec = dict(
        commands=dict(type='list'),
        rpcs=dict(type='list'),

        display=dict(choices=['text', 'json', 'xml'], aliases=['format', 'output']),

        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(junos_argument_spec)

    required_one_of = [('commands', 'rpcs')]

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

    warnings = list()
    check_args(module, warnings)

    items = list()
    items.extend(parse_commands(module, warnings))
    items.extend(parse_rpcs(module))

    wait_for = module.params['wait_for'] or list()
    display = module.params['display']
    conditionals = [Conditional(c) for c in wait_for]

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

    while retries > 0:
        responses = rpc(module, items)

        transformed = list()

        for item, resp in zip(items, responses):
            if item['xattrs']['format'] == 'xml':
                if not HAS_JXMLEASE:
                    module.fail_json(msg='jxmlease is required but does not appear to '
                        'be installed.  It can be installed using `pip install jxmlease`')

                try:
                    transformed.append(jxmlease.parse(resp))
                except:
                    raise ValueError(resp)
            else:
                transformed.append(resp)

        for item in list(conditionals):
            try:
                if item(transformed):
                    if match == 'any':
                        conditionals = list()
                        break
                    conditionals.remove(item)
            except FailedConditionalError:
                pass

        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 be satisfied'
        module.fail_json(msg=msg, failed_conditions=failed_conditions)

    result = {
        'changed': False,
        'warnings': warnings,
        'stdout': responses,
        'stdout_lines': to_lines(responses)
    }


    module.exit_json(**result)
コード例 #35
0
def main():
    """ main entry point for module execution
    """
    element_spec = dict(
        name=dict(),
        description=dict(),
        rd=dict(type='list'),
        interfaces=dict(type='list'),
        target=dict(type='list'),
        state=dict(default='present', choices=['present', 'absent']),
        active=dict(default=True, type='bool')
    )

    aggregate_spec = element_spec.copy()
    aggregate_spec['name'] = dict(required=True)

    argument_spec = dict(
        aggregate=dict(type='list', elements='dict', options=aggregate_spec),
        purge=dict(default=False, type='bool')
    )

    argument_spec.update(element_spec)
    argument_spec.update(junos_argument_spec)

    required_one_of = [['aggregate', 'name']]
    mutually_exclusive = [['aggregate', 'name'],
                          ['aggregate', 'description'],
                          ['aggregate', 'rd'],
                          ['aggregate', 'interfaces'],
                          ['aggregate', 'target'],
                          ['aggregate', 'state'],
                          ['aggregate', 'active']]

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

    warnings = list()
    check_args(module, warnings)

    result = {'changed': False}

    if warnings:
        result['warnings'] = warnings

    top = 'routing-instances/instance'

    param_to_xpath_map = collections.OrderedDict()
    param_to_xpath_map.update([
        ('name', {'xpath': 'name', 'is_key': True}),
        ('description', 'description'),
        ('type', 'instance-type'),
        ('rd', 'route-distinguisher/rd-type'),
        ('interfaces', 'interface/name'),
        ('target', 'vrf-target/community'),
    ])

    params = to_param_list(module)
    requests = list()

    for param in params:
        item = param.copy()

        item['type'] = 'vrf'

        want = map_params_to_obj(module, param_to_xpath_map, param=item)
        requests.append(map_obj_to_ele(module, want, top, param=item))

    with locked_config(module):
        for req in requests:
            diff = load_config(module, tostring(req), warnings, action='replace')

        commit = not module.check_mode
        if diff:
            if commit:
                commit_configuration(module)
            else:
                discard_changes(module)
            result['changed'] = True

            if module._diff:
                result['diff'] = {'prepared': diff}

    module.exit_json(**result)
コード例 #36
0
def main():
    """ main entry point for module execution
    """
    element_spec = dict(
        name=dict(),
        ipv4=dict(),
        ipv6=dict(),
        unit=dict(default=0, type='int'),
        state=dict(default='present', choices=['present', 'absent']),
        active=dict(default=True, type='bool')
    )

    aggregate_spec = deepcopy(element_spec)
    aggregate_spec['name'] = dict(required=True)

    # remove default in aggregate spec, to handle common arguments
    remove_default_spec(aggregate_spec)

    argument_spec = dict(
        aggregate=dict(type='list', elements='dict', options=aggregate_spec),
    )

    argument_spec.update(element_spec)
    argument_spec.update(junos_argument_spec)

    required_one_of = [['name', 'aggregate']]
    mutually_exclusive = [['name', 'aggregate']]

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

    warnings = list()
    check_args(module, warnings)

    result = {'changed': False}

    if warnings:
        result['warnings'] = warnings

    top = 'interfaces/interface'

    param_to_xpath_map = collections.OrderedDict()
    param_to_xpath_map.update([
        ('name', {'xpath': 'name', 'parent_attrib': False, 'is_key': True}),
        ('unit', {'xpath': 'name', 'top': 'unit', 'parent_attrib': False, 'is_key': True}),
        ('ipv4', {'xpath': 'inet/address/name', 'top': 'unit/family', 'is_key': True}),
        ('ipv6', {'xpath': 'inet6/address/name', 'top': 'unit/family', 'is_key': True})
    ])

    params = to_param_list(module)

    requests = list()
    for param in params:
        # if key doesn't exist in the item, get it from module.params
        for key in param:
            if param.get(key) is None:
                param[key] = module.params[key]

        item = param.copy()
        if not item['ipv4'] and not item['ipv6']:
            module.fail_json(msg="one of the following is required: ipv4,ipv6")

        want = map_params_to_obj(module, param_to_xpath_map, param=item)
        requests.append(map_obj_to_ele(module, want, top, param=item))

    diff = None
    with locked_config(module):
        for req in requests:
            diff = load_config(module, tostring(req), warnings, action='replace')

        commit = not module.check_mode
        if diff:
            if commit:
                commit_configuration(module)
            else:
                discard_changes(module)
            result['changed'] = True

            if module._diff:
                result['diff'] = {'prepared': diff}

    module.exit_json(**result)
コード例 #37
0
ファイル: junos_l3_interface.py プロジェクト: ernstp/ansible
def main():
    """ main entry point for module execution
    """
    element_spec = dict(
        name=dict(),
        ipv4=dict(),
        ipv6=dict(),
        unit=dict(default=0, type='int'),
        state=dict(default='present', choices=['present', 'absent']),
        active=dict(default=True, type='bool')
    )

    aggregate_spec = deepcopy(element_spec)
    aggregate_spec['name'] = dict(required=True)

    # remove default in aggregate spec, to handle common arguments
    remove_default_spec(aggregate_spec)

    argument_spec = dict(
        aggregate=dict(type='list', elements='dict', options=aggregate_spec),
    )

    argument_spec.update(element_spec)
    argument_spec.update(junos_argument_spec)

    required_one_of = [['name', 'aggregate']]
    mutually_exclusive = [['name', 'aggregate']]

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

    warnings = list()
    check_args(module, warnings)

    result = {'changed': False}

    if warnings:
        result['warnings'] = warnings

    top = 'interfaces/interface'

    param_to_xpath_map = collections.OrderedDict()
    param_to_xpath_map.update([
        ('name', {'xpath': 'name', 'parent_attrib': False, 'is_key': True}),
        ('unit', {'xpath': 'name', 'top': 'unit', 'parent_attrib': False, 'is_key': True}),
        ('ipv4', {'xpath': 'inet/address/name', 'top': 'unit/family', 'is_key': True}),
        ('ipv6', {'xpath': 'inet6/address/name', 'top': 'unit/family', 'is_key': True})
    ])

    params = to_param_list(module)

    requests = list()
    for param in params:
        # if key doesn't exist in the item, get it from module.params
        for key in param:
            if param.get(key) is None:
                param[key] = module.params[key]

        item = param.copy()
        if not item['ipv4'] and not item['ipv6']:
            module.fail_json(msg="one of the following is required: ipv4,ipv6")

        want = map_params_to_obj(module, param_to_xpath_map, param=item)
        requests.append(map_obj_to_ele(module, want, top, param=item))

    diff = None
    with locked_config(module):
        for req in requests:
            diff = load_config(module, tostring(req), warnings, action='merge')

        commit = not module.check_mode
        if diff:
            if commit:
                commit_configuration(module)
            else:
                discard_changes(module)
            result['changed'] = True

            if module._diff:
                result['diff'] = {'prepared': diff}

    module.exit_json(**result)
コード例 #38
0
def main():
    """ main entry point for module execution
    """
    element_spec = dict(name=dict(),
                        mode=dict(default='on',
                                  choices=['on', 'off', 'active', 'passive']),
                        members=dict(type='list'),
                        min_links=dict(type='int'),
                        device_count=dict(type='int'),
                        description=dict(default=DEFAULT_COMMENT),
                        state=dict(default='present',
                                   choices=['present', 'absent', 'up',
                                            'down']),
                        active=dict(default=True, type='bool'))

    aggregate_spec = deepcopy(element_spec)
    aggregate_spec['name'] = dict(required=True)

    # remove default in aggregate spec, to handle common arguments
    remove_default_spec(aggregate_spec)

    argument_spec = dict(aggregate=dict(type='list',
                                        elements='dict',
                                        options=aggregate_spec), )

    argument_spec.update(element_spec)
    argument_spec.update(junos_argument_spec)

    required_one_of = [['name', 'aggregate']]
    mutually_exclusive = [['name', 'aggregate']]

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

    warnings = list()
    check_args(module, warnings)

    result = {'changed': False}

    if warnings:
        result['warnings'] = warnings

    params = to_param_list(module)
    requests = list()
    for param in params:
        # if key doesn't exist in the item, get it from module.params
        for key in param:
            if param.get(key) is None:
                param[key] = module.params[key]

        item = param.copy()
        state = item.get('state')
        item['disable'] = True if state == 'down' else False

        if state in ('present', 'up', 'down'):
            item['state'] = 'present'

        else:
            item['disable'] = True

        mode = item.get('mode')
        if mode == 'off':
            item['mode'] = ''
        elif mode == 'on':
            item['mode'] = 'passive'

        configure_lag_params(module, requests, item)
        configure_member_params(module, requests, item)

    diff = None
    with locked_config(module):
        for req in requests:
            diff = load_config(module, tostring(req), warnings, action='merge')

        commit = not module.check_mode
        if diff:
            if commit:
                commit_configuration(module)
            else:
                discard_changes(module)
            result['changed'] = True

            if module._diff:
                result['diff'] = {'prepared': diff}

    module.exit_json(**result)
コード例 #39
0
ファイル: junos_user.py プロジェクト: ernstp/ansible
def main():
    """ main entry point for module execution
    """
    element_spec = dict(
        name=dict(),
        full_name=dict(),
        role=dict(choices=ROLES),
        sshkey=dict(),
        state=dict(choices=['present', 'absent'], default='present'),
        active=dict(type='bool', default=True)
    )

    aggregate_spec = deepcopy(element_spec)
    aggregate_spec['name'] = dict(required=True)

    # remove default in aggregate spec, to handle common arguments
    remove_default_spec(aggregate_spec)

    argument_spec = dict(
        aggregate=dict(type='list', elements='dict', options=aggregate_spec, aliases=['collection', 'users']),
        purge=dict(default=False, type='bool')
    )

    argument_spec.update(element_spec)
    argument_spec.update(junos_argument_spec)

    mutually_exclusive = [['aggregate', 'name']]

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

    warnings = list()
    check_args(module, warnings)

    result = {'changed': False, 'warnings': warnings}

    want = map_params_to_obj(module)
    ele = map_obj_to_ele(module, want)

    purge_request = None
    if module.params['purge']:
        purge_request = handle_purge(module, want)

    with locked_config(module):
        if purge_request:
            load_config(module, tostring(purge_request), warnings, action='replace')
        diff = load_config(module, tostring(ele), warnings, action='merge')

        commit = not module.check_mode
        if diff:
            if commit:
                commit_configuration(module)
            else:
                discard_changes(module)
            result['changed'] = True

            if module._diff:
                result['diff'] = {'prepared': diff}

    module.exit_json(**result)
コード例 #40
0
def main():
    """ main entry point for module execution
    """
    element_spec = dict(name=dict(),
                        vlan_id=dict(type='int'),
                        description=dict(default=DEFAULT_DESCRIPTION),
                        interfaces=dict(),
                        state=dict(default='present',
                                   choices=['present', 'absent']),
                        active=dict(default=True, type='bool'))

    aggregate_spec = deepcopy(element_spec)
    aggregate_spec['name'] = dict(required=True)

    # remove default in aggregate spec, to handle common arguments
    remove_default_spec(aggregate_spec)

    argument_spec = dict(
        aggregate=dict(type='list', elements='dict', options=aggregate_spec))

    argument_spec.update(element_spec)
    argument_spec.update(junos_argument_spec)

    required_one_of = [['aggregate', 'name']]
    mutually_exclusive = [['aggregate', 'name']]

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

    warnings = list()
    check_args(module, warnings)

    result = {'changed': False}

    if warnings:
        result['warnings'] = warnings

    top = 'vlans/vlan'

    param_to_xpath_map = collections.OrderedDict()
    param_to_xpath_map.update([('name', {
        'xpath': 'name',
        'is_key': True
    }), ('vlan_id', 'vlan-id'), ('description', 'description')])

    params = to_param_list(module)
    requests = list()

    for param in params:
        # if key doesn't exist in the item, get it from module.params
        for key in param:
            if param.get(key) is None:
                param[key] = module.params[key]

        item = param.copy()

        validate_param_values(module, param_to_xpath_map, param=item)

        want = map_params_to_obj(module, param_to_xpath_map, param=item)
        requests.append(map_obj_to_ele(module, want, top, param=item))

    with locked_config(module):
        for req in requests:
            diff = load_config(module, tostring(req), warnings, action='merge')

        commit = not module.check_mode
        if diff:
            if commit:
                commit_configuration(module)
            else:
                discard_changes(module)
            result['changed'] = True

            if module._diff:
                result['diff'] = {'prepared': diff}

    module.exit_json(**result)
コード例 #41
0
ファイル: junos_system.py プロジェクト: jdeer0618/ansible-1
def main():
    """ main entry point for module execution
    """
    argument_spec = dict(hostname=dict(),
                         domain_name=dict(),
                         domain_search=dict(type='list'),
                         name_servers=dict(type='list'),
                         state=dict(choices=['present', 'absent'],
                                    default='present'),
                         active=dict(default=True, type='bool'))

    argument_spec.update(junos_argument_spec)

    params = ['hostname', 'domain_name', 'domain_search', 'name_servers']
    required_if = [('state', 'present', params, True),
                   ('state', 'absent', params, True),
                   ('state', 'active', params, True),
                   ('state', 'suspend', params, True)]

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

    warnings = list()
    check_args(module, warnings)

    result = {'changed': False}

    if warnings:
        result['warnings'] = warnings

    top = 'system'

    param_to_xpath_map = collections.OrderedDict()
    param_to_xpath_map.update([('hostname', {
        'xpath': 'host-name',
        'leaf_only': True
    }), ('domain_name', {
        'xpath': 'domain-name',
        'leaf_only': True
    }),
                               ('domain_search', {
                                   'xpath': 'domain-search',
                                   'leaf_only': True,
                                   'value_req': True
                               }),
                               ('name_servers', {
                                   'xpath': 'name-server/name',
                                   'is_key': True
                               })])

    validate_param_values(module, param_to_xpath_map)

    want = list()
    want.append(map_params_to_obj(module, param_to_xpath_map))
    ele = map_obj_to_ele(module, want, top)

    kwargs = {'commit': not module.check_mode}
    kwargs['action'] = 'replace'

    diff = load_config(module, tostring(ele), warnings, **kwargs)

    if diff:
        result.update({
            'changed': True,
            'diff': diff,
        })

    module.exit_json(**result)
コード例 #42
0
ファイル: junos_linkagg.py プロジェクト: ernstp/ansible
def main():
    """ main entry point for module execution
    """
    element_spec = dict(
        name=dict(),
        mode=dict(default='on', choices=['on', 'off', 'active', 'passive']),
        members=dict(type='list'),
        min_links=dict(type='int'),
        device_count=dict(type='int'),
        description=dict(),
        state=dict(default='present', choices=['present', 'absent', 'up', 'down']),
        active=dict(default=True, type='bool')
    )

    aggregate_spec = deepcopy(element_spec)
    aggregate_spec['name'] = dict(required=True)

    # remove default in aggregate spec, to handle common arguments
    remove_default_spec(aggregate_spec)

    argument_spec = dict(
        aggregate=dict(type='list', elements='dict', options=aggregate_spec),
    )

    argument_spec.update(element_spec)
    argument_spec.update(junos_argument_spec)

    required_one_of = [['name', 'aggregate']]
    mutually_exclusive = [['name', 'aggregate']]

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

    warnings = list()
    check_args(module, warnings)

    result = {'changed': False}

    if warnings:
        result['warnings'] = warnings

    params = to_param_list(module)
    requests = list()
    for param in params:
        # if key doesn't exist in the item, get it from module.params
        for key in param:
            if param.get(key) is None:
                param[key] = module.params[key]

        item = param.copy()
        state = item.get('state')
        item['disable'] = True if state == 'down' else False

        if state in ('present', 'up', 'down'):
            item['state'] = 'present'

        else:
            item['disable'] = True

        mode = item.get('mode')
        if mode == 'off':
            item['mode'] = ''
        elif mode == 'on':
            item['mode'] = 'passive'

        configure_lag_params(module, requests, item)
        configure_member_params(module, requests, item)

    diff = None
    with locked_config(module):
        for req in requests:
            diff = load_config(module, tostring(req), warnings, action='merge')

        commit = not module.check_mode
        if diff:
            if commit:
                commit_configuration(module)
            else:
                discard_changes(module)
            result['changed'] = True

            if module._diff:
                result['diff'] = {'prepared': diff}

    module.exit_json(**result)
コード例 #43
0
def main():
    """ main entry point for module execution
    """
    argument_spec = dict(
        name=dict(required=True),
        description=dict(),
        enabled=dict(default=True, type='bool'),
        speed=dict(),
        mtu=dict(type='int'),
        duplex=dict(choices=['full', 'half', 'auto']),
        tx_rate=dict(),
        rx_rate=dict(),
        collection=dict(),
        purge=dict(default=False, type='bool'),
        state=dict(default='present',
                   choices=['present', 'absent', 'active', 'suspend']))

    argument_spec.update(junos_argument_spec)

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

    warnings = list()
    check_args(module, warnings)

    result = {'changed': False}

    if warnings:
        result['warnings'] = warnings

    top = 'interfaces/interface'

    param_to_xpath_map = collections.OrderedDict()
    param_to_xpath_map.update({
        'name': 'name',
        'description': 'description',
        'speed': 'speed',
        'mtu': 'mtu',
        'enabled': {
            'xpath': 'disable',
            'tag_only': True
        },
        'duplex': 'link-mode'
    })

    choice_to_value_map = {
        'link-mode': {
            'full': 'full-duplex',
            'half': 'half-duplex',
            'auto': 'automatic'
        },
        'disable': {
            True: False,
            False: True
        }
    }

    validate_param_values(module, param_to_xpath_map)

    want = list()
    want.append(map_params_to_obj(module, param_to_xpath_map))

    ele = map_obj_to_ele(module, want, top, choice_to_value_map)

    kwargs = {'commit': not module.check_mode}
    kwargs['action'] = 'replace'

    diff = load_config(module, tostring(ele), warnings, **kwargs)

    if diff:
        result.update({
            'changed': True,
            'diff': {
                'prepared': diff
            },
            'rpc': tostring(ele)
        })

    module.exit_json(**result)