How to connect a Windows Machine with Ansible via Winrm

I assume that you have already installed ansible. If not, please check my blog.

We have a couple of things to do on  both the ansible server site and the remote Windows machine.

Let’s start with Windows machine. With most version of Windows, Winrm ships in the box but not turned on by default.

There is a script you can run on the remote Windows machine in PowerShell console as an Administrator. Please download it from link below. Please “Set-ExecutionPolicy Bypass” before executing the script.

https://github.com/cemekli/ansible/blob/main/ConfigureRemotingForAnsible.ps1

check winrm configuration with

 winrm get winrm/config/service

 

Check Auth and DefaultPorts section. It should be Basic=true and 5985,5986 port are available.

Ok, let’s move on with ansible server site.

We need to install pywinrm libraries with following command

pip3.9  install pywinrm

Also we need following collections for management of  Windows machine.

ansible-galaxy collection install ansible.windows
ansible-galaxy collection install chocolatey.chocolatey
ansible-galaxy collection install community.windows

Now we can prepare the inventory file with following lines. Please change provided ip and other information with your Windows remote machine ip and user/passwd.  I am using /etc/ansible/hosts file for inventory.

[win]
192.168.1.139

[win:vars]
ansible_user=test
ansible_password=test
ansible_port=5986
ansible_connection=winrm
ansible_winrm_transport=basic
ansible_winrm_server_cert_validation=ignore

 

Ok. Now try to reach remote Windows machine. “win” comes from inventory file above and “-m win_ping” is built-in windows ping module.

ansible win -m win_ping

if you encounter the following  error. You need to uninstall and re-install the urllib3 lib library with 1.x version.

192.168.1.139 | FAILED! => {
“msg”: “winrm or requests is not installed: urllib3 v2 only supports OpenSSL 1.1.1+, currently the ‘ssl’ module is compiled with ‘OpenSSL 1.0.2k-fips 26 Jan 2017’. See: https://github.com/urllib3/urllib3/issues/2168”
}

For uninstall and re-install use following command.

 pip3.9 uninstall urllib3
 pip3.9 install 'urllib3<2.0'

 

if you face an error below , probably Windows local user does not have any Administrator privilege.

192.168.1.139 | UNREACHABLE! => {
“changed”: false,
“msg”: “basic: the specified credentials were rejected by the server”,
“unreachable”: true
}

Let’s try a simple playbook.

 

---
- hosts: win
  tasks:
  - name: Get disk facts.
    win_disk_facts:
  - name: Print GB
    debug:
      msg: '{{ disksize_gib }}'
    vars:
      disk: '{{ ansible_facts.disks|selectattr("system_disk")|first }}'
      disksize_gib: '{{ (disk.size/1024|pow(3))|round|int }} GiB'

 

ansible-playbook disk_usage.yml

 

Ok, that’s it!

This entry was posted in Ansible and tagged , , , , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *