本文整理汇总了Python中ansible.module_utils._text.to_native方法的典型用法代码示例。如果您正苦于以下问题:Python _text.to_native方法的具体用法?Python _text.to_native怎么用?Python _text.to_native使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类ansible.module_utils._text
的用法示例。
在下文中一共展示了_text.to_native方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: query_metadata
# 需要导入模块: from ansible.module_utils import _text [as 别名]
# 或者: from ansible.module_utils._text import to_native [as 别名]
def query_metadata(metadata_url, headers=None, expect_json=False):
""" Return metadata from the provided metadata_url
Args:
metadata_url (str): metadata url
headers (dict): headers to set for metadata request
expect_json (bool): does the metadata_url return json
Returns:
dict or list: metadata request result
"""
result, info = fetch_url(module, metadata_url, headers=headers)
if info['status'] != 200:
raise OpenShiftFactsMetadataUnavailableError("Metadata unavailable")
if expect_json:
return module.from_json(to_native(result.read()))
else:
return [to_native(line.strip()) for line in result.readlines()]
示例2: _get_instances_by_region
# 需要导入模块: from ansible.module_utils import _text [as 别名]
# 或者: from ansible.module_utils._text import to_native [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'])
示例3: resource_action
# 需要导入模块: from ansible.module_utils import _text [as 别名]
# 或者: from ansible.module_utils._text import to_native [as 别名]
def resource_action(self, resource, action, params, options=None, data=None, files=None,
ignore_check_mode=False, record_change=True, ignore_task_errors=False):
resource_payload = self._resource_prepare_params(resource, action, params)
if options is None:
options = {}
try:
result = None
if ignore_check_mode or not self.check_mode:
result = self._resource_call(resource, action, resource_payload, options=options, data=data, files=files)
is_foreman_task = isinstance(result, dict) and 'action' in result and 'state' in result and 'started_at' in result
if is_foreman_task:
result = self.wait_for_task(result, ignore_errors=ignore_task_errors)
except Exception as e:
msg = 'Error while performing {0} on {1}: {2}'.format(
action, resource, to_native(e))
self.fail_from_exception(e, msg)
if record_change and not ignore_check_mode:
# If we were supposed to ignore check_mode we can assume this action was not a changing one.
self.set_changed()
return result
示例4: parse_template
# 需要导入模块: from ansible.module_utils import _text [as 别名]
# 或者: from ansible.module_utils._text import to_native [as 别名]
def parse_template(template_content, module):
if not HAS_PYYAML:
module.fail_json(msg=missing_required_lib("PyYAML"), exception=PYYAML_IMP_ERR)
try:
template_dict = {}
data = re.search(
r'<%#([^%]*([^%]*%*[^>%])*%*)%>', template_content)
if data:
datalist = data.group(1)
if datalist[-1] == '-':
datalist = datalist[:-1]
template_dict = yaml.safe_load(datalist)
# No metadata, import template anyway
template_dict['template'] = template_content
except Exception as e:
module.fail_json(msg='Error while parsing template: ' + to_native(e))
return template_dict
示例5: _perform_action
# 需要导入模块: from ansible.module_utils import _text [as 别名]
# 或者: from ansible.module_utils._text import to_native [as 别名]
def _perform_action(self, action):
"""Perform action with container
Arguments:
action {str} -- action to perform - start, create, stop, run, delete
"""
b_command = construct_command_from_params(action, self.module.params)
self.module.log(
"PODMAN-DEBUG: %s" % " ".join([to_native(i) for i in b_command])
)
rc, out, err = run_podman_command(
module=self.module, args=[b"container"] + b_command, ignore_errors=True
)
if rc != 0:
self.module.fail_json(
msg="Can't %s container %s" % (action, self.name),
stdout=out,
stderr=err,
)
示例6: grafana_list_dashboards
# 需要导入模块: from ansible.module_utils import _text [as 别名]
# 或者: from ansible.module_utils._text import to_native [as 别名]
def grafana_list_dashboards(self):
# define http headers
headers = self.grafana_headers()
dashboard_list = []
try:
if self.search:
r = open_url('%s/api/search?query=%s' % (self.grafana_url, self.search), headers=headers, method='GET')
else:
r = open_url('%s/api/search/' % self.grafana_url, headers=headers, method='GET')
except HTTPError as e:
raise GrafanaAPIException('Unable to search dashboards : %s' % to_native(e))
if r.getcode() == 200:
try:
dashboard_list = json.loads(r.read())
except Exception as e:
raise GrafanaAPIException('Unable to parse json list %s' % to_native(e))
else:
raise GrafanaAPIException('Unable to list grafana dashboards : %s' % str(r.getcode()))
return dashboard_list
示例7: find_object_by_name
# 需要导入模块: from ansible.module_utils import _text [as 别名]
# 或者: from ansible.module_utils._text import to_native [as 别名]
def find_object_by_name(module,content, object_name):
try:
if(object_name == module.params['datacenter']):
vmware_objects = get_all_objs(module,content,[vim.Datacenter])
elif (object_name == module.params['cluster']):
vmware_objects = get_all_objs(module,content,[vim.ComputeResource])
elif (object_name == module.params['datastore']):
vmware_objects = get_all_objs(module,content,[vim.Datastore])
elif (object_name == module.params['portgroup1'] or module.params['portgroup2'] or module.params['portgroup3'] ):
vmware_objects = get_all_objs(module,content,[vim.dvs.DistributedVirtualPortgroup, vim.Network])
for object in vmware_objects:
if object.name == object_name:
logger.info('object: %s',object.name)
return object
return None
except Exception as err:
module.fail_json(changed=False, msg= "Error Occured while Finding the Object by name. Error is %s" %(to_native(err)))
示例8: transform_list_to_dict
# 需要导入模块: from ansible.module_utils import _text [as 别名]
# 或者: from ansible.module_utils._text import to_native [as 别名]
def transform_list_to_dict(list_):
"""
Transforms a list into a dictionary, putting values as keys.
:arg list list_: List of values
:return: dict: dictionary built
"""
ret = {}
if not list_:
return ret
for value in list_:
if isinstance(value, collections.Mapping):
ret.update(value)
else:
ret[to_native(value)] = True
return ret
# Makes a deep merge of 2 dictionaries and returns the merged dictionary
示例9: _connect
# 需要导入模块: from ansible.module_utils import _text [as 别名]
# 或者: from ansible.module_utils._text import to_native [as 别名]
def _connect(self):
if self.module.params['file_mode']:
self.forti_device = FortiOS('')
else:
host = self.module.params['host']
username = self.module.params['username']
password = self.module.params['password']
timeout = self.module.params['timeout']
vdom = self.module.params['vdom']
self.forti_device = FortiOS(host, username=username, password=password, timeout=timeout, vdom=vdom)
try:
self.forti_device.open()
except Exception as e:
self.module.fail_json(msg='Error connecting device. %s' % to_native(e),
exception=traceback.format_exc())
示例10: export_manifest
# 需要导入模块: from ansible.module_utils import _text [as 别名]
# 或者: from ansible.module_utils._text import to_native [as 别名]
def export_manifest(module, manifest):
path = "/subscription/consumers/%s/export" % (manifest['uuid'])
try:
resp, info = fetch_portal(module, path, 'GET', accept_header='application/zip')
if not module.check_mode:
with open(module.params['path'], 'wb') as f:
while True:
data = resp.read(65536) # 64K
if not data:
break
f.write(data)
except Exception as e:
module.fail_json(msg="Failure downloading manifest, {0}".format(to_native(e)))
示例11: _exception2fail_json
# 需要导入模块: from ansible.module_utils import _text [as 别名]
# 或者: from ansible.module_utils._text import to_native [as 别名]
def _exception2fail_json(msg='Generic failure: {0}'):
def decor(f):
@wraps(f)
def inner(self, *args, **kwargs):
try:
return f(self, *args, **kwargs)
except Exception as e:
self.fail_from_exception(e, msg.format(to_native(e)))
return inner
return decor
示例12: _update_entity
# 需要导入模块: from ansible.module_utils import _text [as 别名]
# 或者: from ansible.module_utils._text import to_native [as 别名]
def _update_entity(self, resource, desired_entity, current_entity, params, foreman_spec):
"""Update a given entity with given properties if any diverge
Parameters:
resource (string): Plural name of the api resource to manipulate
desired_entity (dict): Desired properties of the entity
current_entity (dict): Current properties of the entity
params (dict): Lookup parameters (i.e. parent_id for nested entities) (optional)
foreman_spec (dict): Description of the entity structure
Return value:
The new current state if the entity
"""
payload = {}
desired_entity = _flatten_entity(desired_entity, foreman_spec)
current_entity = _flatten_entity(current_entity, foreman_spec)
for key, value in desired_entity.items():
# String comparison needs extra care in face of unicode
if foreman_spec[key].get('type', 'str') == 'str':
if to_native(current_entity.get(key)) != to_native(value):
payload[key] = value
else:
if current_entity.get(key) != value:
payload[key] = value
if payload:
payload['id'] = current_entity['id']
if not self.check_mode:
if params:
payload.update(params)
return self.resource_action(resource, 'update', payload)
else:
# In check_mode we emulate the server updating the entity
fake_entity = current_entity.copy()
fake_entity.update(payload)
self.set_changed()
return fake_entity
else:
# Nothing needs changing
return current_entity
示例13: download_plugin
# 需要导入模块: from ansible.module_utils import _text [as 别名]
# 或者: from ansible.module_utils._text import to_native [as 别名]
def download_plugin(module, plugin_url, file_name, download_cache):
if not os.path.isdir(download_cache):
os.makedirs(download_cache, 0o775)
download_path = os.path.join(download_cache, file_name)
if os.path.isfile(download_path):
return download_path
for _ in range(0, 3):
resp, info = fetch_url(
module, plugin_url, method='GET', timeout=20, follow_redirects=True)
status_code = info['status']
if status_code >= 200 and status_code < 300:
tmp_dest = getattr(module, 'tmpdir', None)
fd, b_tempname = tempfile.mkstemp(dir=tmp_dest)
f = os.fdopen(fd, 'wb')
try:
shutil.copyfileobj(resp, f)
except Exception as e:
os.remove(b_tempname)
resp.close()
module.fail_json(
msg='Failed to create temporary content file: %s' %
to_native(e))
f.close()
resp.close()
module.atomic_move(to_native(b_tempname), download_path)
return download_path
if resp is not None:
resp.close()
module.fail_json(msg='Error downloading url "%s": %s' % (plugin_url,
info['msg']))
示例14: parse
# 需要导入模块: from ansible.module_utils import _text [as 别名]
# 或者: from ansible.module_utils._text import to_native [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))
示例15: server_exists
# 需要导入模块: from ansible.module_utils import _text [as 别名]
# 或者: from ansible.module_utils._text import to_native [as 别名]
def server_exists(api, server):
# hack to determine if virtual server exists
result = False
try:
api.GlobalLB.Server.get_object_status([server])
result = True
except bigsuds.OperationFailed as e:
if "was not found" in to_native(e):
result = False
else:
# genuine exception
raise
return result