How to use the ansible.errors.AnsibleFilterError function in ansible

To help you get started, we’ve selected a few ansible examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github Azure / sonic-mgmt / ansible / plugins / filter / filters.py View on Github external
def extract_hostname(values, topology, vm_base, inventory_hostname):
    """
    This function takes a list of host VMs as parameter 'values' and then return 'inventory_hostname'
    corresponding EOS hostname based on 'topology' structure, 'vm_base' parameters
    """
    if values is None:
      raise errors.AnsibleFilterError('Values is not provided')

    if topology is None:
      raise errors.AnsibleFilterError('topology is not provided')

    if vm_base is None:
      raise errors.AnsibleFilterError('vm_base is not provided')

    if inventory_hostname is None:
      raise errors.AnsibleFilterError('inventory_hostname is not provided')

    if not isinstance(values, list):
      raise errors.AnsibleFilterError('Wrong type for values')

    if not isinstance(topology, dict):
      raise errors.AnsibleFilterError('Wrong type for the topology')

    if not isinstance(vm_base, str) and not isinstance(vm_base, unicode):
      raise errors.AnsibleFilterError('Wrong type for the vm_base')

    if not isinstance(inventory_hostname, str) and not isinstance(inventory_hostname, unicode):
      raise errors.AnsibleFilterError('Wrong type for the inventor_hostname')
github openshift / openshift-tools / openshift / installer / vendored / openshift-ansible-3.3.46 / filter_plugins / oo_filters.py View on Github external
{'a':3, 'z': 'z'},        # True, return
                         {'a':4, 'z': 'b'},        # FAILED, obj['z'] != obj['z']
                       ]
                attribute = 'a'
                filters   = {'z': 'z'}
                returns [1, 2, 3]
        """
        if not isinstance(data, list):
            raise errors.AnsibleFilterError("|failed expects to filter on a List")

        if not attribute:
            raise errors.AnsibleFilterError("|failed expects attribute to be set")

        if filters is not None:
            if not isinstance(filters, dict):
                raise errors.AnsibleFilterError("|failed expects filter to be a"
                                                " dict")
            retval = [FilterModule.get_attr(d, attribute) for d in data if (
                all([d.get(key, None) == filters[key] for key in filters]))]
        else:
            retval = [FilterModule.get_attr(d, attribute) for d in data]

        retval = [val for val in retval if val != None]

        return retval
github openshift / openshift-tools / openshift / installer / vendored / openshift-ansible-3.5.28 / roles / openshift_master_facts / filter_plugins / openshift_master.py View on Github external
def translate_idps(idps, api_version, openshift_version, deployment_type):
        ''' Translates a list of dictionaries into a valid identityProviders config '''
        idp_list = []

        if not isinstance(idps, list):
            raise errors.AnsibleFilterError("|failed expects to filter on a list of identity providers")
        for idp in idps:
            if not isinstance(idp, dict):
                raise errors.AnsibleFilterError("|failed identity providers must be a list of dictionaries")

            cur_module = sys.modules[__name__]
            idp_class = getattr(cur_module, idp['kind'], None)
            idp_inst = idp_class(api_version, idp) if idp_class is not None else IdentityProviderBase(api_version, idp)
            idp_inst.set_provider_items()
            idp_list.append(idp_inst)

        IdentityProviderBase.validate_idp_list(idp_list, openshift_version, deployment_type)
        return yaml.dump([idp.to_dict() for idp in idp_list],
                         allow_unicode=True,
                         default_flow_style=False,
                         Dumper=AnsibleDumper)
github ansible / ansible / lib / ansible / plugins / filter / core.py View on Github external
def mandatory(a):
    from jinja2.runtime import Undefined

    ''' Make a variable mandatory '''
    if isinstance(a, Undefined):
        raise AnsibleFilterError('Mandatory variable not defined.')
    return a
github openshift / openshift-tools / openshift / installer / vendored / openshift-ansible-3.11.28-1 / roles / lib_utils / filter_plugins / oo_filters.py View on Github external
returns [{ "certfile": "/etc/origin/master/named_certificates/custom1.crt",
                       "keyfile": "/etc/origin/master/named_certificates/custom1.key",
                       "cafile": "/etc/origin/master/named_certificates/custom-ca1.crt",
                       "names": [ "public-master-host.com",
                                  "other-master-host.com" ] },
                     { "certfile": "/etc/origin/master/named_certificates/custom2.crt",
                       "keyfile": "/etc/origin/master/named_certificates/custom2.key",
                       "cafile": "/etc/origin/master/named_certificates/custom-ca-2.crt",
                       "names": [ "some-hostname.com" ] }]
    """
    if not isinstance(named_certs_dir, string_types):
        raise errors.AnsibleFilterError("|failed expects named_certs_dir is str or unicode")

    if not isinstance(internal_hostnames, list):
        raise errors.AnsibleFilterError("|failed expects internal_hostnames is list")

    if not HAS_OPENSSL:
        raise errors.AnsibleFilterError("|missing OpenSSL python bindings")

    for certificate in certificates:
        if 'names' in certificate.keys():
            continue
        else:
            certificate['names'] = []

        if not os.path.isfile(certificate['certfile']) or not os.path.isfile(certificate['keyfile']):
            raise errors.AnsibleFilterError("|certificate and/or key does not exist '%s', '%s'" %
                                            (certificate['certfile'], certificate['keyfile']))

        try:
            st_cert = open(certificate['certfile'], 'rt').read()
github openshift / openshift-tools / openshift / installer / vendored / openshift-ansible-3.6.65 / filter_plugins / oo_filters.py View on Github external
""" filter function for testing if node should be returned """
        if not isinstance(node, dict):
            raise errors.AnsibleFilterError("failed expects to filter on a list of dicts")
        if 'openshift_node_labels' in node:
            labels = node['openshift_node_labels']
        elif 'cli_openshift_node_labels' in node:
            labels = node['cli_openshift_node_labels']
        elif 'openshift' in node and 'node' in node['openshift'] and 'labels' in node['openshift']['node']:
            labels = node['openshift']['node']['labels']
        else:
            return False

        if isinstance(labels, string_types):
            labels = yaml.safe_load(labels)
        if not isinstance(labels, dict):
            raise errors.AnsibleFilterError(
                "failed expected node labels to be a dict or serializable to a dict"
            )
        return label in labels and (value is None or labels[label] == value)
github ceph / ceph-ansible / plugins / filter / ipaddrs_in_ranges.py View on Github external
def filters(self):
        if netaddr:
            return {
                'ips_in_ranges': self.ips_in_ranges
            }
        else:
            # Need to install python's netaddr for these filters to work
            raise errors.AnsibleFilterError(
                "The ips_in_ranges filter requires python's netaddr be "
                "installed on the ansible controller.")
github linuxdynasty / ld-ansible-filter-plugins / aws.py View on Github external
"Name": "tag-value",
                "Values": [name]
            },
            {
                "Name": "vpc-id",
                "Values": [vpc_id],
            }
        ]
    }
    try:
        sg_groups = client.describe_security_groups(**params)['SecurityGroups']
        if len(sg_groups) == 1:
            cidrs = map(lambda x: x['CidrIp'], sg_groups[0]['IpPermissions'][0]['IpRanges'])
            return cidrs
        elif len(sg_groups) > 1:
            raise errors.AnsibleFilterError(
                "Too many results for {0}: {1}".format(
                    name, ",".join(sg_groups)
                )
            )
        else:
            raise errors.AnsibleFilterError(
                "Security Group {0} was not found".format(name)
            )
    except botocore.exceptions.ClientError as e:
        raise e
github ansible / ansible / lib / ansible / plugins / filter / mathstuff.py View on Github external
c = set(c)
            else:
                c = list(c)
    except TypeError as e:
        error = e
        _do_fail(e)
    except Exception as e:
        error = e
        _do_fail(e)
        display.warning('Falling back to Ansible unique filter as Jinja2 one failed: %s' % to_text(e))

    if not HAS_UNIQUE or error:

        # handle Jinja2 specific attributes when using Ansible's version
        if case_sensitive or attribute:
            raise AnsibleFilterError("Ansible's unique filter does not support case_sensitive nor attribute parameters, "
                                     "you need a newer version of Jinja2 that provides their version of the filter.")

        if isinstance(a, Hashable):
            c = set(a)
        else:
            c = []
            for x in a:
                if x not in c:
                    c.append(x)
    return c
github openshift / openshift-tools / openshift / installer / vendored / openshift-ansible-3.6.65 / filter_plugins / oo_filters.py View on Github external
{'a':2, 'b':6, 'z': 'z'}  # True, return
                          ],
                          [ {'a':3, 'z': 'z'},        # True, return
                            {'a':4, 'z': 'b'}         # FAILED, obj['z'] != obj['z']
                          ],
                          {'a':5, 'z': 'z'},          # True, return
                        ]
            attribute = 'a'
            filters   = {'z': 'z'}
            returns [1, 2, 3, 5]
    """
    if not isinstance(data_list, list):
        raise errors.AnsibleFilterError("oo_collect expects to filter on a List")

    if not attribute:
        raise errors.AnsibleFilterError("oo_collect expects attribute to be set")

    data = []
    retval = []

    for item in data_list:
        if isinstance(item, list):
            retval.extend(oo_collect(item, attribute, filters))
        else:
            data.append(item)

    if filters is not None:
        if not isinstance(filters, dict):
            raise errors.AnsibleFilterError(
                "oo_collect expects filter to be a dict")
        retval.extend([get_attr(d, attribute) for d in data if (
            all([d.get(key, None) == filters[key] for key in filters]))])