AUTOMATESQL
Back to all guides
June 10, 2025•14 min

SQL Server AG Patching with Ansible: Tasks

Jun 10, 2025

Technical Screenshot

In my last post, we defined the prerequisites needed for patching. Before applying the patch, we need to make sure the variables are set and that we're dealing with a healthy AG. With those out of the way, we're ready to build out the remaining tasks.

  • tasks/cleanup.yml
  • tasks/failback.yml
    • files/failback_ag.ps1
  • tasks/failover.yml
    • files/failover_ag.ps1
  • tasks/patch_secondaries.yml
    • files/change_failover_mode.ps1
  • tasks/main.yml(We'll complete the file by adding the additional tasks.)
  • playbook_patchSqlAG.yml(playbook to execute the role)

By the end of this post, you'll have all the required files to build the sql_ag_patch role. We'll also complete the tasks/main.yml file that we started during the last post.

tasks/cleanup.yml

During the install, we copy the update exe and the SqlServer PowerShell module to each managed node. This set of tasks will remove both of those.

tasks/failback.yml

This file is used to initiate a fallback of the AG (if specified). It uses the ansible.windows.win_powershell module to execute the failback_ag.ps1 script.

files/failback_ag.ps1

The following script performs the failback process to the original primary replica. It's designed to safely switch database roles between primary and secondary replicas.

tasks/failover.yml

This file follows a similar pattern as failback.yml. We're leveraging Ansible's windows.win_powershell module to execute the failover.ps1 script. However, before doing so, we use the builtin.set_fact module to create a two new facts; ps_path_ag_primary and new_primary. The new_primary fact is used later to determine which replica became the new primary after the failover was performed.

files/failover.ps1

This script finds and fails over to a suitable secondary replica. It searches for replicas that are synchronous, secondary, and synchronized, then checks each one to ensure it matches the desired SQL Server version. Once it finds the first replica meeting all criteria (synchronous commit mode, secondary role, synchronized state, and correct version), it performs the failover to that replica and outputs the new primary server name. The script handles both default and named SQL Server instances and sets appropriate status variables and exits after the failover.

tasks/patch_secondaries.yml

This file manages the patching process for all secondary replicas. It only runs when patching is needed (is_patch_needed is true) and follows a structured approach: first changing the secondary replica's failover mode to manual to prevent automatic failover during patching, then installing SQL updates, optionally rebooting the server, waiting for SQL Server to become available again, and finally restoring the failover mode back to automatic if it was previously changed. The process ensures the secondary replicas can be safely patched without disrupting the availability group's automatic failover capabilities. To do: A future version of this file will include a check for a pending reboot of the target server.

files/change_failover_mode.ps1

This script changes the failover mode of a secondary replica. It takes parameters of the SQL instance, AG name, current and new primary servers, hostname, and target failover mode (Manual or Automatic). The script intelligently determines which primary server to connect to, constructs the proper PowerShell paths for both primary and secondary replicas (handling default vs named instances), verifies it's connecting to the actual primary replica, locates the target secondary replica, and then changes its failover mode only if it differs from the current setting. It includes validation to ensure it's working with the correct replicas before making changes.

tasks/main.yml

And finally, you can complete the main.yml file. This file orchestrates the complete SQL Server Always On Availability Group patching process. First, it runs prerequisites and identifies the primary node, then validates the AG health before patching. For secondary replicas, it applies patches directly when needed. For primary replicas requiring patches, it performs a more complex process - failing over to a secondary, patching the former primary (now secondary), and optionally failing back to the original primary if configured. The process concludes with the final AG validation and cleanup of temporary files. The workflow handles different server roles and only performs operations when patching is actually needed, ensuring minimal disruption to the availability group.

playbook_patchSqlAG.yml

We can't forget the playbook that imports the sql_ag_patch role and then executes it. To patch each secondary individually be sure to uncomment serial: 1.

Conclusion

We've now completed the sql_ag_patch Ansible role that automates the entire SQL Server Always On Availability Group patching process. From the initial prerequisites and health validation to the coordinated failover, patching, and fallback operations. This role provides a robust example of the level of automation DBAs can achieve with Ansible.

The role we've built handles the complexities that make AG patching challenging: intelligent replica selection, proper failover mode management, version validation, and comprehensive error handling. By automating these processes, we've eliminated the manual steps that often lead to human error during maintenance windows.

Key benefits of this approach include:

  • Consistency and Reliability- Every patching operation follows the same validated process, reducing the risk of configuration drift or missed steps that can occur with manual procedures.
  • Reduced Downtime- The automated failover and fallback processes minimize the time your instances spend in transitional states.
  • Enhanced Safety- Built-in health checks and version validations ensure patches are only applied when conditions are optimal, preventing potentially disruptive operations.
  • Scalability- Whether you're managing a single AG or dozens across multiple environments, the same role can be deployed consistently across your infrastructure.

This series has taken you from understanding the prerequisites through building each component of an example patching solution. In an upcoming video, I'll walk through executing this role against the SQL Server environment shown in the screenshot below. This will show it in action, and I'll highlight the capabilities that make this approach so valuable to enterprise SQL Server DBAs.

Before

Technical Screenshot

After

Technical Screenshot

Play Recap

Technical Screenshot

Previous ← SQL Server AG Patching with Ansible: Prerequisites

LinkedIn YouTube Newsletter

Share this article:
The Database Platform Automation Roadmap

The Database Platform Automation Roadmap

Move from checklists and scattered scripts to desired-state Ansible playbooks—so you can stop wondering whether production still matches what you built. Includes the 60-second self-audit and 23-page field guide (PDF).