Ansible can execute PowerShell commands on Windows targets via the win_shell and win_powershell modules, enabling remote automation of Windows systems. This works by using WinRM (Windows Remote Management) to connect securely to Windows hosts, allowing you to run scripts, cmdlets, or one-liners just as you would locally—but from a Linux or Windows Ansible control machine. You need Ansible installed, WinRM properly configured on target Windows machines, and appropriate permissions (typically Administrator-level access on the remote host).
What You'll Need
- An Ansible control machine (Linux, macOS, or Windows with Ansible installed)
- Ansible version 2.8 or higher (earlier versions have limited Windows support)
- One or more Windows target hosts running Windows 7 SP1, Windows Server 2008 R2 SP1, or newer
- PowerShell 3.0 or higher on target Windows hosts (standard on all modern Windows versions)
- WinRM service enabled and configured on target Windows machines
- Network connectivity between control and target hosts (port 5985 for HTTP or 5986 for HTTPS)
- Valid credentials with local Administrator rights on target Windows systems
Step-by-Step
- Install Ansible on your control machine: On Linux (Debian/Ubuntu), run
sudo apt update && sudo apt install ansible. On macOS, usebrew install ansible. On Windows, install viapip install ansiblein PowerShell (ensure Python 3.6+ is installed first). Verify withansible --version. - Enable WinRM on target Windows hosts: Open PowerShell as Administrator on each Windows machine. Run the following to configure WinRM:
Enable-PSRemoting -Force. This starts the WinRM service, sets it to auto-start, and creates a firewall rule for HTTP on port 5985. For HTTPS (recommended for production), runwinrm quickconfig -qfollowed bywinrm quickconfig -transport:https(requires a valid SSL certificate). - Test WinRM connectivity locally: On the target Windows host, run
winrm enumerate winrm/config/listenerto confirm listeners exist. Then test from another machine usingTest-WsMan <target_IP_or_hostname>. If successful, you’ll see WS-Management service details. - Configure Ansible inventory for Windows: Edit or create your inventory file (e.g.,
/etc/ansible/hostsor a custom file likewindows.ini). Add your Windows host with WinRM-specific variables. Example:[windows]winserver1 ansible_host=192.168.1.50 ansible_connection=winrm ansible_port=5985 ansible_winrm_server_cert_validation=ignore ansible_user=Administrator ansible_password='P@ssw0rd123!'Note: Store credentials securely (see Tips section). - Run a basic PowerShell command with win_shell: Use the
win_shellmodule for simple commands. In your terminal, run:ansible windows -i ./windows.ini -m win_shell -a "Get-Process | Where-Object { $_.CPU -gt 100 }"This lists processes consuming over 100 seconds of CPU time on all hosts in thewindowsgroup. - Use win_powershell for script blocks : For multi-line or complex scripts, use win_powershell . Create a playbook file (e.g., check_disk.yml ): --- name: Check disk space on Windows hosts hosts: windows gather_facts: no tasks: - name: Get disk info win_powershell: script: | Run it with ansible-playbook check_disk.yml .
- Pass arguments safely: Avoid embedding variables directly in scripts. Use
argsinwin_powershellfor clean parameterization:win_powershell:script: |param([string]$Path, [int]$MinSize)Get-ChildItem $Path -Recurse | Where-Object { $_.Length -gt $MinSize } | Select-Object FullName, Lengthargs:Path: "C:\Logs"MinSize: 10485760
Common Mistakes
- Skipping WinRM configuration: Ansible fails with "HTTP status 401" (unauthorized) or "connection refused" if WinRM isn’t running or listeners aren’t set up. Always run
Enable-PSRemotingfirst. - Using HTTP in environments requiring HTTPS: Many orgs block non-encrypted WinRM traffic. If servers require HTTPS, set
ansible_winrm_transport: sslandansible_port=5986. - Hardcoding passwords in inventory: This is a security risk. Use Ansible Vault (
ansible-vault encrypt_string) or Windows Credential Manager withansible_winrm_operation_timeout_secandansible_winrm_read_timeout_sectuned for long-running commands. - Ignoring PowerShell execution policy: Default
Restrictedblocks scripts. Ansible’swin_shellbypasses this, but forwin_powershell, ensureSet-ExecutionPolicy RemoteSignedis applied on targets (via GPO or manual setup). - Using wrong module:
shellandcommandmodules don’t work on Windows. Always usewin_shellorwin_powershell.
Tips
- Use
gather_facts: noin playbooks to skip fact collection on Windows (it’s slow and error-prone withoutansible_windows_facts). - For large-scale deployments, configure WinRM with certificate-based auth: generate a self-signed cert, bind it to the listener, and pass
ansible_winrm_cert_pemandansible_winrm_cert_key_pemin inventory. - Debug slow commands by increasing timeouts: Add
-e "ansible_winrm_operation_timeout_sec=120 ansible_winrm_read_timeout_sec=130"to your command. - Pre-test PowerShell commands manually on a target machine first—especially those using .NET or COM objects—to ensure they work outside Ansible.
- Group Windows hosts by OS version or function in your inventory for targeted runs (e.g.,
[win2019:children]). - Use the
becomekeyword only when necessary;win_shellruns as the specified user by default, butbecome: yescan cause issues with credential delegation.
Troubleshooting
If your PowerShell command fails, follow this checklist:
- Check basic connectivity: From your Ansible control machine, run
Test-NetConnection <target> -Port 5985(PowerShell) ortelnet <target> 5985(if telnet client is installed). If it fails, verify network firewalls and WinRM service status on the target. - Verify WinRM configuration: On the target, run
winrm get winrm/configand confirmClientandServicesections allow remote management. Look forAllowUnencrypted = trueif using HTTP. - Test credentials manually: Use
Enter-PSSession -ComputerName <target> -Credential <user>to log in interactively. If this fails, Ansible will too. - Enable verbose Ansible output: Add
-vvvto your command (e.g.,ansible windows -m win_shell -a "whoami" -vvv) to see raw WinRM errors, including HTTP status codes and response bodies. - Handle SSL certificate errors: If using HTTPS with self-signed certs, add
ansible_winrm_server_cert_validation=ignoreto inventory (not recommended for production). Better: install a trusted cert on the target. - Address timeout issues: Commands taking >30 seconds often fail by default. Increase timeouts globally in
/etc/ansible/ansible.cfgwithwinrm_operation_timeout_sec = 120andwinrm_read_timeout_sec = 130. - Check PowerShell version: Run
$PSVersionTable.PSVersionon the target. If below 3.0, update PowerShell (requires .NET Framework 4.5+).
Frequently Asked Questions
Can I run PowerShell scripts stored on the control machine against Windows targets?
Yes. Usewin_powershell with the script parameter set to the local file path (e.g., script: "C:\scripts\check_disk.ps1"), or use win_copy to transfer the script first, then execute it remotely.
Do I need PowerShell Core or is Windows PowerShell fine?
Windows PowerShell (5.1+) is fully supported. PowerShell Core (6+) works too, but Ansible’swin_ modules target Windows PowerShell by default. To use PowerShell Core, specify the path explicitly in win_powershell via executable: "pwsh.exe".
How do I pass sensitive variables like passwords securely?
Never hardcode them. Useansible-vault to encrypt the password in your inventory file, or store credentials in Windows Credential Manager and reference them with ansible_winrm_password set to a vault-encrypted variable.
Can I run Ansible from a Windows control machine?
Yes. Install Ansible via pip on Windows, but ensure thepywinrm Python package is installed (pip install pywinrm). Some older Windows versions require additional Visual C++ Redistributables for WinRM dependencies.
Why does my win_shell command return "The term 'xyz' is not recognized"?
This usually means the command (e.g., a custom cmdlet or script) isn’t in the PowerShell session’s path. Either import the module first (e.g.,Import-Module MyModule), or use the full path to the executable. win_shell runs with a minimal environment.
Is Ansible’s Windows support production-ready?
Yes. Ansible has full Windows support since 2015, with enterprise adoption in large organizations. Always test your playbooks in a non-production environment first, and usecheck_mode: yes to validate changes before applying them.