--- # Install Windows Updates on the [windows] inventory group and reboot if required. # Usage: # ansible-playbook windows/update.yaml # install + reboot if needed # ansible-playbook windows/update.yaml -e reboot=false # install only, report if reboot pending # ansible-playbook windows/update.yaml -e search_only=true # just list available updates - name: Update Windows servers hosts: windows gather_facts: false vars: reboot: true search_only: false update_categories: - SecurityUpdates - CriticalUpdates - UpdateRollups - DefinitionUpdates - Updates tasks: - name: Check connectivity ansible.windows.win_ping: - name: Search for available updates ansible.windows.win_updates: category_names: "{{ update_categories }}" state: searched register: search when: search_only | bool - name: List available updates ansible.builtin.debug: msg: "{{ search.updates | dict2items | map(attribute='value.title') | list }}" when: search_only | bool - name: Install updates and report when: not search_only | bool block: - name: Install updates ansible.windows.win_updates: category_names: "{{ update_categories }}" state: installed reboot: "{{ reboot | bool }}" reboot_timeout: 3600 register: result # With reboot=false, updates blocked by the pending restart (WU_E_INSTALL_NOT_ALLOWED) # are expected; only fail on other errors. failed_when: >- result.failed_update_count | default(0) | int > 0 and (reboot | bool or result.updates | dict2items | map(attribute='value') | selectattr('failure_hresult_code', 'defined') | rejectattr('failure_hresult_code', 'equalto', 2149842966) | list | length > 0) # Runs even if the install failed, so a failed run still shows what is pending. always: # Re-search afterwards: win_updates marks updates that were staged for a reboot as # "not installed" even after the reboot applies them, so this is the reliable view. - name: Check what is still pending ansible.windows.win_updates: category_names: "{{ update_categories }}" state: searched register: after - name: Report vars: reboot_pending: "{{ after.reboot_required | default(result.reboot_required | default(false)) | bool }}" ansible.builtin.debug: msg: - "Processed this run: {{ result.updates | default({}) | dict2items | map(attribute='value.title') | list }}" - "Still pending: {{ after.updates | default({}) | dict2items | map(attribute='value.title') | list }}" - "Reboot still required: {{ reboot_pending }}{{ ' - reboot and re-run to finish' if reboot_pending | bool else '' }}"