本文整理匯總了Python中ansible.errors.AnsibleParserError方法的典型用法代碼示例。如果您正苦於以下問題:Python errors.AnsibleParserError方法的具體用法?Python errors.AnsibleParserError怎麽用?Python errors.AnsibleParserError使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類ansible.errors
的用法示例。
在下文中一共展示了errors.AnsibleParserError方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: run
# 需要導入模塊: from ansible import errors [as 別名]
# 或者: from ansible.errors import AnsibleParserError [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)
示例2: find_version
# 需要導入模塊: from ansible import errors [as 別名]
# 或者: from ansible.errors import AnsibleParserError [as 別名]
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))
示例3: json_type_converter
# 需要導入模塊: from ansible import errors [as 別名]
# 或者: from ansible.errors import AnsibleParserError [as 別名]
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
示例4: login
# 需要導入模塊: from ansible import errors [as 別名]
# 或者: from ansible.errors import AnsibleParserError [as 別名]
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
示例5: parse
# 需要導入模塊: from ansible import errors [as 別名]
# 或者: from ansible.errors import AnsibleParserError [as 別名]
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)
示例6: _get_host_vars
# 需要導入模塊: from ansible import errors [as 別名]
# 或者: from ansible.errors import AnsibleParserError [as 別名]
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
示例7: parse_source
# 需要導入模塊: from ansible import errors [as 別名]
# 或者: from ansible.errors import AnsibleParserError [as 別名]
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
示例8: hostname
# 需要導入模塊: from ansible import errors [as 別名]
# 或者: from ansible.errors import AnsibleParserError [as 別名]
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")
示例9: run
# 需要導入模塊: from ansible import errors [as 別名]
# 或者: from ansible.errors import AnsibleParserError [as 別名]
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
示例10: fetch_allowed_list
# 需要導入模塊: from ansible import errors [as 別名]
# 或者: from ansible.errors import AnsibleParserError [as 別名]
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
示例11: logout
# 需要導入模塊: from ansible import errors [as 別名]
# 或者: from ansible.errors import AnsibleParserError [as 別名]
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)))
示例12: get_lag
# 需要導入模塊: from ansible import errors [as 別名]
# 或者: from ansible.errors import AnsibleParserError [as 別名]
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
示例13: conv_str2value
# 需要導入模塊: from ansible import errors [as 別名]
# 或者: from ansible.errors import AnsibleParserError [as 別名]
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
示例14: parse
# 需要導入模塊: from ansible import errors [as 別名]
# 或者: from ansible.errors import AnsibleParserError [as 別名]
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
示例15: parse
# 需要導入模塊: from ansible import errors [as 別名]
# 或者: from ansible.errors import AnsibleParserError [as 別名]
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))