Ansible: bring powershell output into ansible variables

Introduction

I learned yesterday how to deal with structured output from powershell commands in ansible.

  • Run your command in the ansible win_shell module

    • Pipe it through select-object to limit the object structure
    • Pipe it through convertto-json
    • Register the output into an ansible variable
  • Set a new fact with the stdout attribute of the ansible variable, piped through from-json

Example:

(venv) ops@com-adm-l01:~/ansible$ cat ad-hoc/win-list-services.yml 
---
- hosts: windows
  tasks:
    - name: get services and service owners
      win_shell: |
        (Get-WmiObject Win32_Service) | select-object name, StartName | convertto-json
      register: services_raw_json

    - set_fact:
        services: "{{ services_raw_json.stdout | from_json }}"

    - debug:
        var: services

Example ansible run:

(venv) ops@com-adm-l01:~/ansible$ ansible-playbook -i inventories/tst/inventory ad-hoc/win-list-services.yml 
...
        {
            "StartName": "LocalSystem",
            "name": "XblAuthManager"
        },
        {
            "StartName": "LocalSystem",
            "name": "XblGameSave"
        }
    ]
}
PLAY RECAP **************************************************************************************************************************************************************
tst01-bloodhoundtest-w01   : ok=4    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   
tst01-choco-w01            : ok=4    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   
...