jerdub1993
jerdub1993

Reputation: 475

How to get Ansible to return 'OK' (nothing changed) when initiating a PowerShell script?

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)?

Upvotes: 0

Views: 1428

Answers (1)

U880D
U880D

Reputation: 12070

it'll return changed, because of course it doesn't know what all the script did

Right, because of that that is the defined default behavior for this type of module(s).

Regarding your question

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?

this is already the correct idea. In other words, yes, such kind of behavior is possible.

Additionally to the already given comment about Defining changed, one'll need also Defining failure. This is because a non-zero return code would result into an failure otherwise.

The minimal example playbook

---
- hosts: localhost
  become: false
  gather_facts: false

  tasks:

  - name: Exec sh command
    shell:
      cmd: "echo ''; exit 254;"
    register: result
    failed_when: result.rc != 0 and result.rc != 254
    changed_when: result.rc != 254

  - name: Show result
    debug:
      msg: "{{ result }}"

will result into the output of

TASK [Exec sh command] *****************

TASK [Show result] *********************
ok: [localhost] =>
  msg:
    changed: false
    cmd: echo ''; exit 254;
    delta: '0:00:00.012397'
    end: '2022-12-24 18:00:00.012397'
    failed: false
    failed_when_result: false
    msg: non-zero return code
    rc: 254
    start: '2022-12-24 18:00:00.000000'
    stderr: ''
    stderr_lines: []
    stdout: ''
    stdout_lines: []

Similar Q&A

Upvotes: 1

Related Questions