本文整理汇总了Python中ansible.module_utils._text.to_bytes方法的典型用法代码示例。如果您正苦于以下问题:Python _text.to_bytes方法的具体用法?Python _text.to_bytes怎么用?Python _text.to_bytes使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类ansible.module_utils._text
的用法示例。
在下文中一共展示了_text.to_bytes方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: get_play_prereqs_2_4
# 需要导入模块: from ansible.module_utils import _text [as 别名]
# 或者: from ansible.module_utils._text import to_bytes [as 别名]
def get_play_prereqs_2_4(self, options):
loader = DataLoader()
if self.vault_pass:
loader.set_vault_secrets([('default', VaultSecret(_bytes=to_bytes(self.vault_pass)))])
# create the inventory, and filter it based on the subset specified (if any)
inventory = InventoryManager(loader=loader, sources=options.inventory)
# create the variable manager, which will be shared throughout
# the code, ensuring a consistent view of global variables
try:
# Ansible 2.8
variable_manager = VariableManager(loader=loader, inventory=inventory,
version_info=self.version_info(ansible_version))
variable_manager._extra_vars = self.extra_vars
except TypeError:
variable_manager = VariableManager(loader=loader, inventory=inventory)
variable_manager.extra_vars = self.extra_vars
variable_manager.options_vars = {'ansible_version': self.version_info(ansible_version)}
return loader, inventory, variable_manager
示例2: connect
# 需要导入模块: from ansible.module_utils import _text [as 别名]
# 或者: from ansible.module_utils._text import to_bytes [as 别名]
def connect(self):
self.foremanapi = apypie.Api(
uri=self._foremanapi_server_url,
username=to_bytes(self._foremanapi_username),
password=to_bytes(self._foremanapi_password),
api_version=2,
verify_ssl=self._foremanapi_validate_certs,
)
self.ping()
self._patch_templates_resource_name()
self._patch_location_api()
self._patch_subnet_rex_api()
self.check_required_plugins()
示例3: parse
# 需要导入模块: from ansible.module_utils import _text [as 别名]
# 或者: from ansible.module_utils._text import to_bytes [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)
示例4: update_play_context
# 需要导入模块: from ansible.module_utils import _text [as 别名]
# 或者: from ansible.module_utils._text import to_bytes [as 别名]
def update_play_context(self, pc_data):
"""Updates the play context information for the connection"""
pc_data = to_bytes(pc_data)
if PY3:
pc_data = cPickle.loads(pc_data, encoding='bytes')
else:
pc_data = cPickle.loads(pc_data)
play_context = PlayContext()
play_context.deserialize(pc_data)
messages = ['updating play_context for connection']
if self._play_context.become ^ play_context.become:
self._httpapi.set_become(play_context)
self._play_context = play_context
return messages
示例5: _buffered_exec_command
# 需要导入模块: from ansible.module_utils import _text [as 别名]
# 或者: from ansible.module_utils._text import to_bytes [as 别名]
def _buffered_exec_command(self, cmd, stdin=subprocess.PIPE):
''' run a command on the chroot. This is only needed for implementing
put_file() get_file() so that we don't have to read the whole file
into memory.
compared to exec_command() it looses some niceties like being able to
return the process's exit code immediately.
'''
executable = C.DEFAULT_EXECUTABLE.split()[0] if C.DEFAULT_EXECUTABLE else '/bin/sh'
local_cmd = [self.chroot_cmd, self.path, executable, '-c', cmd]
display.vvv(
"EXEC %s cmd is %s" % (local_cmd,cmd), host=self.path)
local_cmd = [to_bytes(i, errors='surrogate_or_strict') for i in local_cmd]
p = subprocess.Popen(local_cmd, shell=False, stdin=stdin,
env={
'PATH': '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin',
'FAKE_KERN': self.osimage.get('kernver'),
'LD_PRELOAD': 'libluna-fakeuname.so'
},
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
return p
示例6: put_file
# 需要导入模块: from ansible.module_utils import _text [as 别名]
# 或者: from ansible.module_utils._text import to_bytes [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)
示例7: fetch_file
# 需要导入模块: from ansible.module_utils import _text [as 别名]
# 或者: from ansible.module_utils._text import to_bytes [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))
示例8: banner_cowsay
# 需要导入模块: from ansible.module_utils import _text [as 别名]
# 或者: from ansible.module_utils._text import to_bytes [as 别名]
def banner_cowsay(self, msg, color=None):
if u": [" in msg:
msg = msg.replace(u"[", u"")
if msg.endswith(u"]"):
msg = msg[:-1]
runcmd = [self.b_cowsay, b"-W", b"60"]
if self.noncow:
thecow = self.noncow
if thecow == 'random':
thecow = random.choice(list(self.cows_available))
runcmd.append(b'-f')
runcmd.append(to_bytes(thecow))
runcmd.append(to_bytes(msg))
cmd = subprocess.Popen(runcmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
(out, err) = cmd.communicate()
self.display(u"%s\n" % to_text(out), color=color)
示例9: construct_command_from_params
# 需要导入模块: from ansible.module_utils import _text [as 别名]
# 或者: from ansible.module_utils._text import to_bytes [as 别名]
def construct_command_from_params(self):
"""Create a podman command from given module parameters.
Returns:
list -- list of byte strings for Popen command
"""
if self.action in ['start', 'stop', 'delete']:
return self.start_stop_delete()
if self.action in ['create', 'run']:
cmd = [self.action, '--name', self.params['name']]
all_param_methods = [func for func in dir(self)
if callable(getattr(self, func))
and func.startswith("addparam")]
params_set = (i for i in self.params if self.params[i] is not None)
for param in params_set:
func_name = "_".join(["addparam", param])
if func_name in all_param_methods:
cmd = getattr(self, func_name)(cmd)
cmd.append(self.params['image'])
if self.params['command']:
if isinstance(self.params['command'], list):
cmd += self.params['command']
else:
cmd += self.params['command'].split()
return [to_bytes(i, errors='surrogate_or_strict') for i in cmd]
示例10: cfndiff_module_validation
# 需要导入模块: from ansible.module_utils import _text [as 别名]
# 或者: from ansible.module_utils._text import to_bytes [as 别名]
def cfndiff_module_validation(module):
'''
Validate for correct module call/usage in ansible.
'''
# Boto3 is required!
if not HAS_BOTO3:
module.fail_json(msg='boto3 is required. Try pip install boto3')
# cfn_flip is required!
if not HAS_CFN_FLIP:
module.fail_json(msg='cfn_flip is required. Try pip install cfn_flip')
template = module.params['template']
b_template = to_bytes(template, errors='surrogate_or_strict')
# Validate path of template
if not os.path.exists(b_template):
module.fail_json(msg="template %s not found" % (template))
if not os.access(b_template, os.R_OK):
module.fail_json(msg="template %s not readable" % (template))
if os.path.isdir(b_template):
module.fail_json(msg="diff does not support recursive diff of directory: %s" % (template))
return module
示例11: _transfer_data
# 需要导入模块: from ansible.module_utils import _text [as 别名]
# 或者: from ansible.module_utils._text import to_bytes [as 别名]
def _transfer_data(self, remote_path, data):
"""
Used by the base _execute_module(), and in <2.4 also by the template
action module, and probably others.
"""
if isinstance(data, dict):
data = jsonify(data)
if not isinstance(data, bytes):
data = to_bytes(data, errors='surrogate_or_strict')
LOG.debug('_transfer_data(%r, %s ..%d bytes)',
remote_path, type(data), len(data))
self._connection.put_data(remote_path, data)
return remote_path
#: Actions listed here cause :func:`_fixup_perms2` to avoid a needless
#: roundtrip, as they modify file modes separately afterwards. This is due
#: to the method prototype having a default of `execute=True`.
示例12: _generate_report
# 需要导入模块: from ansible.module_utils import _text [as 别名]
# 或者: from ansible.module_utils._text import to_bytes [as 别名]
def _generate_report(self):
"""Generate a TestSuite report.
Generate a TestSuite report from the collected TaskData and HostData.
"""
test_cases = []
for task_uuid, task_data in self._task_data.items():
if task_data.action == 'setup' and \
self._include_setup_tasks_in_report == 'false':
continue
for host_uuid, host_data in task_data.host_data.items():
test_cases.append(self._build_test_case(task_data, host_data))
test_suite = TestSuite(self._playbook_name, test_cases)
report = TestSuite.to_xml_string([test_suite])
output_file = os.path.join(self._output_dir, '%s-%s.xml' % (
self._playbook_name, time.time()))
with open(output_file, 'wb') as xml:
xml.write(to_bytes(report, errors='surrogate_or_strict'))
示例13: write
# 需要导入模块: from ansible.module_utils import _text [as 别名]
# 或者: from ansible.module_utils._text import to_bytes [as 别名]
def write(self):
result = {'dest': self.outfile}
if self.module.check_mode: # stop here before doing anything permanent
return result
dump_kwargs = {}
if self.pretty_print:
dump_kwargs.update({'indent': 4, 'separators': (',', ': ')})
if self.do_backup: # backup first if needed
result.update(self.backup())
tmpfd, tmpfile = tempfile.mkstemp()
with open(tmpfile, "w") as f:
f.write(json.dumps(self.patcher.obj, **dump_kwargs))
self.module.atomic_move(tmpfile,
to_native(os.path.realpath(to_bytes(self.outfile, errors='surrogate_or_strict')), errors='surrogate_or_strict'),
unsafe_writes=self.module.params['unsafe_writes'])
return result
示例14: get_vault_editor
# 需要导入模块: from ansible.module_utils import _text [as 别名]
# 或者: from ansible.module_utils._text import to_bytes [as 别名]
def get_vault_editor(vault_password):
"""
Get the correct VaultEditor object in different Ansible versions
"""
if LooseVersion(ansible_version) >= LooseVersion("2.4.0"):
# for Ansible version 2.4.0 or higher
vault_secrets = [('default', VaultSecret(_bytes=to_bytes(vault_password)))]
return VaultEditor(VaultLib(vault_secrets))
else:
# for Ansible version 2.3.2 or lower
return VaultEditor(vault_password)
示例15: _get_session
# 需要导入模块: from ansible.module_utils import _text [as 别名]
# 或者: from ansible.module_utils._text import to_bytes [as 别名]
def _get_session(self):
if not self.session:
self.session = requests.session()
self.session.auth = HTTPBasicAuth(self.get_option('user'), to_bytes(self.get_option('password')))
self.session.verify = self.get_option('validate_certs')
return self.session