Ansible is a versatile automation tool capable of managing Windows systems, including the execution of PowerShell scripts. This article explains how Ansible can run PowerShell scripts, its requirements, and best practices for integrating PowerShell into your automation workflows.
Can Ansible Run PowerShell Scripts?
Yes, Ansible can run PowerShell scripts on Windows systems. Using the win_shell and win_command modules, you can execute inline PowerShell commands or external PowerShell script files on target Windows hosts.
Prerequisites for Running PowerShell Scripts with Ansible
1. Enable Windows Remote Management (WinRM)
WinRM allows Ansible to communicate with Windows hosts. To enable it:
1. Open PowerShell as Administrator.
2. Run the following commands:
``powershell
winrm quickconfig
winrm set winrm/config/service/auth '@{Basic="true"}'
winrm set winrm/config/service '@{AllowUnencrypted="true"}'
Set-Item wsman:\localhost\Client\TrustedHosts -Value "<Ansible_Control_Node_IP>"
`
2. Install pywinrm
Install the pywinrm Python library on the Ansible control node:
`bash
pip install pywinrm
`
3. Configure Ansible Inventory
Define your Windows hosts in the inventory file:
`ini
[windows]
windows_host ansible_host=192.168.1.10 ansible_user=Administrator ansible_password=your_password ansible_connection=winrm
`
Using Ansible to Run PowerShell Scripts
1. Run Inline PowerShell Commands
Use the win_shell module to execute PowerShell commands directly:
`yaml
- name: Run an inline PowerShell command
hosts: windows
tasks:
- name: Get Windows services
win_shell: Get-Service | Select-Object -First 5
`
2. Execute PowerShell Scripts from a File
To run an external PowerShell script, use the win_shell module:
`yaml
- name: Run a PowerShell script
hosts: windows
tasks:
- name: Execute a PowerShell script
win_shell: |
powershell.exe -ExecutionPolicy Bypass -File C:\Scripts\example.ps1
`
3. Transfer and Execute PowerShell Scripts
If the script is not present on the Windows host, use the copy module to transfer it first:
`yaml
- name: Transfer and run a PowerShell script
hosts: windows
tasks:
- name: Copy the script to the host
copy:
src: ./example.ps1
dest: C:\Temp\example.ps1
- name: Execute the PowerShell script
win_shell: |
powershell.exe -ExecutionPolicy Bypass -File C:\Temp\example.ps1
`
4. Capture Command Output
You can store the output of a PowerShell script execution for further use:
`yaml
- name: Capture PowerShell script output
hosts: windows
tasks:
- name: Run a script and save output
win_shell: |
powershell.exe -ExecutionPolicy Bypass -Command "Get-Process"
register: process_output
- name: Display output
debug:
var: process_output.stdout
``