Python ansible.errors.AnsibleParserError() Examples

The following are 21 code examples of ansible.errors.AnsibleParserError(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module ansible.errors , or try the search function .
Example #1
Source File: aos_switch_filters.py    From aruba-switch-ansible with Apache License 2.0 6 votes vote down vote up
def find_version(serach_string, version):
    """
    Return the current SWI Version of the selected Image
    :param serach_string: string that shall be looked through
    :param version: string for one of the following (primary,secondary,primary_boot,secondary_boot)
    :return: SWI Version as string
    """
    regex = u"(?:WC|YA|YC|KB|WB|K|KB)\.[0-9]{2}\.[0-9]{2}\.[0-9]{4}"
    matches = re.findall(regex, serach_string)
    if version == "primary":
        return matches[0]
    elif version == "secondary":
        return matches[1]
    elif version == "primary_boot":
        return matches[2]
    elif version == "secondary_boot":
        return matches[3]
    else:
        raise AnsibleParserError(
            'No correct version selector entered. Choose one of the following:'
            ' primary,secondary,primary_boot,secondary_boot. You entered: %s .' % to_text(version)) 
Example #2
Source File: runner.py    From contrail-docker with Apache License 2.0 6 votes vote down vote up
def run(self, verbose=False):
        if not verbose:
            # Results of PlaybookExecutor
            cb = DisplayErrorCallback()
            self.pbex._tqm._stdout_callback = cb
        try:
            res = self.pbex.run()
        except AnsibleParserError as err:
            print(err)
            return None
        stats = self.pbex._tqm._stats

        # Test if success for record_logs
        run_success = True
        hosts = sorted(stats.processed.keys())
        for h in hosts:
            t = stats.summarize(h)
            if t['unreachable'] > 0 or t['failures'] > 0:
                run_success = False

        return stats 
Example #3
Source File: gcp_compute.py    From google.cloud with GNU General Public License v3.0 6 votes vote down vote up
def hostname(self):
        """
            :return the hostname of this instance
        """
        for order in self.hostname_ordering:
            name = None
            if order == "public_ip":
                name = self._get_publicip()
            elif order == "private_ip":
                name = self._get_privateip()
            elif order == "name":
                name = self.json[u"name"]
            else:
                raise AnsibleParserError("%s is not a valid hostname precedent" % order)

            if name:
                return name

        raise AnsibleParserError("No valid name found for host") 
Example #4
Source File: myinventory.py    From codo-cmdb with GNU General Public License v3.0 6 votes vote down vote up
def parse_source(self, source):
        parsed = False

        if not self._inventory_plugins:
            self._setup_inventory_plugins()

        for plugin in self._inventory_plugins:
            if plugin.verify_file(source):
                try:
                    plugin.parse(self._inventory, self._loader, source)
                    parsed = True
                    break
                except:
                    pass
        else:
            raise AnsibleParserError("No plugin could parse your data.")

        return parsed 
Example #5
Source File: csv.py    From commcare-cloud with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def _get_host_vars(self, row, hosts_aliases):
        vars = {}
        for key, raw_val in row.items():
            raw_val = raw_val.strip()
            if 'var' in key and raw_val:
                item_type, name = key.split('.') if '.' in key else ('S', key)
                parts = re.split(r'var:\s*', name)
                if len(parts) != 2:
                    raise AnsibleParserError('Unable to parse varible name: "{}"'.format(name))
                name = parts[1]
                vars[name] = conv_str2value(item_type, raw_val, hosts_aliases)
        if 'hostname' not in vars:
            vars['hostname'] = row['hostname']
        else:
            vars['alt_hostname'] = row['hostname']
        return vars 
Example #6
Source File: csv.py    From commcare-cloud with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def parse(self, inventory, loader, path, cache=False):
        super(InventoryModule, self).parse(inventory, loader, path)

        try:
            if self.loader:
                (b_data, private) = self.loader._get_file_contents(path)
            else:
                b_path = to_bytes(path, errors='surrogate_or_strict')
                with open(b_path, 'rb') as fh:
                    b_data = fh.read()

            # Faster to do to_text once on a long string than many
            # times on smaller strings
            data = to_text(b_data, errors='surrogate_or_strict').splitlines()

            self._parse(data)
        except Exception as e:
            raise AnsibleParserError(e) 
Example #7
Source File: ztp_vars.py    From aruba-switch-ansible with Apache License 2.0 6 votes vote down vote up
def login(self, username, password):
        """
        Function handles login for REST API of the Switch
        :param username: The switch account username for authentication
        :param password: The switch account password authentication
        :return: Session object
        """
        # Create Session Object
        session = requests.Session()
        # Authenticate Session Object
        response = session.post(self.base_url + "login",
                                params={"username": username, "password": password}, verify=False,
                                timeout=2)
        if response.status_code != 200:
            raise AnsibleParserError('Login Request Failed with Status Code %s .' % to_text(str(response.status_code)))
        else:
            return session 
Example #8
Source File: common_filters.py    From aruba-switch-ansible with Apache License 2.0 6 votes vote down vote up
def json_type_converter(current_dict, typelist):
    """
    This filter fill allow you to build JSON Bodies with Data types of booleans and integers.
    If you enter values which are not in the dict, nothing will happen. This allows you to use this function even for dynamic bodies.
    :param current_dict: the current dict in which strings are that shall be booleans or integers
    :param typelist: a list of list where by each list has a dict key at index 0 and either "int" or "boolean" at index 1.
    :return: current_dict with correct types, best directly transfered into module
    """
    for tuple in typelist:
        if tuple[0] in current_dict:
            type = tuple[1]
            if type == "boolean":
                current_dict[tuple[0]] = bool(current_dict[tuple[0]])
            elif type == "int":
                current_dict[tuple[0]] = int(current_dict[tuple[0]])
            else:
                raise AnsibleParserError(
                    'You entered the not valid type %s for the key %s . Only "int" or "boolean" is allowed.' % (to_text(type),to_text(type[0])))

    return current_dict 
Example #9
Source File: Example4.LookUpPlugin.py    From Implementing-DevOps-with-Ansible-2 with MIT License 6 votes vote down vote up
def run(self, terms, variables=None, **kwargs):

        ret = []
        # Perform iteration
        for term in terms:

            display.debug("File lookup term: %s" % term)

            # Find the file in the expected search path
            lookupfile = self.find_file_in_search_path(variables, 'files', term)
            display.vvvv(u"File lookup using %s as file" % lookupfile)
            try:
                if lookupfile:
                    contents, show_data = self._loader._get_file_contents(lookupfile)
                    ret.append(contents.rstrip())
                else:
                    raise AnsibleParserError()

            except AnsibleParserError:
                raise AnsibleError("could not locate file in lookup: %s" % term) 
Example #10
Source File: ztp_vars.py    From aruba-switch-ansible with Apache License 2.0 5 votes vote down vote up
def get_lag(self, data):
        """
        Get LAG information for each interface
        :param data: data object with filtered data
        :return: data object with additional information
        """
        response = self.session.get(self.base_url + "system/ports/*?attributes=interfaces,name", verify=False,
                                    timeout=2)
        if response.status_code != 200:
            raise AnsibleParserError(
                'Port Get Request Failed with Status Code %s .' % to_text(str(response.status_code)))
        if not response.json():
            raise AnsibleParserError('Port Request returns Empty Object. This means no LAG is configured')

        # reformat response
        lag_dict = {}
        for port in response.json():
            if "lag" in port['name']:
                for intf in port['interfaces']:
                    lag_dict[intf] = port['name']

        if not lag_dict:
            raise AnsibleParserError('No Lag configured on Switch')

        # Match Lag to data_set
        for data_set in data:
            if data_set['interface'] in lag_dict:
                data_set['lag'] = lag_dict[data_set['interface']]
            else:
                raise AnsibleParserError('No Lag configured for interface %s' % to_text(data_set['interface']))

        return data 
Example #11
Source File: ztp_vars.py    From aruba-switch-ansible with Apache License 2.0 5 votes vote down vote up
def logout(self):
        """
        Session will be closed
        :return: True/False
        """
        session = self.session
        response = session.post(self.base_url + "logout", verify=False)
        if response.status_code != 200:
            raise AnsibleParserError('Logout Request Failed with Status Code %s .' % to_text(str(response.status_code))) 
Example #12
Source File: csv.py    From commcare-cloud with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def conv_str2value(item_type, item, hosts_aliases=None):
    """
    Convert a character string to a specified data type.

    :param string item_type: A character string representing the type of item data.
    :param string item: Value of item data.
    :return: The converted value.
    """

    if len(item) <= 0:
        return None

    if TYPE_STRING == item_type:
        return item
    elif TYPE_INTEGER == item_type:
        return int(item)
    elif TYPE_BOOLEAN == item_type:
        item = item.lower()
        return item in ('true', 't')
    elif TYPE_FLOAT == item_type:
        return float(item)
    elif TYPE_LIST == item_type:
        return json.loads(item)
    elif TYPE_HOST == item_type:
        if hosts_aliases is None:
            raise AnsibleParserError("Var of type host not supported: {}".format(item))
        return hosts_aliases.get(item, item)

    return item 
Example #13
Source File: my_inventory.py    From Ansible-inventory-file-examples with MIT License 5 votes vote down vote up
def parse(self, inventory, loader, path, cache=None):
        super(InventoryModule, self).parse(inventory, loader, path)

        config_data = loader.load_from_file(path, cache=cache)
        cache_key = self.get_cache_key(path)
        populate_cache = False
        results = {}
        if cache:
            cache = self.get_option('cache')
            if cache:
                try:
                    results = self._cache[cache_key]
                except KeyError:
                    populate_cache = True

        if not config_data.get('hostname'):
            raise AnsibleParserError("hostname was not specified")

        if not results:
            results['host'] = config_data.get('hostname')
            results['variables'] = {'foo': 'bar'}

        self.inventory.add_host(results['host'], 'all')
        for k, v in results['variables'].items():
            self.inventory.set_variable(results['host'], k, v)

        if cache and populate_cache:
            self._cache[cache_key] = results 
Example #14
Source File: ztp_filter.py    From aruba-switch-ansible with Apache License 2.0 5 votes vote down vote up
def fetch_allowed_list(path, ip):
    """
    Fetches all allowed attributes for a certain api path
    :param path: Swagger URI to resource
    :param ip: IP of the AOS-CX Switch
    :return: list of strings that represent attributes of the resource
    """
    # Get API Object
    response = get("https://{}/api/hpe-restapi.json".format(ip), verify=False)
    if response.status_code != 200:
        raise AnsibleParserError(
            'Get API Object Request Failed with Status Code %s .' % to_text(str(response.status_code)))

    # Var Dec
    tmp_object = response.json()['paths']
    allowed_list = []

    # Get all properties of the path
    if path in tmp_object:
        if "put" in tmp_object[path]:
            for parameter in tmp_object[path]['put']['parameters']:
                if parameter['name'] != "data":
                    continue
                else:
                    allowed_list = list(parameter['schema']['properties'].keys())
        else:
            raise AnsibleParserError('No Put Method exists for the path %s .' % to_text(str(path)))
    else:
        raise AnsibleParserError('No API Object exists for the path %s .' % to_text(str(path)))

    return allowed_list 
Example #15
Source File: myinventory.py    From codo-cmdb with GNU General Public License v3.0 5 votes vote down vote up
def parse(self, inventory, loader, host_string, cache=None):
        super(InventoryStringPlugin, self).parse(inventory, loader, host_string)
        try:
            if "," in host_string:
                host_string = [h.strip() for h in host_string.split(',') if h and h.strip()]
            else:
                host_string = [ host_string]

            for h in host_string:
                if h not in self.inventory.hosts:
                    self.inventory.add_host(h, group='ungrouped', port=None)
        except Exception as e:
            raise AnsibleParserError("Invalid data from string, could not parse: %s" % to_native(e)) 
Example #16
Source File: myinventory.py    From codo-cmdb with GNU General Public License v3.0 5 votes vote down vote up
def parse(self, inventory, loader, host_list, cache=None):
        #print('11111111->',inventory, loader, host_list)
        super(InventoryListPlugin, self).parse(inventory, loader, host_list)
        try:
            for h in host_list:
                if h not in self.inventory.hosts:
                    self.inventory.add_host(h, group='ungrouped')
        except Exception as e:
            raise AnsibleParserError("Invalid data from sequnes, could not parse: %s" % to_native(e)) 
Example #17
Source File: myinventory.py    From codo-cmdb with GNU General Public License v3.0 5 votes vote down vote up
def parse(self, inventory, loader, sources, cache=None):
        # print('souce---->',sources)
        super(InventoryDictPlugin, self).parse(inventory, loader, sources)
        try:
            self.inventory.add_host(host=sources.get('host'), group='ungrouped', port=sources.get('port'))
        except Exception as e:
            raise AnsibleParserError("Invalid data from sequnes, could not parse: %s" % to_native(e))

        # 下面这块有时间修改,应该是支持dict传入多主机的,目前先以self.inventory.add_host处理
        # data_from_meta = {}
        #
        # try:
        #     for group, gdata in sources.iteritems():
        #         if group == "_meta":
        #             if "hostvars" in gdata:
        #                 data_from_meta = gdata['hostvars']
        #         else:
        #             self._parse_group(group, gdata)
        #
        #     for host in self._hosts:
        #         got = {}
        #         if data_from_meta:
        #             got = data_from_meta.get(host, {})
        #
        #         self._set_host_vars([host], got)
        #
        # except Exception as e:
        #     raise AnsibleParserError(to_native(e)) 
Example #18
Source File: execute.py    From infrared with Apache License 2.0 5 votes vote down vote up
def _run_playbook(cli_args, vars_dict):
    """Runs ansible cli with vars dict

    :param vars_dict: dict, Will be passed as Ansible extra-vars
    :param cli_args: the list  of command line arguments
    :return: ansible results
    """

    # TODO(yfried): use ansible vars object instead of tmpfile
    # NOTE(oanufrii): !!!this import should be exactly here!!!
    #                 Ansible uses 'display' singleton from '__main__' and
    #                 gets it on module level. While we monkeypatching our
    #                 '__main__' in 'ansible_playbook' function import of
    #                 PlaybookCLI shoul be after that, to get patched
    #                 '__main__'. Otherwise ansible gets unpatched '__main__'
    #                 and creates new 'display' object with default (0)
    #                 verbosity.
    from ansible.cli.playbook import PlaybookCLI
    from ansible.errors import AnsibleOptionsError
    from ansible.errors import AnsibleParserError
    with tempfile.NamedTemporaryFile(
            mode='w+', prefix="ir-settings-", delete=True) as tmp:
        tmp.write(yaml.safe_dump(vars_dict, default_flow_style=False))
        # make sure created file is readable.
        tmp.flush()
        cli_args.extend(['--extra-vars', "@" + tmp.name])
        cli = PlaybookCLI(cli_args)
        LOG.debug('Starting ansible cli with args: {}'.format(cli_args[1:]))
        try:
            cli.parse()
            # Return the result:
            # 0: Success
            # 1: "Error"
            # 2: Host failed
            # 3: Unreachable
            # 4: Parser Error
            # 5: Options error
            return cli.run()
        except (AnsibleParserError, AnsibleOptionsError) as error:
            LOG.error('{}: {}'.format(type(error), error))
            raise error 
Example #19
Source File: csvtojson.py    From infra-ansible with Apache License 2.0 4 votes vote down vote up
def run(self, terms, variables=None, **kwargs):

        ret = []

        cwd = os.getcwd()

        for term in terms:

            params = term.split()

            paramvals = {
                'file' : 'users.csv',
                'var' : 'users'
            }

            # parameters specified?
            try:
                for param in params:
                    name, value = param.split('=')
                    assert(name in paramvals)
                    paramvals[name] = value
                    display.vvvv(u"Param: %s : %s" % (name, value))
            except (ValueError, AssertionError) as e:
                raise AnsibleError(e)

            if os.path.isabs(paramvals['file']):
              lookupfile = paramvals['file']
            else:
              lookupfile = cwd + '/' + paramvals['file']

            display.vvvv(u"File lookup using %s as file" % paramvals['file'])
            try:
                if lookupfile:
                    #read csv into rows
                    with open(lookupfile) as f:
                        reader = csv.DictReader(f)
                        rows = list(reader)

                    # do output for users or groups
                    if(paramvals['var'] == 'user_groups'):
                        ret.append(self.get_user_groups(rows))
                    else:
                        ret.append(self.get_users(rows))

                else:
                    raise AnsibleParserError()
            except AnsibleParserError:
                raise AnsibleError("could not locate file in lookup: %s" % paramvals['file'])

        return ret

    # get json for users - file should already support this format 
Example #20
Source File: csvtojson.py    From infra-ansible with Apache License 2.0 4 votes vote down vote up
def run(self, terms, variables=None, **kwargs):

        ret = []

        cwd = os.getcwd()

        for term in terms:

            params = term.split()

            paramvals = {
                'file' : 'users.csv',
                'var' : 'users'
            }

            # parameters specified?
            try:
                for param in params:
                    name, value = param.split('=')
                    assert(name in paramvals)
                    paramvals[name] = value
                    display.vvvv(u"Param: %s : %s" % (name, value))
            except (ValueError, AssertionError) as e:
                raise AnsibleError(e)

            if os.path.isabs(paramvals['file']):
              lookupfile = paramvals['file']
            else:
              lookupfile = cwd + '/' + paramvals['file']

            display.vvvv(u"File lookup using %s as file" % paramvals['file'])
            try:
                if lookupfile:
                    #read csv into rows
                    with open(lookupfile) as f:
                        reader = csv.DictReader(f)
                        rows = list(reader)

                    # do output for users or groups
                    if(paramvals['var'] == 'user_groups'):
                        ret.append(self.get_user_groups(rows))
                    else:
                        ret.append(self.get_users(rows))

                else:
                    raise AnsibleParserError()
            except AnsibleParserError:
                raise AnsibleError("could not locate file in lookup: %s" % paramvals['file'])

        return ret

    # get json for users - file should already support this format 
Example #21
Source File: csvtojson.py    From infra-ansible with Apache License 2.0 4 votes vote down vote up
def run(self, terms, variables=None, **kwargs):

        ret = []

        cwd = os.getcwd()

        for term in terms:

            params = term.split()

            paramvals = {
                'file' : 'users.csv',
                'var' : 'users'
            }

            # parameters specified?
            try:
                for param in params:
                    name, value = param.split('=')
                    assert(name in paramvals)
                    paramvals[name] = value
                    display.vvvv(u"Param: %s : %s" % (name, value))
            except (ValueError, AssertionError) as e:
                raise AnsibleError(e)

            if os.path.isabs(paramvals['file']):
              lookupfile = paramvals['file']
            else:
              lookupfile = cwd + '/' + paramvals['file']

            display.vvvv(u"File lookup using %s as file" % paramvals['file'])
            try:
                if lookupfile:
                    #read csv into rows
                    with open(lookupfile) as f:
                        reader = csv.DictReader(f)
                        rows = list(reader)

                    # do output for users or groups
                    if(paramvals['var'] == 'user_groups'):
                        ret.append(self.get_user_groups(rows))
                    else:
                        ret.append(self.get_users(rows))

                else:
                    raise AnsibleParserError()
            except AnsibleParserError:
                raise AnsibleError("could not locate file in lookup: %s" % paramvals['file'])

        return ret

    # get json for users - file should already support this format