Score:0

When Ansible initiates a PowerShell script, how to get Ansible to return "ok" (nothing changed)?

bq flag

Usually when Ansible kicks off a PowerShell script with win_command/win_shell/win_psexec, as long as it doesn't run into errors it'll return "changed", because of course it doesn't know what all the script did.

Since we can return any exit code in a PowerShell script is there a way, via exit codes or otherwise, to notify Ansible that there was no change required so that Ansible returns an "ok" status? Or will it always return "changed" no matter what (assuming no failure)?

Score:2
bq flag

I think I found it. The win_powershell module accesses the $Ansible PowerShell variable, whereby I can modify what information is returned to the controller.

From the win_powershell documentation:

  • $Ansible.Result is a value that is returned back to the controller as is.
  • $Ansible.Diff was added in the 1.12.0 release of ansible.windows and is a dictionary that is set to the diff result that can be interepreted by Ansible.
  • $Ansible.Changed can be set to true or false to reflect whether the module made a change or not. By default this is set to true.
  • $Ansible.Failed can be set to true if the script wants to return the failure back to the controller.
  • $Ansible.Tmpdir is the path to a temporary directory to use as a scratch location that is cleaned up after the module has finished.
  • $Ansible.Verbosity reveals Ansible’s verbosity level for this play. Allows the script to set VerbosePreference/DebugPreference based on verbosity. Added in 1.9.0.
Score:1
fr flag

In a nutshell as a pseudo code example, based on your rc variation scenario where we could imagine you exit with 0 when nothing changed, with 4 when something changed and with any other code when something went wrong...

- name: some shell task
  ansible.windows.win_command: my_command
  register: my_command
  failed_when: my_command.rc | int not in [0,4]
  changed_when: my_command.rc | int == 4

For more information, see Error handling in playbooks

Note that for commands which are strictly informational and never change anything, changed_when: false is perfectly acceptable.

mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.