Skip to content

Commit 82f7bd6

Browse files
committed
Eventually decode ansible output when it's not ascii
ansible seems to write a json file using encoding of the remote system, which might not be UTF-8 In order to decode such files properly, first try with ascii and fallback to testinfra encoding detection if needed.
1 parent 07f7a98 commit 82f7bd6

File tree

2 files changed

+14
-4
lines changed

2 files changed

+14
-4
lines changed

testinfra/backend/ansible.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -65,8 +65,11 @@ def run(self, command, *args, **kwargs):
6565
)
6666

6767
def run_ansible(self, module_name, module_args=None, **kwargs):
68+
def get_encoding():
69+
return self.encoding
70+
6871
result = self.ansible_runner.run_module(
69-
self.host, module_name, module_args, **kwargs
72+
self.host, module_name, module_args, get_encoding=get_encoding, **kwargs
7073
)
7174
logger.info(
7275
"RUN Ansible(%s, %s, %s): %s",

testinfra/utils/ansible_runner.py

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -277,7 +277,7 @@ def options_to_cli(self, options):
277277
raise TypeError("Unsupported argument type '{}'.".format(opt_type))
278278
return " ".join(cli), cli_args
279279

280-
def run_module(self, host, module_name, module_args, **options):
280+
def run_module(self, host, module_name, module_args, get_encoding=None, **options):
281281
cmd, args = "ansible --tree %s", []
282282
if self.inventory_file:
283283
cmd += " -i %s"
@@ -307,8 +307,15 @@ def run_module(self, host, module_name, module_args, **options):
307307
raise RuntimeError(
308308
"Error while running {}: {}".format(" ".join(cmd), out)
309309
)
310-
with open(os.path.join(d, files[0]), "r") as f:
311-
return json.load(f)
310+
fpath = os.path.join(d, files[0])
311+
try:
312+
with open(fpath, "r", encoding="ascii") as f:
313+
return json.load(f)
314+
except UnicodeDecodeError:
315+
if get_encoding is None:
316+
raise
317+
with open(fpath, "r", encoding=get_encoding()) as f:
318+
return json.load(f)
312319

313320
@classmethod
314321
def get_runner(cls, inventory):

0 commit comments

Comments
 (0)