Python ansible.errors.AnsibleError() Examples

The following are 30 code examples of ansible.errors.AnsibleError(). 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: vault.py    From ansible-vault with BSD 3-Clause "New" or "Revised" License 7 votes vote down vote up
def _fetch_secret(self, cafile, capath, data, key, vault_token, url, cahostverify, skipverify):
        try:
            context = None
            if cafile or capath:
                context = ssl.create_default_context(cafile=cafile, capath=capath)
                context.check_hostname = cahostverify
            elif skipverify:
                context = ssl._create_unverified_context()
            request_url = urljoin(url, "v1/%s" % (key))
            data = data.encode('utf-8') if data else None
            req = urllib2.Request(request_url, data)
            req.add_header('X-Vault-Token', vault_token)
            req.add_header('Content-Type', 'application/json')
            response = urllib2.urlopen(req, context=context) if context else urllib2.urlopen(req)
        except Exception as ex:
            if hasattr(ex, 'code') and ex.code in [301, 302, 303, 307]:
                return self._fetch_secret(cafile, capath, data, key, vault_token, ex.headers.dict['location'],
                                          cahostverify, skipverify)
            else:
                raise AnsibleError('Unable to read %s from vault: %s' % (key, ex))
        reader = codecs.getreader("utf-8")
        body = reader(response)
        if response.headers.get('Content-Type') == 'application/json':
            body = json.load(body)
        return body 
Example #2
Source File: lchroot.py    From luna with GNU General Public License v3.0 6 votes vote down vote up
def put_file(self, in_path, out_path):
        ''' transfer a file from local to lchroot '''
        super(Connection, self).put_file(in_path, out_path)
        display.vvv("PUT %s TO %s" % (in_path, out_path), host=self.path)

        out_path = pipes.quote(self._prefix_login_path(out_path))
        try:
            with open(to_bytes(in_path, errors='surrogate_or_strict'), 'rb') as in_file:
                try:
                    p = self._buffered_exec_command('dd of=%s bs=%s' % (out_path, BUFSIZE), stdin=in_file)
                except OSError:
                    raise AnsibleError("lchroot connection requires dd command in the lchroot")
                try:
                    stdout, stderr = p.communicate()
                except:
                    traceback.print_exc()
                    raise AnsibleError("failed to transfer file %s to %s" % (in_path, out_path))
                if p.returncode != 0:
                    raise AnsibleError("failed to transfer file %s to %s:\n%s\n%s" % (in_path, out_path, stdout, stderr))
        except IOError:
            raise AnsibleError("file or module does not exist at: %s" % in_path) 
Example #3
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 #4
Source File: alicloud_ecs.py    From alibaba.alicloud with Apache License 2.0 6 votes vote down vote up
def _get_instances_by_region(self, regions, filters):
        '''
           :param regions: a list of regions in which to describe instances
           :param filters: a list of ECS filter dictionaries
           :return A list of instance dictionaries
        '''
        all_instances = []
        if not regions:
            try:
                regions = list(map(lambda x: x.id, self.connect_to_ecs(footmark.ecs, "cn-beijing").describe_regions()))
            except Exception as e:
                raise AnsibleError('Unable to get regions list from available methods, you must specify the "regions" option to continue.')

        for region in regions:
            try:
                conn = connect_to_acs(footmark.ecs, region, **self.credentials)
                insts = conn.describe_instances(**filters)
                all_instances.extend(map(lambda x: x.read(), insts))
            except Exception as e:
                raise AnsibleError("Failed to describe instances: %s" % to_native(e))
        return sorted(all_instances, key=lambda x: x['instance_id']) 
Example #5
Source File: bitwarden.py    From ansible-modules-bitwarden with GNU General Public License v3.0 6 votes vote down vote up
def _run(self, args):
        p = Popen([self.cli_path] + args, stdin=PIPE, stdout=PIPE, stderr=STDOUT)
        out, _ = p.communicate()
        out = out.decode()
        rc = p.wait()
        if rc != 0:
            display.debug("Received error when running '{0} {1}': {2}"
                          .format(self.cli_path, args, out))
            if out.startswith("Vault is locked."):
                raise AnsibleError("Error accessing Bitwarden vault. "
                                   "Run 'bw unlock' to unlock the vault.")
            elif out.startswith("You are not logged in."):
                raise AnsibleError("Error accessing Bitwarden vault. "
                                   "Run 'bw login' to login.")
            elif out.startswith("Failed to decrypt."):
                raise AnsibleError("Error accessing Bitwarden vault. "
                                   "Make sure BW_SESSION is set properly.")
            elif out.startswith("Not found."):
                raise AnsibleError("Error accessing Bitwarden vault. "
                        "Specified item not found: {}".format(args[-1]))
            else:
                raise AnsibleError("Unknown failure in 'bw' command: "
                                   "{0}".format(out))
        return out.strip() 
Example #6
Source File: pfsense.py    From ansible-pfsense with GNU General Public License v3.0 6 votes vote down vote up
def run(self, terms, variables, **kwargs):
        """ Entry point for main function (to properly catch & display exceptions stacktrace)"""
        trace = None
        res = []

        try:
            res = self._run(terms, variables, **kwargs)
        except AnsibleError:
            raise
        except AssertionError:
            raise
        except Exception:
            trace = traceback.format_exc()
        finally:
            if trace is not None:
                raise AnsibleError(trace)

        return res 
Example #7
Source File: bitwarden.py    From ansible-modules-bitwarden with GNU General Public License v3.0 6 votes vote down vote up
def run(self, terms, variables=None, **kwargs):
        bw = Bitwarden(path=kwargs.get('path', 'bw'))

        if not bw.logged_in:
            raise AnsibleError("Not logged into Bitwarden: please run "
                               "'bw login', or 'bw unlock' and set the "
                               "BW_SESSION environment variable first")

        field = kwargs.get('field', 'password')
        values = []

        if kwargs.get('sync'):
            bw.sync()

        for term in terms:
            if kwargs.get('custom_field'):
                values.append(bw.get_custom_field(term, field))
            elif field == 'notes':
                values.append(bw.get_notes(term))
            else:
                values.append(bw.get_entry(term, field))
        return values 
Example #8
Source File: pfsense.py    From ansible-pfsense with GNU General Public License v3.0 6 votes vote down vote up
def load_data(self, from_file):
        """ Load and return pfsense data """
        fvars = self.get_definitions(from_file)
        if fvars is None:
            raise AnsibleError("No usable data found in {0}".format(from_file))

        for section in ['hosts_aliases', 'ports_aliases', 'pfsenses', 'rules']:
            if section not in fvars:
                raise AnsibleError("Missing {0} section in {1}".format(section, from_file))

        data = PFSenseData(
            hosts_aliases=fvars['hosts_aliases'],
            ports_aliases=fvars['ports_aliases'],
            pfsenses=fvars['pfsenses'],
            rules=fvars['rules'],
            target_name=self.get_hostname()
        )
        return data 
Example #9
Source File: grapher.py    From ansible-playbook-grapher with MIT License 6 votes vote down vote up
def template(self, data, variables, fail_on_undefined=False):
        """
        Template the data using Jinja. Return data if an error occurs during the templating
        :param fail_on_undefined:
        :type fail_on_undefined: bool
        :param data:
        :type data: Union[str, ansible.parsing.yaml.objects.AnsibleUnicode]
        :param variables:
        :type variables: dict
        :return:
        """
        try:
            templar = Templar(loader=self.data_loader, variables=variables)
            return templar.template(data, fail_on_undefined=fail_on_undefined)
        except AnsibleError as ansible_error:
            # Sometime we need to export
            if fail_on_undefined:
                raise
            self.display.warning(ansible_error)
            return data 
Example #10
Source File: vault.py    From ansible-vault with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def _fetch_client_token(self, cafile, capath, url, data, cahostverify, skipverify):
        try:
            context = None
            if cafile or capath:
                context = ssl.create_default_context(cafile=cafile, capath=capath)
                context.check_hostname = cahostverify
            elif skipverify:
                context = ssl._create_unverified_context()
            data = data.encode('utf-8') if data else None
            req = urllib2.Request(url, json.dumps(data))
            req.add_header('Content-Type', 'application/json')
            response = urllib2.urlopen(req, context=context) if context else urllib2.urlopen(req)
        except Exception as ex:
            if hasattr(ex, 'code') and ex.code in [301, 302, 303, 307]:
                return self._fetch_client_token(cafile, capath, ex.headers.dict['location'], data, cahostverify,
                                                skipverify)
            else:
                raise AnsibleError('Unable to retrieve personal token from vault: %s' % (ex))
        reader = codecs.getreader("utf-8")
        result = json.load(reader(response))
        return result 
Example #11
Source File: os_cinder.py    From openshift-ansible-contrib with Apache License 2.0 6 votes vote down vote up
def run(self, volume_names, variables=None, **kwargs):
        cloud = shade.openstack_cloud()
        volume_attributes = [
            "id",
            "name",
            "display_name",
            "size",
            "description",
        ]

        def get_volume(name_or_id):
            volume = cloud.get_volume(name_or_id)
            if not volume:
                raise AnsibleError(
                    "Could not find volume: {}".format(name_or_id))

            result = {}
            for attribute_name in volume_attributes:
                result[attribute_name] = getattr(volume, attribute_name)
            return result

        return [get_volume(volume_name) for volume_name in volume_names] 
Example #12
Source File: runner.py    From codo-cmdb with GNU General Public License v3.0 6 votes vote down vote up
def run(self):
        if not self.inventory.list_hosts("all"):
            raise AnsibleError("Inventory is empty.")

        if not self.inventory.list_hosts(self.pattern):
            raise AnsibleError(
                "pattern: %s  dose not match any hosts." % self.pattern)

        try:
            self.runner.run(self.play)
        finally:
            if self.runner:
                self.runner.cleanup()
            if self.loader:
                self.loader.cleanup_all_tmp_files()

        return self.resultcallback.result_q 
Example #13
Source File: vault.py    From ansible-vault with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def _verify_python_version(self, key, cafile, capath, cahostverify):
        python_version_cur = ".".join([str(version_info.major),
                                       str(version_info.minor),
                                       str(version_info.micro)])
        python_version_min = "2.7.9"
        if StrictVersion(python_version_cur) < StrictVersion(python_version_min):
            if cafile or capath:
                raise AnsibleError('Unable to read %s from vault:'
                                   ' Using Python %s, and vault lookup plugin requires at least %s'
                                   ' to use an SSL context (VAULT_CACERT or VAULT_CAPATH)'
                                   % (key, python_version_cur, python_version_min))
            elif cahostverify:
                raise AnsibleError('Unable to read %s from vault:'
                                   ' Using Python %s, and vault lookup plugin requires at least %s'
                                   ' to verify Vault certificate. (set VAULT_CAHOSTVERIFY to \'%s\''
                                   ' to disable certificate verification.)'
                                   % (key, python_version_cur, python_version_min, DISABLE_VAULT_CAHOSTVERIFY)) 
Example #14
Source File: sshjail.py    From ansible-sshjail with MIT License 6 votes vote down vote up
def match_jail(self):
        if self.jid is None:
            code, stdout, stderr = self._jailhost_command("jls -q jid name host.hostname path")
            if code != 0:
                display.vvv("JLS stdout: %s" % stdout)
                raise AnsibleError("jls returned non-zero!")

            lines = stdout.strip().split(b'\n')
            found = False
            for line in lines:
                if line.strip() == '':
                    break

                jid, name, hostname, path = to_text(line).strip().split()
                if name == self.jailspec or hostname == self.jailspec:
                    self.jid = jid
                    self.jname = name
                    self.jpath = path
                    found = True
                    break

            if not found:
                raise AnsibleError("failed to find a jail with name or hostname of '%s'" % self.jailspec) 
Example #15
Source File: grafana_dashboard.py    From community.grafana with GNU General Public License v3.0 6 votes vote down vote up
def run(self, terms, variables=None, **kwargs):

        grafana_args = terms[0].split(' ')
        grafana_dict = {}
        ret = []

        for param in grafana_args:
            try:
                key, value = param.split('=')
            except ValueError:
                raise AnsibleError("grafana_dashboard lookup plugin needs key=value pairs, but received %s" % terms)
            grafana_dict[key] = value

        grafana = GrafanaAPI(**grafana_dict)

        ret = grafana.grafana_list_dashboards()

        return ret 
Example #16
Source File: display.py    From litmus with Apache License 2.0 6 votes vote down vote up
def deprecated(self, msg, version=None, removed=False):
        ''' used to print out a deprecation message.'''

        if not removed and not C.DEPRECATION_WARNINGS:
            return

        if not removed:
            if version:
                new_msg = "[DEPRECATION WARNING]: %s. This feature will be removed in version %s." % (msg, version)
            else:
                new_msg = "[DEPRECATION WARNING]: %s. This feature will be removed in a future release." % (msg)
            new_msg = new_msg + " Deprecation warnings can be disabled by setting deprecation_warnings=False in ansible.cfg.\n\n"
        else:
            raise AnsibleError("[DEPRECATED]: %s.\nPlease update your playbooks." % msg)

        wrapped = textwrap.wrap(new_msg, self.columns, drop_whitespace=False)
        new_msg = "\n".join(wrapped) + "\n"

        if new_msg not in self._deprecations:
            self.display(new_msg.strip(), color=C.COLOR_DEPRECATE, stderr=True)
            self._deprecations[new_msg] = 1 
Example #17
Source File: plugins.py    From infrared with Apache License 2.0 6 votes vote down vote up
def _install_roles_from_file(plugin_path):
        # Ansible Galaxy - install roles from file
        for req_file in ['requirements.yml', 'requirements.yaml']:
            galaxy_reqs_file = os.path.join(plugin_path, req_file)
            if not os.path.isfile(galaxy_reqs_file):
                continue
            LOG.debug("Installing Galaxy "
                      "requirements... ({})".format(galaxy_reqs_file))
            from ansible.cli.galaxy import GalaxyCLI
            from ansible.errors import AnsibleError
            glxy_cli = GalaxyCLI(['install'])
            glxy_cli.parse()
            glxy_cli.options.role_file = galaxy_reqs_file
            try:
                glxy_cli.execute_install()
            except AnsibleError as e:
                raise IRFailedToAddPlugin(e.message)
        else:
            LOG.debug("Galaxy requirements files weren't found.") 
Example #18
Source File: lchroot.py    From luna with GNU General Public License v3.0 6 votes vote down vote up
def fetch_file(self, in_path, out_path):
        ''' fetch a file from chroot to local '''
        super(Connection, self).fetch_file(in_path, out_path)
        display.vvv("FETCH %s TO %s" % (in_path, out_path), host=self.path)

        in_path = pipes.quote(self._prefix_login_path(in_path))
        try:
            p = self._buffered_exec_command('dd if=%s bs=%s' % (in_path, BUFSIZE))
        except OSError:
            raise AnsibleError("chroot connection requires dd command in the chroot")

        with open(to_bytes(out_path, errors='surrogate_or_strict'), 'wb+') as out_file:
            try:
                chunk = p.stdout.read(BUFSIZE)
                while chunk:
                    out_file.write(chunk)
                    chunk = p.stdout.read(BUFSIZE)
            except:
                traceback.print_exc()
                raise AnsibleError("failed to transfer file %s to %s" % (in_path, out_path))
            stdout, stderr = p.communicate()
            if p.returncode != 0:
                raise AnsibleError("failed to transfer file %s to %s:\n%s\n%s" % (in_path, out_path, stdout, stderr)) 
Example #19
Source File: ec2_zones_by_region.py    From demo-ansible with Apache License 2.0 5 votes vote down vote up
def run(self, region, inject=None, **kwargs):
        try:
            conn = boto.ec2.connect_to_region(region)
            zones = [z.name for z in conn.get_all_zones()]
            return zones
        except e:
            raise errors.AnsibleError("Could not lookup zones for region: %s\nexception: %s" % (region, e)) 
Example #20
Source File: cloudformation.py    From ansible-plugins with GNU General Public License v3.0 5 votes vote down vote up
def get_item(self, resource_type, key):
        conn = boto.cloudformation.connect_to_region(self.region)
        stack = conn.describe_stacks(stack_name_or_id=self.stack_name)[0]
        if resource_type in ['parameter', 'output']:
            attr = "{0}s".format(resource_type)
            return [item.value for item in
                    getattr(stack, attr) if item.key == key]
        elif resource_type == 'resource_id':
            return [stack.describe_resources(key)[0].physical_resource_id]
        else:
            raise errors.AnsibleError(
                "unknown resource type {0}".format(resource_type)) 
Example #21
Source File: plugin_formatter.py    From citrix-adc-ansible-modules with GNU General Public License v3.0 5 votes vote down vote up
def rst_ify(text):
    ''' convert symbols like I(this is in italics) to valid restructured text '''

    try:
        t = _ITALIC.sub(r"*\1*", text)
        t = _BOLD.sub(r"**\1**", t)
        t = _MODULE.sub(r":ref:`\1 <\1_module>`", t)
        t = _LINK.sub(r"`\1 <\2>`_", t)
        t = _URL.sub(r"\1", t)
        t = _CONST.sub(r"``\1``", t)
        t = _RULER.sub(r"------------", t)
    except Exception as e:
        raise AnsibleError("Could not process (%s) : %s" % (text, e))

    return t 
Example #22
Source File: pfsense.py    From ansible-pfsense with GNU General Public License v3.0 5 votes vote down vote up
def check_alias_name(name):
        """ check an alias name """
        # todo: check reserved keywords (any, self, ...)
        if re.match('^[a-zA-Z0-9_]+$', name) is None:
            raise AnsibleError(name + ': the name of the alias may only consist of the characters "a-z, A-Z, 0-9 and _"') 
Example #23
Source File: wwn.py    From dellemcpmax_ansible with GNU Affero General Public License v3.0 5 votes vote down vote up
def WWN_nodots_filter(self, a_variable):
        """
        Returns WWN uppercase without colons like 112233445566AABB
        :param a_variable: (str) variable to transform
        :return: (str) transformed string
        """
        try:
            return WWN(a_variable).wwn.upper().replace(':', '')
        except WWNError as error:
            raise AnsibleError(f'Malformed WWN {error}') 
Example #24
Source File: sshjail.py    From ansible-sshjail with MIT License 5 votes vote down vote up
def _copy_file(self, from_file, to_file):
        copycmd = self._play_context.make_become_cmd(' '.join(['cp', from_file, to_file]))

        display.vvv(u"REMOTE COPY {0} TO {1}".format(from_file, to_file), host=self.inventory_hostname)
        code, stdout, stderr = self._jailhost_command(copycmd)
        if code != 0:
            raise AnsibleError("failed to copy file from %s to %s:\n%s\n%s" % (from_file, to_file, stdout, stderr)) 
Example #25
Source File: gcp_compute.py    From google.cloud with GNU General Public License v3.0 5 votes vote down vote up
def fail_json(self, *args, **kwargs):
        raise AnsibleError(kwargs["msg"]) 
Example #26
Source File: tripleo_all_nodes_data.py    From tripleo-ansible with Apache License 2.0 5 votes vote down vote up
def run(self, tmp=None, task_vars=None):
        """Renders the all_nodes data for TripleO as group_vars"""

        manager = Manager()
        all_nodes = manager.dict()
        try:
            self.compute_all_nodes(all_nodes, task_vars)

            all_nodes = dict(all_nodes)
            all_nodes_path = os.path.join(task_vars['playbook_dir'],
                                          'group_vars', 'overcloud.json')
            with open(all_nodes_path, 'w') as f:
                DISPLAY.vv("Rendering all_nodes to {}".format(all_nodes_path))
                json.dump(all_nodes, f, sort_keys=True, indent=4)
        except Exception as e:
            DISPLAY.error(traceback.format_exc())
            raise AnsibleError(str(e))
        finally:
            manager.shutdown()
            # multiprocessing can hang the plugin exit if there are still
            # references to the Manager() object. Even though we have called
            # .shutdown(), clean up all_nodes just to be safe.
            all_nodes = None

        DISPLAY.vv("returning")
        return dict(all_nodes=all_nodes) 
Example #27
Source File: vars.py    From trellis with MIT License 5 votes vote down vote up
def raw_vars(self, play, host, hostvars):
        if 'raw_vars' not in hostvars:
            return

        raw_vars = Templar(variables=hostvars, loader=play._loader).template(hostvars['raw_vars'])
        if not isinstance(raw_vars, list):
            raise AnsibleError('The `raw_vars` variable must be defined as a list.')

        patterns = [re.sub(r'\*', '(.)*', re.sub(r'\.', '\.', var)) for var in raw_vars if var.split('.')[0] in hostvars]
        keys = set(pattern.split('\.')[0] for pattern in patterns)
        for key in keys:
            if key in play.vars:
                play.vars[key] = self.raw_triage(key, play.vars[key], patterns)
            elif key in hostvars:
                host.vars[key] = self.raw_triage(key, hostvars[key], patterns) 
Example #28
Source File: gcp_kms_filters.py    From google.cloud with GNU General Public License v3.0 5 votes vote down vote up
def fail_json(self, *args, **kwargs):
        raise AnsibleError(kwargs['msg']) 
Example #29
Source File: bitwarden.py    From ansible-modules-bitwarden with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, path):
        self._cli_path = path
        try:
            check_output(self._cli_path)
        except OSError:
            raise AnsibleError("Command not found: {0}".format(self._cli_path)) 
Example #30
Source File: wwn.py    From dellemcpmax_ansible with GNU Affero General Public License v3.0 5 votes vote down vote up
def WWN_filter(self, a_variable):
        """
        Returns WWN uppercase with colons like 11:22:33:44:55:66:AA:BB
        :param a_variable: (str) variable to transform
        :return: (str) transformed string
        """
        try:
            return WWN(a_variable).wwn.upper()
        except WWNError as error:
            raise AnsibleError(f'Malformed WWN {error}')