当前位置: 首页>>代码示例>>Python>>正文


Python errors.AnsibleError方法代码示例

本文整理汇总了Python中ansible.errors.AnsibleError方法的典型用法代码示例。如果您正苦于以下问题:Python errors.AnsibleError方法的具体用法?Python errors.AnsibleError怎么用?Python errors.AnsibleError使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在ansible.errors的用法示例。


在下文中一共展示了errors.AnsibleError方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: _get_instances_by_region

# 需要导入模块: from ansible import errors [as 别名]
# 或者: from ansible.errors import AnsibleError [as 别名]
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']) 
开发者ID:alibaba,项目名称:alibaba.alicloud,代码行数:23,代码来源:alicloud_ecs.py

示例2: run

# 需要导入模块: from ansible import errors [as 别名]
# 或者: from ansible.errors import AnsibleError [as 别名]
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) 
开发者ID:PacktPublishing,项目名称:Implementing-DevOps-with-Ansible-2,代码行数:22,代码来源:Example4.LookUpPlugin.py

示例3: _fetch_client_token

# 需要导入模块: from ansible import errors [as 别名]
# 或者: from ansible.errors import AnsibleError [as 别名]
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 
开发者ID:jhaals,项目名称:ansible-vault,代码行数:23,代码来源:vault.py

示例4: _fetch_secret

# 需要导入模块: from ansible import errors [as 别名]
# 或者: from ansible.errors import AnsibleError [as 别名]
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 
开发者ID:jhaals,项目名称:ansible-vault,代码行数:27,代码来源:vault.py

示例5: _verify_python_version

# 需要导入模块: from ansible import errors [as 别名]
# 或者: from ansible.errors import AnsibleError [as 别名]
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)) 
开发者ID:jhaals,项目名称:ansible-vault,代码行数:19,代码来源:vault.py

示例6: run

# 需要导入模块: from ansible import errors [as 别名]
# 或者: from ansible.errors import AnsibleError [as 别名]
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 
开发者ID:opendevops-cn,项目名称:codo-cmdb,代码行数:19,代码来源:runner.py

示例7: run

# 需要导入模块: from ansible import errors [as 别名]
# 或者: from ansible.errors import AnsibleError [as 别名]
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 
开发者ID:ansible-collections,项目名称:community.grafana,代码行数:20,代码来源:grafana_dashboard.py

示例8: put_file

# 需要导入模块: from ansible import errors [as 别名]
# 或者: from ansible.errors import AnsibleError [as 别名]
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) 
开发者ID:dchirikov,项目名称:luna,代码行数:23,代码来源:lchroot.py

示例9: fetch_file

# 需要导入模块: from ansible import errors [as 别名]
# 或者: from ansible.errors import AnsibleError [as 别名]
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)) 
开发者ID:dchirikov,项目名称:luna,代码行数:25,代码来源:lchroot.py

示例10: deprecated

# 需要导入模块: from ansible import errors [as 别名]
# 或者: from ansible.errors import AnsibleError [as 别名]
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 
开发者ID:litmuschaos,项目名称:litmus,代码行数:23,代码来源:display.py

示例11: match_jail

# 需要导入模块: from ansible import errors [as 别名]
# 或者: from ansible.errors import AnsibleError [as 别名]
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) 
开发者ID:austinhyde,项目名称:ansible-sshjail,代码行数:25,代码来源:sshjail.py

示例12: run

# 需要导入模块: from ansible import errors [as 别名]
# 或者: from ansible.errors import AnsibleError [as 别名]
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] 
开发者ID:openshift,项目名称:openshift-ansible-contrib,代码行数:24,代码来源:os_cinder.py

示例13: template

# 需要导入模块: from ansible import errors [as 别名]
# 或者: from ansible.errors import AnsibleError [as 别名]
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 
开发者ID:haidaraM,项目名称:ansible-playbook-grapher,代码行数:22,代码来源:grapher.py

示例14: _install_roles_from_file

# 需要导入模块: from ansible import errors [as 别名]
# 或者: from ansible.errors import AnsibleError [as 别名]
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.") 
开发者ID:redhat-openstack,项目名称:infrared,代码行数:21,代码来源:plugins.py

示例15: load_data

# 需要导入模块: from ansible import errors [as 别名]
# 或者: from ansible.errors import AnsibleError [as 别名]
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 
开发者ID:opoplawski,项目名称:ansible-pfsense,代码行数:20,代码来源:pfsense.py


注:本文中的ansible.errors.AnsibleError方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。