示例#1
0
def main():

    module = AnsibleModule(argument_spec=dict(
        hostname=dict(required=True),
        username=dict(required=True),
        password=dict(required=True, no_log=True),
    ))

    hostname = module.params['hostname']
    username = module.params['username']
    password = module.params['password']
    changed = False
    msg = ""

    mk = mt_api.Mikrotik(hostname, username, password)
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    result = sock.connect_ex((hostname, 8728))
    if result == 0:
        try:
            mk.login()
        except:
            module.fail_json(
                msg=
                "Could not log into Mikrotik device.  Check the username and password."
            )
    else:
        module.fail_json(
            msg="Could not access RouterOS api." +
            " Verify API service is enabled and not blocked by firewall.")

    # response = apiros.talk([b'/ip/address/add', b'=address=192.168.15.2/24', b'=interface=ether7'])
    module.exit_json(
        changed=False,
        failed=False,
    )
示例#2
0
def main():

    module = AnsibleModule(argument_spec=dict(
        hostname=dict(required=True),
        username=dict(required=True),
        password=dict(required=True, no_log=True),
    ))

    hostname = module.params['hostname']
    username = module.params['username']
    password = module.params['password']
    changed = False
    msg = ""

    mk = mt_api.Mikrotik(hostname, username, password)
    try:
        mk.login()
    except:
        module.fail_json(
            msg=
            "Could not log into Mikrotik device.  Check the username and password."
        )

    # response = apiros.talk([b'/ip/address/add', b'=address=192.168.15.2/24', b'=interface=ether7'])
    module.exit_json(
        changed=False,
        failed=False,
    )
示例#3
0
 def login(self):
     self.mk = mt_api.Mikrotik(
         self.hostname,
         self.username,
         self.password,
     )
     try:
         self.mk.login()
         self.login_success = True
     except:
         self.failed_msg = "Could not log into Mikrotik device, check the username and password."
示例#4
0
def main():

  module = AnsibleModule(
      argument_spec=dict(
          hostname=dict(required=True),
          username=dict(required=True),
          password=dict(required=True, no_log=True),
          command=dict(required=True, type='str'),
          command_arguments=dict(required=False, type='dict'),
      )
  )

  hostname     = module.params['hostname']
  username     = module.params['username']
  password     = module.params['password']
  changed = False
  changed_message = []

  mk = mt_api.Mikrotik(hostname, username, password)
  try:
    mk.login()
  except:
    module.fail_json(
        msg="Could not log into Mikrotik device." +
        " Check the username and password.",
    )

  api_path = module.params['command']

  if module.params['command_arguments'] != None:
    response = mk.api_command(base_path=api_path, params=module.params['command_arguments'])
  else:
    response = mk.api_command(base_path=api_path)

  if response[-1][0] == '!done':
    changed = True
    changed_message.append(response)
    changed_message.append(api_path)
    if module.params['command_arguments'] != None:
      changed_message.append(module.params['command_arguments'])

  if changed:
    module.exit_json(
        failed=False,
        changed=True,
        msg=changed_message
    )
  else:
    module.exit_json(
        failed=False,
        changed=False,
        msg="Command failed"
    )
示例#5
0
 def login(self):
     self.mk = mt_api.Mikrotik(
         self.hostname,
         self.username,
         self.password,
     )
     sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
     result = sock.connect_ex((self.hostname, 8728))
     if result == 0:
         try:
             self.mk.login()
             self.login_success = True
         except:
             self.failed_msg = "Could not log into Mikrotik device." + " Check the username and password.",
     else:
         self.failed_msg = "Could not access RouterOS api." + " Verify API service is enabled and not blocked by firewall.",
示例#6
0
def main():

    module = AnsibleModule(argument_spec=dict(
        hostname=dict(required=True),
        username=dict(required=True),
        password=dict(required=True, no_log=True),
        interface=dict(required=True, type='str'),
        address=dict(
            required=True, type='str', aliases=['ip', 'addr', 'ip_address']),
        network=dict(required=False, type='str', default=""),
        comment=dict(required=False, type='str', default=""),
        state=dict(required=False,
                   default="present",
                   choices=['present', 'absent'],
                   type='str'),
    ))

    hostname = module.params['hostname']
    username = module.params['username']
    password = module.params['password']
    ip_address = module.params['address']
    interface = module.params['interface']
    network = module.params['network']
    ip_state = module.params['state']
    comment = module.params['comment']
    changed = False
    msg = ""

    interface_path = '/interface'
    address_path = '/ip/address'
    address_print_params = {
        ".proplist": "interface,address,.id,network,netmask,comment"
    }
    interface_print_params = {".proplist": "name,.id,type"}
    mk = mt_api.Mikrotik(hostname, username, password)
    try:
        mk.login()
        interfaces = mk.api_print(interface_path, interface_print_params)
    except:
        module.fail_json(msg="Could not log into Mikrotik device." +
                         " Check the username and password.", )

    ###################################
    # Check if interface is present
    # exit if interface is not present
    ###################################
    interfacelist = []
    exitmessage = []
    for i in range(0, len(interfaces) - 1):
        interfacelist.append(interfaces[i][1]["name"])
    intExists = False

    if (interface in interfacelist):
        intExists = True
        # module.exit_json(failed=False, changed=False, msg=interfacelist)
    if intExists:
        pass
        #exitmessage.append("Interface " + interface + " exists.") #this is never used
    else:
        exitmessage.append("Interface " + interface + " does not exist.")
        module.fail_json(failed=True, msg=exitmessage)

    ##############################################
    # Check if IP address is set on the interface
    # make no changes if address already set
    ##############################################
    ip_addresses = mk.api_print(address_path, address_print_params)

    iplist = []
    for i in range(0, len(ip_addresses) - 1):
        iplist.append(ip_addresses[i][1]["address"])
        if ip_addresses[i][1]["address"] == ip_address:
            ip_id = ip_addresses[i][1][".id"]

    if ip_state == "present":
        if ip_address in iplist:
            module.exit_json(
                failed=False,
                #msg="IP Address: " + ip_address +
                #" is already configured" +
                #" on interface " + interface,
            )

        else:
            add_dict = {
                'address': ip_address,
                'interface': interface,
                'comment': comment
            }
            response = mk.api_add(address_path, add_dict)
            module.exit_json(
                failed=False,
                changed=True,
                #msg="IP address: " + ip_address + " has been configured" +
                #" on interface " + interface
            )

    if ip_state == "absent":
        if ip_address in iplist:
            response = mk.api_remove(address_path, ip_id)
            module.exit_json(
                failed=False,
                changed=True,
                #msg="IP Address: " + ip_address +
                #" has been removed"
            )

        else:
            module.exit_json(
                failed=False,
                changed=False,
                #msg="IP Address: " + ip_address +
                #" is already absent"
            )
def main():
    module = AnsibleModule(argument_spec=dict(
        hostname=dict(required=True),
        username=dict(required=True),
        password=dict(required=True, no_log=True),
        name=dict(required=False, type='str'),
        comment=dict(required=False, type='str'),
        admin_mac=dict(required=False, type='str'),
        auto_mac=dict(required=False, type='str'),
        ageing_time=dict(required=False, type='str'),
        forward_delay=dict(required=False, type='str'),
        max_message_age=dict(required=False, type='str'),
        transmit_hold_count=dict(required=False, type='str'),
        arp=dict(required=False,
                 choices=['disabled', 'enabled', 'proxy-arp', 'reply-only'],
                 type='str'),
        protocol_mode=dict(required=False,
                           choices=['none', 'rstp', 'stp'],
                           type='str'),
        settings=dict(required=False, type='dict'),
        state=dict(required=False, choices=['present', 'absent'], type='str'),
    ),
                           supports_check_mode=True)

    hostname = module.params['hostname']
    username = module.params['username']
    password = module.params['password']
    state = module.params['state']
    ansible_bridge_name = module.params['name']
    check_mode = module.check_mode
    changed = False
    changed_message = []
    msg = ""

    mk = mt_api.Mikrotik(hostname, username, password)
    try:
        mk.login()
    except:
        module.fail_json(msg="Could not log into Mikrotik device." +
                         " Check the username and password.", )

    bridge_path = '/interface/bridge'

    response = mk.api_print(base_path=bridge_path)
    bridge_params = module.params
    mikrotik_bridge = {}
    for item in response:
        if 'name' in item[1]:
            if ansible_bridge_name == item[1]['name']:
                mikrotik_bridge = item[1]

    ########################################################
    # Check if we need to edit the bridge settings
    ########################################################
    if bridge_params['settings'] is not None:
        settings_path = '/interface/bridge/settings'
        settings_response = mk.api_print(settings_path)
        settings_response = settings_response[0][1]
        settings = bridge_params['settings']
        bridge_settings_diff_keys = {}

        for key in settings:
            if isinstance(settings[key], bool):
                settings[key] = str(settings[key])
                settings[key] = str.lower(settings[key])
            else:
                if settings[key] == "yes":
                    settings[key] = "true"
                if settings[key] == "no":
                    settings[key] = "false"

        for key in settings:
            if key in settings_response:
                if settings[key] != settings_response[key]:
                    bridge_settings_diff_keys[key] = settings[key]
            else:
                bridge_settings_diff_keys[key] = settings[key]

        if bridge_settings_diff_keys != {}:
            if not check_mode:
                mk.api_edit(base_path=settings_path,
                            params=bridge_settings_diff_keys)
            changed_message.append(bridge_settings_diff_keys)
            changed = True
        else:
            changed = False

    #######################################
    # remove unneeded parameters
    # clean up parameters
    ######################################

    remove_params = ['hostname', 'username', 'password', 'state', 'settings']
    for i in remove_params:
        del bridge_params[i]

    clean_params(bridge_params)

    if '.id' in mikrotik_bridge:
        client_id = mikrotik_bridge['.id']
    else:
        client_id = False

    ##################################################################
    # We need to make sure that bridge_bridge name is a string
    # if it's null then it has not been defined.
    ###################################################################
    if (state == "present" and isinstance(ansible_bridge_name, str)):
        if mikrotik_bridge == {}:
            if not check_mode:
                mk.api_add(base_path=bridge_path, params=bridge_params)
            changed_message.append(ansible_bridge_name + " added")
            changed = True,
        else:
            bridge_diff_keys = {}

            for key in bridge_params:
                if key in mikrotik_bridge:
                    if bridge_params[key] != mikrotik_bridge[key]:
                        bridge_diff_keys[key] = bridge_params[key]
                else:
                    bridge_diff_keys[key] = bridge_params[key]
            if bridge_diff_keys != {}:
                bridge_diff_keys['numbers'] = client_id
                if not check_mode:
                    mk.api_edit(base_path=bridge_path, params=bridge_diff_keys)
                changed = True
                changed_message.append("Changed bridge: " +
                                       bridge_params['name'])
            else:
                ####################
                # Already up date
                ###################
                if not changed:
                    changed = False

    elif state == "absent":
        if client_id:
            if not check_mode:
                mk.api_remove(base_path=bridge_path, remove_id=client_id)
            changed_message.append(bridge_params['name'] + " removed")
            changed = True
        #####################################################
        # if client_id is not set there is nothing to remove
        #####################################################
        else:
            if not changed:
                changed = False
    elif settings:
        ########################################################
        # if settings were set we were modifying bridge settings
        # only
        pass
    else:
        module.exit_json(
            failed=True,
            changed=False,
        )

    if changed:
        module.exit_json(failed=False, changed=True, msg=changed_message)
    else:
        module.exit_json(
            failed=False,
            changed=False,
        )
示例#8
0
def main():
  module = AnsibleModule(
    argument_spec=dict(
      hostname    =dict(required=True),
      username    =dict(required=True),
      password    =dict(required=True),
      interface   =dict(required=True, type='str'),
      bridge =dict(required=False, type='str'),
      comment     =dict(required=False, type='str'),
      path_cost   =dict(required=False, type='str'),
      priority    =dict(required=False, type='str'),
      horizon     =dict(required=False, type='str'),
      external_fdb=dict(
        required=False,
        choices=['yes', 'no', 'auto'],
        type='str'
      ),
      auto_isolate=dict(
        required=False,
        choices=['yes', 'no'],
        type='str'
      ),
      edge=dict(
        required=False,
        choices=['auto', 'yes', 'no', 'no-discover', 'yes-discover'],
        type='str'
      ),
      point_to_point=dict(
        required=False,
        choices=['yes', 'no', 'auto'],
        type='str'
      ),
      state=dict(
        required=True,
        choices=['present', 'absent'],
        type='str'
      ),
    ),
    supports_check_mode=True
  )

  hostname     = module.params['hostname']
  username     = module.params['username']
  password     = module.params['password']
  state        = module.params['state']
  ansible_bridge_port_interface  = module.params['interface']
  changed = False
  changed_message = []
  check_mode = module.check_mode
  msg = ""

  mk = mt_api.Mikrotik(hostname, username, password)
  try:
    mk.login()
  except:
    module.fail_json(
        msg="Could not log into Mikrotik device." +
        " Check the username and password.",
    )

  bridge_port_path = '/interface/bridge/port'

  response = mk.api_print(base_path=bridge_port_path)
  bridge_port_params = module.params
  mikrotik_bridge_port = {}
  for item in response:
    if 'interface' in item[1].keys():
      if ansible_bridge_port_interface == item[1]['interface']:
        mikrotik_bridge_port = item[1]

  #######################################
  # remove unneeded parameters
  ######################################

  remove_params = ['hostname', 'username', 'password', 'state']
  for i in remove_params:
    del bridge_port_params[i]

  ##########################################
  # modify clean_params in place
  ############################################
  clean_params(bridge_port_params)

  if '.id' in mikrotik_bridge_port:
    client_id = mikrotik_bridge_port['.id']
  else:
    client_id = False

  if state == "present":
    if mikrotik_bridge_port == {}:
      if not check_mode:
        mk.api_add(
            base_path=bridge_port_path,
            params=bridge_port_params
        )
      changed_message.append(ansible_bridge_port_interface + " added to bridge")
      changed = True,
    else:
      bridge_port_diff_keys = {}

      for key in bridge_port_params:
        if key in mikrotik_bridge_port:
          if bridge_port_params[key] != mikrotik_bridge_port[key]:
            bridge_port_diff_keys[key] = bridge_port_params[key]
        else:
          bridge_port_diff_keys[key] = bridge_port_params[key]
      if bridge_port_diff_keys != {}:
        bridge_port_diff_keys['numbers'] = client_id
        if not check_mode:
          mk.api_edit(base_path=bridge_port_path, params=bridge_port_diff_keys)
        changed = True
        changed_message.append("Changed bridge port: " + bridge_port_params['bridge'])
      else:
        ####################
        # Already up date
        ###################
        if not changed:
          changed = False

  elif state == "absent":
    if client_id:
      if not check_mode:
        mk.api_remove(base_path=bridge_port_path, remove_id=client_id)
      changed_message.append(bridge_port_params['interface'] + " removed")
      changed = True
    #####################################################
    # if client_id is not set there is nothing to remove
    #####################################################
    else:
      if not changed:
        changed = False
  else:
    module.exit_json(
        failed=True,
        changed=False,
    )

  if changed:
    module.exit_json(
        failed=False,
        changed=True,
        msg=changed_message
    )
  else:
    module.exit_json(
        failed=False,
        changed=False,
    )
def main():

  module = AnsibleModule(
    argument_spec=dict(
      hostname  = dict(required=True),
      username  = dict(required=True),
      password  = dict(required=True),
      list_name  = dict(required=True, type='str'),
      address_list = dict(required=False, type='list'),
      state = dict(
        required  = False,
        default   = "present",
        choices   = ['present', 'absent', 'force'],
        type      = 'str'
      ),
    ),
    supports_check_mode=True
  )

  hostname     = module.params['hostname']
  username     = module.params['username']
  password     = module.params['password']
  ansible_list_name = module.params['list_name']
  ansible_address_list = module.params['address_list']
  state        = module.params['state']
  check_mode   = module.check_mode
  changed      = False
  msg = ""

  address_list_path = '/ip/firewall/address-list'
  mk = mt_api.Mikrotik(hostname, username, password)
  try:
    mk.login()
  except:
    module.fail_json(
      msg="Could not log into Mikrotik device." +
      " Check the username and password.",
    )

  response = mk.api_print(address_list_path)
  mikrotik_address_list = []
  mikrotik_address_id = {}
  list_name = ansible_list_name
  for item in response:
    if 'list' in item[1].keys():
      address = item[1]['address']
      if item[1]['list'] == list_name:
        temp_dict = {}
        temp_dict['address'] = item[1]['address']
        if 'comment' in item[1].keys():
          temp_dict['comment'] = item[1]['comment']
        mikrotik_address_list.append(dict(temp_dict))
        mikrotik_address_id[address] = item[1]['.id']

  if state == "present":
    if ansible_address_list == mikrotik_address_list:
      module.exit_json(
        changed = False,
        failed  = False,
        msg     = "list up to date",
      )
    common_list = []
    for item in ansible_address_list:
      for item2 in mikrotik_address_list:
        if item['address'] in item2['address']:
          common_list.append(item['address'])
          if item['comment'] in item2['comment']:
            ##################
            # update comment
            #################
            pass

    #################################
    # build add_list
    # add item missing from mikrotik
    #################################
    add_list = []
    for item in ansible_address_list:
      if item['address'] not in common_list:
        temp_dict = {}
        temp_dict['address'] = item['address']
        temp_dict['comment'] = item['comment']
        add_list.append(dict(temp_dict))

    for i in add_list:
      #address = i['address']
      #comment = i['comment']
      add_dictionary = {
        "address": i['address'],
        "list": list_name,
        "comment": i['comment']
      }
      if not check_mode:
        mk.api_add(address_list_path, add_dictionary)
      changed = True

    #####################
    # build remove list
    ######################
    remove_list = []
    for item in mikrotik_address_list:
      if item['address'] not in common_list:
        remove_list.append(item['address'])
    #######################################
    # Remove every item in the address_list
    #######################################
    for i in remove_list:
      remove_id = mikrotik_address_id[i]
      if not check_mode:
        mk.api_remove(address_list_path, remove_id)
      if not changed:
        changed = True
  else:
    #######################################
    # Remove every item
    #######################################
    for remove_id in mikrotik_address_id.values():
      if not check_mode:
        mk.api_remove(address_list_path, remove_id)
      if not changed:
        changed = True

  if changed:
    module.exit_json(
      changed = True,
      failed = False,
      msg    = ansible_list_name + "has been modified",
     )
  else:
    module.exit_json(
      changed = False,
      failed = False,
      msg    = ansible_list_name + " is up to date",
    )
def main():
    module = AnsibleModule(argument_spec=dict(
        hostname=dict(required=True),
        username=dict(required=True),
        password=dict(required=True),
        address=dict(required=False, type='str'),
        comment=dict(required=True, type='str'),
        secret=dict(required=False, type='str'),
        service=dict(required=False, type='list'),
        timeout=dict(required=False, type='str'),
        incoming=dict(required=False, type='dict'),
        state=dict(required=True, choices=['present', 'absent'], type='str'),
    ),
                           supports_check_mode=True)

    hostname = module.params['hostname']
    username = module.params['username']
    password = module.params['password']
    state = module.params['state']
    check_mode = module.check_mode
    changed = False
    msg = ""

    radius_path = '/radius'
    mk = mt_api.Mikrotik(hostname, username, password)
    try:
        mk.login()
    except:
        module.fail_json(msg="Could not log into Mikrotik device." +
                         " Check the username and password.", )

    response = mk.api_print(radius_path)
    radius_params = module.params

    ########################################################
    # Check if we need to edit the incoming radius settings
    ########################################################
    if radius_params['incoming'] is not None:
        incoming_path = '/radius/incoming'
        incoming_response = mk.api_print(incoming_path)
        incoming = radius_params['incoming']
        if incoming_response[0][1]['accept'] == incoming['accept']:
            if incoming_response[0][1]['port'] == incoming['port']:
                # nothing to do
                pass
            else:
                # edit port
                if not check_mode:
                    mk.api_edit(base_path=incoming_path, params=incoming)
        else:
            # edit the accept and the port
            if not check_mode:
                mk.api_edit(base_path=incoming_path, params=incoming)
    #######################################
    # Since we are grabbing all the parameters passed by the module
    # We need to remove the one that won't be used
    # as mikrotik parameters
    remove_params = ['hostname', 'username', 'password', 'state', 'incoming']
    for i in remove_params:
        radius_params.pop(i)
    #######################################
    # remove keys with empty values
    # convert service list to stings
    ######################################
    for key in radius_params.keys():
        if radius_params[key] is None:
            radius_params.pop(key)

    #################################################
    # Convert service list to comma separated string
    #################################################
    list_to_string = ""
    if 'service' in radius_params:
        list_to_string = ','.join(map(str, radius_params['service']))
        radius_params['service'] = list_to_string

    ################################################
    # mikrotik_radius is the dictionary with the parameters
    # we get from mikrotik
    #################################
    # We grab the first radius item to
    # match the comment
    #################################
    mikrotik_radius = {}
    for i in response:
        if 'comment' in i[1]:
            if i[1]['comment'] == radius_params['comment']:
                mikrotik_radius = i[1]
                break

    ##########################################################
    # Define radius_id to be used by remove and edit function
    ##########################################################
    if '.id' in mikrotik_radius:
        radius_id = mikrotik_radius['.id']
    else:
        radius_id = False

    ######################################################
    # If the state is present and we can't find matching
    # radius comment we add a new item with all the parameters
    # from Ansible
    #######################################################
    if state == "present":
        if mikrotik_radius == {}:
            if not check_mode:
                mk.api_add(base_path=radius_path, params=radius_params)
            module.exit_json(
                failed=False,
                changed=True,
                msg="Added radius item",
            )
        ###################################################
        # If an item exists we check if all the parameters
        # match what we have in ansible
        ######################################
        else:
            radius_diff_keys = {}
            for key in radius_params:
                if radius_params[key] != mikrotik_radius[key]:
                    radius_diff_keys[key] = radius_params[key]
            if radius_diff_keys != {}:
                radius_diff_keys['numbers'] = radius_id
                if not check_mode:
                    mk.api_edit(base_path=radius_path, params=radius_diff_keys)
                module.exit_json(failed=False,
                                 changed=True,
                                 msg="Changed radius item: " +
                                 radius_params['comment'])
            else:
                ####################
                # Already up date
                module.exit_json(
                    failed=False,
                    changed=False,
                )
    elif state == "absent":
        if radius_id:
            if not check_mode:
                mk.api_remove(base_path=radius_path, remove_id=radius_id)
            module.exit_json(failed=False,
                             changed=True,
                             msg=radius_params['comment'] + " removed")
        #####################################################
        # if radius_id is not set there is nothing to remove
        #####################################################
        else:
            module.exit_json(
                failed=False,
                changed=False,
            )
    else:
        module.exit_json(
            failed=True,
            changed=False,
        )
def main():
    module = AnsibleModule(argument_spec=dict(
        hostname=dict(required=True),
        username=dict(required=True),
        password=dict(required=True, no_log=True),
        name=dict(required=True, type='str'),
        on_event=dict(required=False, type='str'),
        comment=dict(required=False, type='str'),
        interval=dict(required=False, type='str'),
        policy=dict(required=False, type='list'),
        start_date=dict(required=False, type='str'),
        start_time=dict(required=False, type='str'),
        state=dict(required=True, choices=['present', 'absent'], type='str'),
    ),
                           supports_check_mode=True)

    hostname = module.params['hostname']
    username = module.params['username']
    password = module.params['password']
    state = module.params['state']
    check_mode = module.check_mode
    ansible_scheduler_name = module.params['name']
    changed = False
    changed_message = []
    msg = ""

    mk = mt_api.Mikrotik(hostname, username, password)
    try:
        mk.login()
    except:
        module.fail_json(msg="Could not log into Mikrotik device." +
                         " Check the username and password.", )

    api_path = '/system/scheduler'

    response = mk.api_print(base_path=api_path)
    ansible_scheduler_params = module.params
    mikrotik_scheduler_task = {}
    for item in response:
        if 'name' in item[1]:
            if ansible_scheduler_name == item[1]['name']:
                mikrotik_scheduler_task = item[1]

    #######################################
    # remove unneeded parameters
    ######################################

    remove_params = ['hostname', 'username', 'password', 'state']
    for i in remove_params:
        del ansible_scheduler_params[i]

    ##########################################
    # modify params in place
    ############################################
    clean_params(ansible_scheduler_params)

    if '.id' in mikrotik_scheduler_task:
        client_id = mikrotik_scheduler_task['.id']
    else:
        client_id = False

    if state == "present":
        #################################################
        # Convert policy list to comma separated string
        #################################################

        if mikrotik_scheduler_task == {}:
            if 'policy' in ansible_scheduler_params:
                list_to_string = ""
                list_to_string = ','.join(
                    map(str, ansible_scheduler_params['policy']))
                ansible_scheduler_params['policy'] = list_to_string
            if not check_mode:
                mk.api_add(base_path=api_path, params=ansible_scheduler_params)
            changed_message.append(ansible_scheduler_name + " added to bridge")
            changed = True,
        else:
            scheduler_diff_keys = {}

            ########################################################################
            # policy parameter is a comma separated list of values in a string that
            # we receive from mikrotik
            # we need to convert it to a list and then do a comparison against
            # ansible policy list to get the difference
            # if there is a difference between the two we need to convert the
            # ansible_scheduler_params['policy'] to a string with comma separated values
            #########################################################################

            if 'policy' in ansible_scheduler_params:
                dif_list = []
                if 'policy' in mikrotik_scheduler_task:
                    policy = mikrotik_scheduler_task['policy'].split(',')
                    dif_list = set(
                        ansible_scheduler_params['policy']) & set(policy)

                if dif_list == []:
                    list_to_string = ""
                    list_to_string = ','.join(
                        map(str, ansible_scheduler_params['policy']))
                    scheduler_diff_keys['policy'] = list_to_string

            for key in ansible_scheduler_params:
                if key != 'policy':
                    if key in mikrotik_scheduler_task:
                        if ansible_scheduler_params[
                                key] != mikrotik_scheduler_task[key]:
                            scheduler_diff_keys[
                                key] = ansible_scheduler_params[key]
                    else:
                        scheduler_diff_keys[key] = ansible_scheduler_params[
                            key]
            if scheduler_diff_keys != {}:
                scheduler_diff_keys['numbers'] = client_id
                if not check_mode:
                    mk.api_edit(base_path=api_path, params=scheduler_diff_keys)
                changed = True
                changed_message.append("Changed scheduler task : " +
                                       ansible_scheduler_params['name'])
            else:
                ####################
                # Already up date
                ###################
                if not changed:
                    changed = False

    elif state == "absent":
        if client_id:
            if not check_mode:
                mk.api_remove(base_path=api_path, remove_id=client_id)
            changed_message.append(ansible_scheduler_params['name'] +
                                   " removed")
            changed = True
        #####################################################
        # if client_id is not set there is nothing to remove
        #####################################################
        else:
            if not changed:
                changed = False
    else:
        module.exit_json(failed=True, changed=False, msg="state is invalid")

    if changed:
        module.exit_json(failed=False, changed=True, msg=changed_message)
    else:
        module.exit_json(
            failed=False,
            changed=False,
        )
示例#12
0
def main():

  module = AnsibleModule(
    argument_spec=dict(
      hostname  = dict(required=True),
      username  = dict(required=True),
      password  = dict(required=True),
      rule      = dict(required=False, type='dict'),
      parameter = dict(required=True, type='str'),
      state = dict(
        required  = False,
        default   = "present",
        choices   = ['present', 'absent'],
        type      = 'str'
      ),
    ),
    supports_check_mode=True
  )

  hostname     = module.params['hostname']
  username     = module.params['username']
  password     = module.params['password']
  rule = module.params['rule']
  state        = module.params['state']
  api_path     = '/ip/firewall/' + module.params['parameter']
  check_mode      = module.check_mode
# ##############################################
# Check if "place-before" is an integer
# #############################################
  try:
    desired_order = int(rule['place-before'])
  except:
    module.exit_json(
      failed=True,
      changed=False,
      msg="place-before is not set or is not set to an integer",
    )
  changed = False
  msg = ""

  mk = mt_api.Mikrotik(hostname, username, password)
  try:
    mk.login()
  except:
    module.fail_json(
        msg="Could not log into Mikrotik device." +
        " Check the username and password.",
    )

  filter_response = mk.api_print(api_path)
  current_rule = None
  current_id = None
  existing_order = None
  last_item = len(filter_response) - 2
  changed_msg = []

  # Always set the comment to the order_number
  if 'comment' in rule:
    rule['comment'] = str(desired_order) + " " + str(rule['comment'])
  else:
    rule['comment'] = str(desired_order)

  if desired_order <= last_item:
    placed_at_the_end = False
  else:
    placed_at_the_end = True
    # remove the place-before if we are placing
    # the rule at the bottom of the chain
    rule.pop('place-before', None)

  # Check rule is not present
  # find existing rule
  # current_rule is what's on mikrotik right now
  for index, current_param in enumerate(filter_response):
    if 'comment' in current_param[1]:
      if re.search(r"^" + str(desired_order) + "\s+", current_param[1]['comment']):
        current_id = current_param[1]['.id']
        existing_order = index
        current_rule = current_param[1]
        # remove the place-before since we'll be editing not moving it
        rule.pop('place-before', None)

  # ensure the rule if state is present
  if state == "present":
    # if we don't have an existing rule to match
    # the desired we create a new one
    if not current_rule:
      if not check_mode:
        mk.api_add(api_path, rule)
      changed = True,
    # if current_rule is true we need to ensure the changes
    else:
      out_params = {}
      old_params = {}
      for desired_param in rule:
        rule[desired_param] = str(rule[desired_param])
        if desired_param in current_rule:
          if current_rule[desired_param] != rule[desired_param]:
            out_params[desired_param] = rule[desired_param]
            old_params[desired_param] = current_rule[desired_param]
        else:
          out_params[desired_param] = rule[desired_param]
          if desired_param in current_rule:
            old_params[desired_param] = current_rule[desired_param]

      # When out_params has been set it means we found our diff
      # and will set it on the mikrotik
      if out_params:
        if current_id is not None:
          out_params['.id'] = current_id

          if not check_mode:
            mk.api_edit(
                base_path = api_path,
                params    = out_params
            )

          # we don't need to show the .id in the changed message
          if '.id' in out_params:
            del out_params['.id']
          changed = True

          changed_msg.append({
              "new_params": out_params,
              "old_params": old_params,
          })

    # ensure the rule is in right position
    if current_id:
      if int(existing_order) != int(desired_order):
        api_path += '/move'
        params = False
        if placed_at_the_end:
          if existing_order > last_item:
            params = {
            '.id': current_id,
            }
        else:
          params = {
          '.id': current_id,
          'destination': desired_order
          }
        if params:
          if not check_mode:
            mk.api_command(api_path, params)
          changed_msg.append({
              "moved": existing_order,
              "to": old_params,
          })
          changed = True

#####################################
# Remove the rule
#####################################
  elif state == "absent":
    if current_rule:
      if not check_mode:
        mk.api_remove(api_path, current_id)
      changed = True
      changed_msg.append("removed rule: " + str(desired_order))
  else:
    failed = True

  if changed:
    module.exit_json(
        failed=False,
        changed=True,
        msg=changed_msg
      )
  elif not changed:
    module.exit_json(
        failed=False,
        changed=False,
      )
  else:
    module.fail_json()