1

I am trying to execute an ansible-playbook commend in subprocess at the end of a python script, which does 'magic' before kicking off the correct command.

If you are not familiar with ansible-playbook. The output is normally colorful(green/yellow/red text) and is correctly spaced.

I would be fine if python just kicked off a command and exited if need be.

What I am getting currently is black and white text after the command has completed.

I want to get the normal color outout in real time as if I ran ansible-playbook from the command line. Is there a way to do this?

my current code is as follows:

command = '{0} --flush-cache -f 20 -i {1}/dyn_inv.py --extra-vars @{2}/vars.json {3}'.format(ansible_playbook_loc, script_path, var_path, args.playbook[0]) print command process = subprocess.Popen(command.split(), stdout=subprocess.PIPE, stderr=subprocess.STDOUT) devices = process.communicate()[0].rstrip('\n').split() print devices 
2
  • Most applications that display colored output only do so if output is going to a terminal, not a pipe or file. Check if the command has an option to force colored output when not going to a terminal. Commented Jan 12, 2018 at 21:47
  • If not, use the pseudo terminal utilities to run the ansible-playbook command through a pty. Commented Jan 12, 2018 at 21:49

1 Answer 1

4

Ansible by default will only colorize text when its output is connected to a terminal. You can force it to use color codes by setting ANSIBLE_FORCE_COLOR=1 in the environment. For example:

import os os.environ['ANSIBLE_FORCE_COLOR'] = '1' 

You can accomplish the same thing by setting the force_color option in your ansible.cfg.

Sign up to request clarification or add additional context in comments.

1 Comment

Works perfectly, Thanks!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.