本文整理匯總了Python中ansible.module_utils._text.to_text方法的典型用法代碼示例。如果您正苦於以下問題:Python _text.to_text方法的具體用法?Python _text.to_text怎麽用?Python _text.to_text使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類ansible.module_utils._text
的用法示例。
在下文中一共展示了_text.to_text方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: get_vars
# 需要導入模塊: from ansible.module_utils import _text [as 別名]
# 或者: from ansible.module_utils._text import to_text [as 別名]
def get_vars(self, loader, path, entities):
super().get_vars(loader, path, entities)
result = {}
lab_templates_dir = os.path.join(path, 'user-data', 'topologies')
lab_templates = {}
if os.path.isdir(lab_templates_dir):
for dir_path, subdirs, files in os.walk(lab_templates_dir):
for filename in files:
base_filename, extension = os.path.splitext(filename)
if base_filename == 'topology' and to_text(extension) in constants.YAML_FILENAME_EXTENSIONS:
full_path = os.path.join(dir_path, filename)
dir_name = os.path.basename(os.path.dirname(full_path))
lab_templates[dir_name] = loader.load_from_file(
full_path,
cache=True,
unsafe=False
)
result['topologies'] = lab_templates
return result
示例2: vault_format_ciphertext_yaml
# 需要導入模塊: from ansible.module_utils import _text [as 別名]
# 或者: from ansible.module_utils._text import to_text [as 別名]
def vault_format_ciphertext_yaml(b_ciphertext, indent=None, name=None):
"""
Format a ciphertext to YAML compatible string
"""
indent = indent or 10
block_format_var_name = ''
if name:
block_format_var_name = '%s: ' % name
block_format_header = '%s!vault |' % block_format_var_name
lines = []
vault_ciphertext = to_text(b_ciphertext)
lines.append(block_format_header)
for line in vault_ciphertext.splitlines():
lines.append('%s%s' % (' ' * indent, line))
yaml_ciphertext = '\n'.join(lines)
return yaml_ciphertext
示例3: _get_tag_hostname
# 需要導入模塊: from ansible.module_utils import _text [as 別名]
# 或者: from ansible.module_utils._text import to_text [as 別名]
def _get_tag_hostname(self, preference, instance):
tag_hostnames = preference['tags']
if ',' in tag_hostnames:
tag_hostnames = tag_hostnames.split(',')
else:
tag_hostnames = [tag_hostnames]
tags = instance.get('tags', {})
for v in tag_hostnames:
if '=' in v:
tag_name, tag_value = v.split('=')
if tags.get(tag_name) == tag_value:
return to_text(tag_name) + "_" + to_text(tag_value)
else:
tag_value = tags.get(v)
if tag_value:
return to_text(tag_value)
return None
示例4: _get_hostname
# 需要導入模塊: from ansible.module_utils import _text [as 別名]
# 或者: from ansible.module_utils._text import to_text [as 別名]
def _get_hostname(self, instance, hostnames):
'''
:param instance: an instance dict returned by describe_instances()
:param hostnames: a list of hostname destination variables in order of preference
:return the preferred identifer for the host
'''
if not hostnames:
hostnames = ['instance_id', 'instance_name']
hostname = None
for preference in hostnames:
if 'tag' in preference:
hostname = self._get_tag_hostname(preference, instance)
else:
hostname = self._get_instance_attr(preference, instance)
if hostname:
break
if hostname:
if ':' in to_text(hostname):
return self._sanitize_group_name((to_text(hostname)))
else:
return to_text(hostname)
示例5: get_manifest
# 需要導入模塊: from ansible.module_utils import _text [as 別名]
# 或者: from ansible.module_utils._text import to_text [as 別名]
def get_manifest(module):
path = "/subscription/owners/%s/consumers?type=satellite" % (module.params['rhsm_owner'])
resp, info = fetch_portal(module, path, 'GET')
manifests = json.loads(to_text(resp.read()))
if module.params['name']:
attr = 'name'
if module.params['uuid']:
attr = 'uuid'
manifest = [m for m in manifests if m[attr] == module.params[attr]]
if manifest:
if module.params['state'] == 'present':
return manifest[0], False
if module.params['state'] == 'absent':
if not module.check_mode:
return delete_manifest(module, manifest[0]['uuid']), True
return None, True
elif module.params['state'] == 'present':
if not module.check_mode:
return create_manifest(module), True
return None, True
return None, False
示例6: send_facts
# 需要導入模塊: from ansible.module_utils import _text [as 別名]
# 或者: from ansible.module_utils._text import to_text [as 別名]
def send_facts(self, host, data):
"""
Sends facts to Foreman, to be parsed by foreman_ansible fact
parser. The default fact importer should import these facts
properly.
"""
data["_type"] = "ansible"
data["_timestamp"] = datetime.now().strftime(self.TIME_FORMAT)
facts = {"name": host,
"facts": data,
}
try:
r = requests.post(url=self.FOREMAN_URL + '/api/v2/hosts/facts',
data=json.dumps(facts),
headers=self.FOREMAN_HEADERS,
cert=self.FOREMAN_SSL_CERT,
verify=self.ssl_verify)
r.raise_for_status()
except requests.exceptions.RequestException as err:
print(to_text(err))
示例7: find_version
# 需要導入模塊: from ansible.module_utils import _text [as 別名]
# 或者: from ansible.module_utils._text import to_text [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))
示例8: json_type_converter
# 需要導入模塊: from ansible.module_utils import _text [as 別名]
# 或者: from ansible.module_utils._text import to_text [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
示例9: login
# 需要導入模塊: from ansible.module_utils import _text [as 別名]
# 或者: from ansible.module_utils._text import to_text [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
示例10: parse
# 需要導入模塊: from ansible.module_utils import _text [as 別名]
# 或者: from ansible.module_utils._text import to_text [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)
示例11: get_a_ssh_config
# 需要導入模塊: from ansible.module_utils import _text [as 別名]
# 或者: from ansible.module_utils._text import to_text [as 別名]
def get_a_ssh_config(box_name):
"""Gives back a map of all the machine's ssh configurations"""
output = to_text(subprocess.check_output(["vagrant", "ssh-config", box_name]), errors='surrogate_or_strict')
config = SSHConfig()
config.parse(StringIO(output))
host_config = config.lookup(box_name)
# man 5 ssh_config:
# > It is possible to have multiple identity files ...
# > all these identities will be tried in sequence.
for id in host_config['identityfile']:
if os.path.isfile(id):
host_config['identityfile'] = id
return dict((v, host_config[k]) for k, v in _ssh_to_ansible)
# List out servers that vagrant has running
# ------------------------------
示例12: _authorize
# 需要導入模塊: from ansible.module_utils import _text [as 別名]
# 或者: from ansible.module_utils._text import to_text [as 別名]
def _authorize(self, username, password):
def request_token(url):
resp = open_url(
url,
method=HTTPMethod.POST,
data=json.dumps({'grant_type': 'password', 'username': username, 'password': password}),
headers=BASE_HEADERS,
validate_certs=False
).read()
return json.loads(to_text(resp))
api_versions = sorted(self._fetch_api_versions(), reverse=True)
for version in api_versions:
token_url = self._hostname + self.TOKEN_PATH_TEMPLATE.format(version)
try:
token = request_token(token_url)
except urllib_error.HTTPError as e:
logger.debug("Can't get token for API version: %s", version, exc_info=True)
if e.code != HTTPStatus.UNAUTHORIZED:
raise
else:
return token
raise Exception("Can't fetch token via API")
示例13: equal_values
# 需要導入模塊: from ansible.module_utils import _text [as 別名]
# 或者: from ansible.module_utils._text import to_text [as 別名]
def equal_values(v1, v2):
"""
Checks whether types and content of two values are the same. In case of complex objects, the method might be
called recursively.
:param v1: first value
:param v2: second value
:return: True if types and content of passed values are equal. Otherwise, returns False.
:rtype: bool
"""
# string-like values might have same text but different types, so checking them separately
if is_string(v1) and is_string(v2):
return to_text(v1) == to_text(v2)
if type(v1) != type(v2):
return False
value_type = type(v1)
if value_type == list:
return equal_lists(v1, v2)
elif value_type == dict:
return equal_dicts(v1, v2)
else:
return v1 == v2
示例14: _get_config
# 需要導入模塊: from ansible.module_utils import _text [as 別名]
# 或者: from ansible.module_utils._text import to_text [as 別名]
def _get_config(p, section, key, env_var, default):
''' helper function for get_config '''
value = default
if p is not None:
try:
value = p.get(section, key, raw=True)
except:
pass
if env_var is not None:
env_value = os.environ.get(env_var, None)
if env_value is not None:
value = env_value
return to_text(value, errors='surrogate_or_strict', nonstring='passthru')
示例15: _validate_request
# 需要導入模塊: from ansible.module_utils import _text [as 別名]
# 或者: from ansible.module_utils._text import to_text [as 別名]
def _validate_request(self, method, payload, check):
'''Compares value being applied to the configuration present on the device'''
check_presence = self.get_config(check)
if method == 'DELETE':
if not check_presence:
response = {'changed': False,
'failed': False,
'msg': 'Not present'}
return response
elif method != 'GET':
if check_presence:
diffkeys = False
data = self._module.from_json(to_text(check_presence))
for key in payload:
if key in data:
if payload[key] != data[key]:
diffkeys = True
break
if not diffkeys:
data['changed'] = False
data['failed'] = False
return data
return None