當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。