Kode Kode - 1 year ago 283
PowerShell Question

Output from PowerShell to Ansible for Use in Ansible Conditional / Controlling Play Execution

I am using Ansible on Windows hosts by calling PowerShell scripts. It works great, but I have a requirement within my Playbook to only have plays run based on condition (using the Ansible When).

The challenge I am facing is how to output from PowerShell to Ansible. As a use case, lets assume that I have two plays. The first play calls a script to check the PowerShell version number, and the second play should only run if the PowerShell version is 5.0.

How would I, if is it possible, to output from the first play's PowerShell script a variable back to Ansible that can used in the When of the second play to either allow or prevent execution?

Answer Source

For this specific case, you'd probably just want to use the ansible_powershell_version fact, eg:

- name: do PS5-only thing
  raw: Run-SomePS5Thing
  when: ansible_powershell_version >= 5

But in general, to capture stuff in a var and use it later, you can just use the register: keyword on the command task in conjunction with filters on the downstream tasks to pluck out the values you need, eg:

  # Filters can deal with text too, but since it's Powershell, 
  # let's use structured data- ConvertTo-Json gives us something Ansible
  # can read with the from_json filter
  - raw: Get-NetRoute | ConvertTo-Json -depth 1
    register: routeout

  # use from_json to read the stdout from raw and convert to a dictionary 
  # we can pull values from
  - debug: msg="Default gateway is {{ (routeout.stdout | from_json).NextHop }}"

  # or do something conditionally:
  - debug: msg="Default gateway isn't what we expected!"
    when: (routeout.stdout | from_json).NextHop != ""
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download