Returning Data from PowerShell Scripts to be consumed by Ansible Playbooks

This topic was not initially obvious to me, so hopefully it will help someone out reading this. Consider the scenario where you have an Ansible playbook which executes some PowerShell code via win_shell and you wish to consume the PowerShell output later on in the playbook.

The output from win_shell is available in the return value stdout (The command standard output ) or stdout_lines (The command standard output split in lines ). This output is in text format, so if you need to grab something particular from the output you can use some text parsing method, for example a regular expression.

Take a look at this example playbook and PowerShell script:

The playbook copies the test_output.ps1 script file, executes it and stores the result in result1. The PowerShell script simply outputs some random log text and some VM IP address details.

We can see what is available to us as output in stdout and, slightly easier to read, stdout_lines:

To consume the info we’re interested in (the VM IP addresses), we can parse the returned text with something like this:

vms: “{{ result1.stdout | regex_findall(’(?<=VM: )(.*)’) }}”

This is all very well, but sometimes parsing text with a regex is not the easiest of tasks. Instead, consider returning text in JSON format and using the from_json filter to process it, illustrated in the following Ansible playbook and PowerShell script:

This time we control the output a bit more carefully from the PowerShell script and convert it to JSON prior to outputting it. Then in the playbook we can process it with the from_json filter :

vm: “{{ result2.stdout | from_json }}”

and consequently consume it easily by picking object properties:

msg: VM {{ vm.name }} has IP Address {{ vm.ipAddress }}

If you use a different method to this, feel free to leave a comment below.