There are times when you want Ansible to stop printing any of its own text and show only the output of the remote command.
It is like ssh user@server command but with all Ansible options, custom SSH arguments, different transports and other advanced features.
I am referring to the ansible binary and not ansible-playbook, although with some adjustments it is possible to apply this trick to ansible-playbook as well.
Basis of the trick 1) Use the raw module to run remote commands and avoid result packaging by AnsiballZ 2) Force output in json format to extract stdout without using unreliable grep expressions 3) Process the output with jq 4) Ask jq not to print quotes on string values
ANSIBLE_LOAD_CALLBACK_PLUGINS=1 ANSIBLE_STDOUT_CALLBACK=json ansible -i localhost, -m raw -a cat /etc/passwd all -c local | jq -r .plays[].tasks[].hosts[]?.stdout
Dissection 1) The environment variables tell Ansible to load callback plugins and use the json callback for output 2) -i localhost, and -c local are not essential in the example, you can use the corresponding inventory 3) -m raw -a command is the usual ansible invocation to run remote commands without module wrapping 4) -r in jq removes quotes from strings 5) The expression .plays[].tasks[].hosts[]?.stdout traverses all tasks and hosts in all plays and extracts stdout
Why it can be useful What I needed was to retrieve a secret file from a remote server and encrypt it locally using sops. You can use the community.sops.sops_encrypt module but it requires several steps and working with secrets complicates debugging. A simple ansible call followed by a pipe to sops -e consumes less attention and requires Ansible output to arrive as clean as possible, without headers or additional messages, to avoid corrupting the content.
Practical tips Replace localhost with your real inventory when applicable. If the remote command generates line breaks or special characters, be careful with parsing. This method is especially useful when you want to integrate with utilities like sops or with pipelines that expect only the stdout content.
At Q2BSTUDIO we are a software development company specialized in custom applications and custom software. We offer artificial intelligence and AI solutions for businesses, AI agent development, cybersecurity services, aws and azure cloud services and business intelligence services. We also work with Power BI integration and consulting to boost data and analytics projects. If you are looking for experts in custom applications, artificial intelligence, cybersecurity, aws and azure cloud services, AI agents, AI for businesses, business intelligence services or Power BI, at Q2BSTUDIO we can help design and implement secure, scalable solutions adapted to your business.


