Beispiel #1
0
def main():
    """ main entry point for module execution
    """
    element_spec = dict(
        name=dict(),
        full_name=dict(),
        role=dict(choices=ROLES),
        encrypted_password=dict(no_log=True),
        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()
    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)
def main():
    """main entry point for Ansible module"""
    argument_spec = dict(
        rpc=dict(required=True),
        args=dict(type="dict"),
        attrs=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()
    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 {}
    attrs = module.params["attrs"] or {}

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

    for key, value in iteritems(attrs):
        xattrs.update({key: value})

    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 = exec_rpc(module, tostring(element), ignore_warning=False)

    result["xml"] = 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"] = tostring(reply).split("\n")

    module.exit_json(**result)
    def set_state(self, want, have):
        """ Select the appropriate function based on the state provided

        :param want: the desired configuration as a dictionary
        :param have: the current configuration as a dictionary
        :rtype: A list
        :returns: the list xml configuration necessary to migrate the current
                  configuration
                  to the desired configuration
        """
        root = build_root_xml_node('interfaces')
        state = self._module.params['state']
        if state == 'overridden':
            config_xmls = self._state_overridden(want, have)
        elif state == 'deleted':
            config_xmls = self._state_deleted(want, have)
        elif state == 'merged':
            config_xmls = self._state_merged(want, have)
        elif state == 'replaced':
            config_xmls = self._state_replaced(want, have)

        for xml in config_xmls:
            root.append(xml)

        return tostring(root)
    def set_state(self, want, have):
        """ Select the appropriate function based on the state provided
        :param want: the desired configuration as a dictionary
        :param have: the current configuration as a dictionary
        :rtype: A list
        :returns: the list xml configuration necessary to migrate the current configuration
                  to the desired configuration
        """
        self.autonomous_system = None
        self.root = build_root_xml_node("configuration")
        self.protocols = build_child_xml_node(self.root, "protocols")
        self.routing_options = build_child_xml_node(self.root,
                                                    "routing-options")
        state = self._module.params["state"]
        if state in ("merged", "replaced", "rendered") and not want:
            self._module.fail_json(
                msg="value of config parameter must not be empty for state {0}"
                .format(state))
        config_xmls = []
        if state == "deleted":
            config_xmls = self._state_deleted(want, have)
        elif state == "purged":
            config_xmls = self._state_purged(want, have)
        elif state in ("merged", "rendered"):
            config_xmls = self._state_merged(want, have)
        elif state == "replaced":
            config_xmls = self._state_replaced(want, have)

        for xml in config_xmls:
            self.protocols.append(xml)
        temp_lst = []
        for xml in self.root.getchildren():
            xml = tostring(xml)
            temp_lst.append(xml)
        return temp_lst
    def set_state(self, want, have):
        """ Select the appropriate function based on the state provided

        :param want: the desired configuration as a dictionary
        :param have: the current configuration as a dictionary
        :rtype: A list
        :returns: the commands necessary to migrate the current configuration
                  to the desired configuration
        """
        state = self._module.params['state']
        root = build_root_xml_node('configuration')
        routing_options = build_child_xml_node(root, 'routing-options')
        routing_instances = build_child_xml_node(root, 'routing-instances')
        if state == 'overridden':
            config_xmls = self._state_overridden(want, have)
        elif state == 'deleted':
            config_xmls = self._state_deleted(want, have)
        elif state == 'merged':
            config_xmls = self._state_merged(want, have)
        elif state == 'replaced':
            config_xmls = self._state_replaced(want, have)

        for xml in config_xmls:
            if xml['root_type'] == 'routing-options':
                routing_options.append(xml['static_route_xml'])
            elif xml['root_type'] == 'routing-instances':
                routing_instances.append(xml['static_route_xml'])

        return [tostring(xml) for xml in root.getchildren()]
Beispiel #6
0
    def set_state(self, want, have):
        """ Select the appropriate function based on the state provided

        :param want: the desired configuration as a dictionary
        :param have: the current configuration as a dictionary
        :rtype: A list
        :returns: the commands necessary to migrate the current configuration
                  to the desired configuration
        """
        self.router_id = None
        self.root = build_root_xml_node("configuration")
        self.protocols = build_child_xml_node(self.root, "protocols")
        state = self._module.params["state"]
        if (state in ("merged", "replaced", "overridden", "rendered")
                and not want):
            self._module.fail_json(
                msg="value of config parameter must not be empty for state {0}"
                .format(state))
        config_xmls = []
        commands = []
        if state == "overridden":
            config_xmls = self._state_overridden(want, have)
        elif state == "deleted":
            config_xmls = self._state_deleted(want, have)
        elif state in ("merged", "rendered"):
            config_xmls = self._state_merged(want, have)
        elif state == "replaced":
            config_xmls = self._state_replaced(want, have)

        if config_xmls:
            for xml in config_xmls:
                self.protocols.append(xml)

            commands = [tostring(xml) for xml in self.root.getchildren()]
        return commands
Beispiel #7
0
    def set_state(self, want, have):
        """ Select the appropriate function based on the state provided

        :param want: the desired configuration as a dictionary
        :param have: the current configuration as a dictionary
        :rtype: A list
        :returns: the commands necessary to migrate the current configuration
                  to the desired configuration
        """
        root = build_root_xml_node("firewall")
        state = self._module.params["state"]
        config_xmls = []
        if state == "overridden":
            config_xmls = self._state_overridden(want, have)
        elif state == "deleted":
            config_xmls = self._state_deleted(want, have)
        elif state == "merged":
            config_xmls = self._state_merged(want, have)
        elif state == "replaced":
            config_xmls = self._state_replaced(want, have)

        for xml in config_xmls:
            root.append(xml)

        return tostring(root)
    def set_state(self, want, have):
        """ Select the appropriate function based on the state provided

        :param want: the desired configuration as a dictionary
        :param have: the current configuration as a dictionary
        :rtype: A list
        :returns: the list xml configuration necessary to migrate the current configuration
                  to the desired configuration
        """
        root = build_root_xml_node("interfaces")
        state = self._module.params["state"]
        if (state in ("merged", "replaced", "overridden", "rendered")
                and not want):
            self._module.fail_json(
                msg="value of config parameter must not be empty for state {0}"
                .format(state))
        if state == "overridden":
            config_xmls = self._state_overridden(want, have)
        elif state == "deleted":
            config_xmls = self._state_deleted(want, have)
        elif state in ("merged", "rendered"):
            config_xmls = self._state_merged(want, have)
        elif state == "replaced":
            config_xmls = self._state_replaced(want, have)

        for xml in config_xmls:
            root.append(xml)

        return tostring(root)
    def set_state(self, want, have):
        """ Select the appropriate function based on the state provided

        :param want: the desired configuration as a dictionary
        :param have: the current configuration as a dictionary
        :rtype: A list
        :returns: the commands necessary to migrate the current configuration
                  to the desired configuration
        """
        state = self._module.params["state"]
        if (state in ("merged", "replaced", "overridden", "rendered")
                and not want):
            self._module.fail_json(
                msg="value of config parameter must not be empty for state {0}"
                .format(state))
        root = build_root_xml_node("configuration")
        routing_options = build_child_xml_node(root, "routing-options")
        routing_instances = build_child_xml_node(root, "routing-instances")
        if state == "overridden":
            config_xmls = self._state_overridden(want, have)
        elif state == "deleted":
            config_xmls = self._state_deleted(want, have)
        elif state in ("merged", "rendered"):
            config_xmls = self._state_merged(want, have)
        elif state == "replaced":
            config_xmls = self._state_replaced(want, have)

        for xml in config_xmls:
            if xml["root_type"] == "routing-options":
                routing_options.append(xml["static_route_xml"])
            elif xml["root_type"] == "routing-instances":
                routing_instances.append(xml["static_route_xml"])

        return [tostring(xml) for xml in root.getchildren()]
Beispiel #10
0
    def set_state(self, want, have):
        """ Select the appropriate function based on the state provided

        :param want: the desired configuration as a dictionary
        :param have: the current configuration as a dictionary
        :rtype: A list
        :returns: the commands necessary to migrate the current configuration
                  to the desired configuration
        """
        self.router_id = None
        self.root = build_root_xml_node("configuration")
        self.protocols = build_child_xml_node(self.root, "protocols")
        self.routing_options = build_child_xml_node(
            self.root, "routing-options"
        )
        state = self._module.params["state"]
        config_xmls = []
        if state == "overridden":
            config_xmls = self._state_overridden(want, have)
        elif state == "deleted":
            config_xmls = self._state_deleted(want, have)
        elif state == "merged":
            config_xmls = self._state_merged(want, have)
        elif state == "replaced":
            config_xmls = self._state_replaced(want, have)

        for xml in config_xmls:
            self.protocols.append(xml)

        return [tostring(xml) for xml in self.root.getchildren()]
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()
    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)
Beispiel #12
0
def main():
    """ main entry point for module execution
    """
    argument_spec = dict(
        name=dict(),
        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()
    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, 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)
Beispiel #13
0
def get_resource_config(connection, config_filter=None, attrib=None):

    if attrib is None:
        attrib = {"inherit": "inherit"}

    get_ele = new_ele("get-configuration", attrib)
    if config_filter:
        get_ele.append(to_ele(config_filter))

    return connection.execute_rpc(tostring(get_ele))
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()
    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)
Beispiel #15
0
    def populate(self):
        config_format = self.module.params["config_format"]
        reply = get_configuration(self.module, format=config_format)

        if config_format == "xml":
            config = tostring(reply.find("configuration")).strip()

        elif config_format == "text":
            config = self.get_text(reply, "configuration-text")

        elif config_format == "json":
            config = self.module.from_json(reply.text.strip())

        elif config_format == "set":
            config = self.get_text(reply, "configuration-set")

        self.facts["config"] = config
Beispiel #16
0
    def populate(self):
        config_format = self.module.params['config_format']
        reply = get_configuration(self.module, format=config_format)

        if config_format == 'xml':
            config = tostring(reply.find('configuration')).strip()

        elif config_format == 'text':
            config = self.get_text(reply, 'configuration-text')

        elif config_format == 'json':
            config = self.module.from_json(reply.text.strip())

        elif config_format == 'set':
            config = self.get_text(reply, 'configuration-set')

        self.facts['config'] = config
Beispiel #17
0
def handle_purge(module, want):
    want_users = [item['name'] for item in want]
    element = Element('system')
    login = SubElement(element, 'login')

    conn = get_connection(module)
    try:
        reply = conn.execute_rpc(tostring(Element('get-configuration')), ignore_warning=False)
    except ConnectionError as exc:
        module.fail_json(msg=to_text(exc, errors='surrogate_then_replace'))

    users = reply.xpath('configuration/system/login/user/name')
    if users:
        for item in users:
            name = item.text
            if name not in want_users and name != 'root':
                user = SubElement(login, 'user', {'operation': 'delete'})
                SubElement(user, 'name').text = name
    if element.xpath('/system/login/user/name'):
        return element
Beispiel #18
0
    def populate(self):
        ele = Element("get-interface-information")
        SubElement(ele, "detail")
        reply = exec_rpc(self.module, tostring(ele))

        interfaces = {}

        for item in reply[0]:
            name = self.get_text(item, "name")
            obj = {
                "oper-status": self.get_text(item, "oper-status"),
                "admin-status": self.get_text(item, "admin-status"),
                "speed": self.get_text(item, "speed"),
                "macaddress": self.get_text(item, "hardware-physical-address"),
                "mtu": self.get_text(item, "mtu"),
                "type": self.get_text(item, "if-type"),
            }

            interfaces[name] = obj

        self.facts["interfaces"] = interfaces
Beispiel #19
0
def handle_purge(module, want):
    want_users = [item["name"] for item in want]
    element = Element("system")
    login = SubElement(element, "login")

    conn = get_connection(module)
    try:
        reply = conn.execute_rpc(tostring(Element("get-configuration")),
                                 ignore_warning=False)
    except ConnectionError as exc:
        module.fail_json(msg=to_text(exc, errors="surrogate_then_replace"))

    users = reply.xpath("configuration/system/login/user/name")
    if users:
        for item in users:
            name = item.text
            if name not in want_users and name != "root":
                user = SubElement(login, "user", {"operation": "delete"})
                SubElement(user, "name").text = name
    if element.xpath("/system/login/user/name"):
        return element
Beispiel #20
0
    def populate(self):
        ele = Element('get-interface-information')
        SubElement(ele, 'detail')
        reply = exec_rpc(self.module, tostring(ele))

        interfaces = {}

        for item in reply[0]:
            name = self.get_text(item, 'name')
            obj = {
                'oper-status': self.get_text(item, 'oper-status'),
                'admin-status': self.get_text(item, 'admin-status'),
                'speed': self.get_text(item, 'speed'),
                'macaddress': self.get_text(item, 'hardware-physical-address'),
                'mtu': self.get_text(item, 'mtu'),
                'type': self.get_text(item, 'if-type'),
            }

            interfaces[name] = obj

        self.facts['interfaces'] = interfaces
Beispiel #21
0
    def set_state(self, want, have):
        """ Select the appropriate function based on the state provided
        :param want: the desired configuration as a dictionary
        :param have: the current configuration as a dictionary
        :rtype: A list
        :returns: the list xml configuration necessary to migrate the current configuration
                  to the desired configuration
        """
        root = build_root_xml_node("chassis")
        ethernet_ele = build_subtree(root, "aggregated-devices/ethernet")
        state = self._module.params["state"]
        if state == "overridden":
            config_xmls = self._state_overridden(want, have)
        elif state == "deleted":
            config_xmls = self._state_deleted(want, have)
        elif state == "merged":
            config_xmls = self._state_merged(want, have)
        elif state == "replaced":
            config_xmls = self._state_replaced(want, have)

        for xml in config_xmls:
            ethernet_ele.append(xml)
        return tostring(root)
def main():
    """ main entry point for module execution
    """
    element_spec = dict(name=dict(),
                        ipv4=dict(),
                        ipv6=dict(),
                        filter_input=dict(),
                        filter_output=dict(),
                        filter6_input=dict(),
                        filter6_output=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()
    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
        }),
        ('filter_input', {
            'xpath': 'inet/filter/input',
            'top': 'unit/family'
        }),
        ('filter_output', {
            'xpath': 'inet/filter/output',
            'top': 'unit/family'
        }),
        ('filter6_input', {
            'xpath': 'inet6/filter/input',
            'top': 'unit/family'
        }),
        ('filter6_output', {
            'xpath': 'inet6/filter/output',
            'top': 'unit/family'
        }),
    ])

    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)
Beispiel #23
0
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()
    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)
Beispiel #24
0
def main():
    """ main entry point for module execution
    """
    element_spec = dict(
        name=dict(),
        full_name=dict(),
        role=dict(choices=ROLES),
        encrypted_password=dict(no_log=True),
        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()
    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)
Beispiel #25
0
def main():
    """ main entry point for module execution
    """
    argument_spec = dict(
        name=dict(),
        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()
    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, 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)
def zeroize(module):
    return exec_rpc(
        module,
        tostring(Element("request-system-zeroize")),
        ignore_warning=False,
    )
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()
    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='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)
Beispiel #28
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()
    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="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)
Beispiel #29
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"),
        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()
    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)
def main():
    """main entry point for Ansible module
    """
    argument_spec = dict(
        rpc=dict(required=True),
        args=dict(type='dict'),
        attrs=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()
    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 {}
    attrs = module.params['attrs'] or {}

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

    for key, value in iteritems(attrs):
        xattrs.update({key: value})

    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 = exec_rpc(module, tostring(element), ignore_warning=False)

    result['xml'] = 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'] = tostring(reply).split('\n')

    module.exit_json(**result)