def main():
    argument_spec = dict(
        src=dict(type='str', default=None),
        filter=dict(type='str', default=""),
    )

    argument_spec.update(fortios_argument_spec)

    required_if = fortios_required_if

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

    result = dict(changed=False)

    # fail if pyFG not present
    if not HAS_PYFG:
        module.fail_json(
            msg=
            'Could not import the python library pyFG required by this module')

    #define device
    f = FortiOS(module.params['host'],
                username=module.params['username'],
                password=module.params['password'],
                timeout=module.params['timeout'],
                vdom=module.params['vdom'])

    #connect
    try:
        f.open()
    except:
        module.fail_json(msg='Error connecting device')

    #get  config
    try:
        f.load_config(path=module.params['filter'])
        result['running_config'] = f.running_config.to_text()

    except:
        module.fail_json(msg='Error reading running config')

    #backup config
    if module.params['backup']:
        backup(module, f.running_config.to_text())

    #update config
    if module.params['src'] is not None:
        #store config in str
        try:
            conf_str = module.params['src']
            f.load_config(in_candidate=True, config_text=conf_str)
        except:
            module.fail_json(
                msg="Can't open configuration file, or configuration invalid")

        #get updates lines
        change_string = f.compare_config()

        #remove not updatable parts
        c = FortiConfig()
        c.parse_config_output(change_string)

        for o in NOT_UPDATABLE_CONFIG_OBJECTS:
            c.del_block(o)

        change_string = c.to_text()

        if change_string != "":
            result['change_string'] = change_string
            result['changed'] = True

        #Commit if not check mode
        if module.check_mode is False and change_string != "":
            try:
                f.commit(change_string)
            except CommandExecutionException as e:
                module.fail_json(
                    msg=
                    "Unable to execute command, check your args, the error was {0}"
                    .format(e.message))
            except FailedCommit as e:
                module.fail_json(
                    msg="Unable to commit, check your args, the error was {0}".
                    format(e.message))
            except ForcedCommit as e:
                module.fail_json(
                    msg=
                    "Failed to force commit, check your args, the error was {0}"
                    .format(e.message))

    module.exit_json(**result)
Пример #2
0
                else:
                    config_block = current_block[detail]
                current_block = config_block
                #print current_block.to_text()
                results['current_block'] = current_block.to_text()
            elif action == 'end' or action == 'next':
                current_block = current_block.get_parent()
            elif action == 'delete':
                current_block.del_block(detail)
                #print current_block.to_text()
                results['current_block'] = current_block.to_text()

    #print d.candidate_config.to_text()

    #print d.compare_config()

    diff = d.compare_config()

    if len(diff) is not 0:
        results['changed'] = True
        results['difference'] = diff

    d.commit(force=True)

    d.close()
    module.exit_json(**results)

#	except Exception:
#		print ('Error.')
#		sys.exit()
Пример #3
0
class AnsibleFortios(object):
    def __init__(self, module):
        if not HAS_PYFG:
            module.fail_json(
                msg=
                'Could not import the python library pyFG required by this module'
            )

        self.result = {
            'changed': False,
        }
        self.module = module

    def _connect(self):
        if self.module.params['file_mode']:
            self.forti_device = FortiOS('')
        else:
            host = self.module.params['host']
            username = self.module.params['username']
            password = self.module.params['password']
            timeout = self.module.params['timeout']
            vdom = self.module.params['vdom']

            self.forti_device = FortiOS(host,
                                        username=username,
                                        password=password,
                                        timeout=timeout,
                                        vdom=vdom)

            try:
                self.forti_device.open()
            except Exception as e:
                self.module.fail_json(msg='Error connecting device. %s' %
                                      to_text(e),
                                      exception=traceback.format_exc())

    def load_config(self, path):
        self.path = path
        self._connect()
        # load in file_mode
        if self.module.params['file_mode']:
            try:
                f = open(self.module.params['config_file'], 'r')
                running = f.read()
                f.close()
            except IOError as e:
                self.module.fail_json(
                    msg='Error reading configuration file. %s' % to_text(e),
                    exception=traceback.format_exc())
            self.forti_device.load_config(config_text=running, path=path)

        else:
            # get  config
            try:
                self.forti_device.load_config(path=path)
            except Exception as e:
                self.forti_device.close()
                self.module.fail_json(msg='Error reading running config. %s' %
                                      to_text(e),
                                      exception=traceback.format_exc())

        # set configs in object
        self.result[
            'running_config'] = self.forti_device.running_config.to_text()
        self.candidate_config = self.forti_device.candidate_config

        # backup if needed
        if self.module.params['backup']:
            backup(self.module, self.forti_device.running_config.to_text())

    def apply_changes(self):
        change_string = self.forti_device.compare_config()
        if change_string:
            self.result['change_string'] = change_string
            self.result['changed'] = True

        # Commit if not check mode
        if change_string and not self.module.check_mode:
            if self.module.params['file_mode']:
                try:
                    f = open(self.module.params['config_file'], 'w')
                    f.write(self.candidate_config.to_text())
                    f.close()
                except IOError as e:
                    self.module.fail_json(
                        msg='Error writing configuration file. %s' %
                        to_text(e),
                        exception=traceback.format_exc())
            else:
                try:
                    self.forti_device.commit()
                except FailedCommit as e:
                    # Something's wrong (rollback is automatic)
                    self.forti_device.close()
                    error_list = self.get_error_infos(e)
                    self.module.fail_json(
                        msg_error_list=error_list,
                        msg=
                        "Unable to commit change, check your args, the error was %s"
                        % e.message)

                self.forti_device.close()
        self.module.exit_json(**self.result)

    def del_block(self, block_id):
        self.forti_device.candidate_config[self.path].del_block(block_id)

    def add_block(self, block_id, block):
        self.forti_device.candidate_config[self.path][block_id] = block

    def get_error_infos(self, cli_errors):
        error_list = []
        for errors in cli_errors.args:
            for error in errors:
                error_code = error[0]
                error_string = error[1]
                error_type = fortios_error_codes.get(error_code, "unknown")
                error_list.append(
                    dict(error_code=error_code,
                         error_type=error_type,
                         error_string=error_string))

        return error_list

    def get_empty_configuration_block(self, block_name, block_type):
        return FortiConfig(block_name, block_type)
Пример #4
0
from pyFG import FortiOS, FortiConfig
import sys

if __name__ == '__main__':
    hostname = sys.argv[1]

    d = FortiOS(hostname, vdom='vpn')
    d.open()
    d.load_config('router bgp')

    new_neigh = FortiConfig('10.6.6.8', 'edit')
    new_neigh.set_param('remote-as', '123')
    new_neigh.set_param('remotas', '123')
    d.candidate_config['router bgp']['neighbor'].set_block(new_neigh)
    d.candidate_config['router bgp']['neighbor']['10.6.6.6'].set_param(
        'remote-as', '444')
    d.candidate_config['router bgp']['neighbor'].del_block('10.6.6.7')

    print "This is the diff of the configs:"
    for line in d.compare_config(text=True):
        print line

    print "This is how to reach the desired state:"
    config_changes = d.compare_config()
    print config_changes

    print "Result of applying the changes:"
    print d.commit(config_changes)

    d.close()
Пример #5
0
# Gets router bgp config from the device, then do some changes to the BGP parameters, deletes a neighbor,
# creates a new one, modifies another and computes the difference

from pyFG import FortiOS, FortiConfig

if __name__ == '__main__':
    f = open('running.conf', 'r')
    running = f.read()
    f.close()

    d = FortiOS('')
    d.load_config(config_text=running)

    d.candidate_config['router bgp'].set_param('as', 123)
    d.candidate_config['router bgp']['neighbor']['10.240.4.3'].set_param('bfd', 'disable')
    d.candidate_config['router bgp']['neighbor'].del_block('10.240.4.24')

    new_neigh = FortiConfig('10.6.6.6', 'edit')
    new_neigh.set_param('as', '666')
    new_neigh.set_param('route-map-out', 'my_route_map')
    new_neigh.set_param('update-source', 'port6')
    new_neigh.set_param('bfd', 'enable')
    d.candidate_config['router bgp']['neighbor'].set_block(new_neigh)

    print "This is the diff of the conigs:"
    for line in d.compare_config(text=True):
        print line

    print "\n\n"
    print "This is how to reach the desired state:"
    print d.compare_config()
Пример #6
0
def main():
    argument_spec = dict(
        src=dict(type='str', default=None),
        filter=dict(type='str', default=""),
    )

    argument_spec.update(fortios_argument_spec)

    required_if = fortios_required_if

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

    result = dict(changed=False)

    # fail if pyFG not present
    if not HAS_PYFG:
        module.fail_json(msg='Could not import the python library pyFG required by this module')

    # define device
    f = FortiOS(module.params['host'],
                username=module.params['username'],
                password=module.params['password'],
                timeout=module.params['timeout'],
                vdom=module.params['vdom'])

    # connect
    try:
        f.open()
    except:
        module.fail_json(msg='Error connecting device')

    # get  config
    try:
        f.load_config(path=module.params['filter'])
        result['running_config'] = f.running_config.to_text()

    except:
        module.fail_json(msg='Error reading running config')

    # backup config
    if module.params['backup']:
        backup(module, f.running_config.to_text())

    # update config
    if module.params['src'] is not None:
        # store config in str
        try:
            conf_str = module.params['src']
            f.load_config(in_candidate=True, config_text=conf_str)
        except:
            module.fail_json(msg="Can't open configuration file, or configuration invalid")

        # get updates lines
        change_string = f.compare_config()

        # remove not updatable parts
        c = FortiConfig()
        c.parse_config_output(change_string)

        for o in NOT_UPDATABLE_CONFIG_OBJECTS:
            c.del_block(o)

        change_string = c.to_text()

        if change_string != "":
            result['change_string'] = change_string
            result['changed'] = True

        # Commit if not check mode
        if module.check_mode is False and change_string != "":
            try:
                f.commit(change_string)
            except CommandExecutionException as e:
                module.fail_json(msg="Unable to execute command, check your args, the error was {0}".format(e.message))
            except FailedCommit as e:
                module.fail_json(msg="Unable to commit, check your args, the error was {0}".format(e.message))
            except ForcedCommit as e:
                module.fail_json(msg="Failed to force commit, check your args, the error was {0}".format(e.message))

    module.exit_json(**result)
Пример #7
0
# creates a new one, modifies another and computes the difference

from pyFG import FortiOS, FortiConfig

if __name__ == '__main__':
    f = open('running.conf', 'r')
    running = f.read()
    f.close()

    d = FortiOS('')
    d.load_config(config_text=running)

    d.candidate_config['router bgp'].set_param('as', 123)
    d.candidate_config['router bgp']['neighbor']['10.240.4.3'].set_param(
        'bfd', 'disable')
    d.candidate_config['router bgp']['neighbor'].del_block('10.240.4.24')

    new_neigh = FortiConfig('10.6.6.6', 'edit')
    new_neigh.set_param('as', '666')
    new_neigh.set_param('route-map-out', 'my_route_map')
    new_neigh.set_param('update-source', 'port6')
    new_neigh.set_param('bfd', 'enable')
    d.candidate_config['router bgp']['neighbor'].set_block(new_neigh)

    print "This is the diff of the conigs:"
    for line in d.compare_config(text=True):
        print line

    print "\n\n"
    print "This is how to reach the desired state:"
    print d.compare_config()
Пример #8
0
from pyFG import FortiOS, FortiConfig
import sys

if __name__ == '__main__':
    hostname = sys.argv[1]

    d = FortiOS(hostname, vdom='vpn')
    d.open()
    d.load_config('router bgp')

    new_neigh = FortiConfig('10.6.6.8', 'edit')
    new_neigh.set_param('remote-as', '123')
    new_neigh.set_param('remotas', '123')
    d.candidate_config['router bgp']['neighbor'].set_block(new_neigh)
    d.candidate_config['router bgp']['neighbor']['10.6.6.6'].set_param('remote-as', '444')
    d.candidate_config['router bgp']['neighbor'].del_block('10.6.6.7')


    print "This is the diff of the configs:"
    for line in d.compare_config(text=True):
        print line

    print "This is how to reach the desired state:"
    config_changes = d.compare_config()
    print config_changes

    print "Result of applying the changes:"
    print d.commit(config_changes)

    d.close()