Using Ansible to connect to Windows using SSH instead of WinRM

Usually when you read about configuration automation of Windows with Ansible, most blog posts talk about connecting Ansible to Windows using WinRM. WinRM is a Windows specific Remote Management protocol.

On the other hand most information about Ansible and configuration automation can be found in combination with Linux. In Linux environments Ansible uses SSH to connect to remote systems.

The good news is, newer Windows version (Windows 10 and Windows Server 2019 and later) come with a built in OpenSSH Server, so that Windows can be managed remotely using SSH.

There is a previous blog post on this website about enabling OpenSSH server in Windows.
This is a pre-requisite.

Here is a basic inventory file, which you usually use for Ansible

[windows]
srv1 ansible_host=192.168.122.104

Here is a basic playbook.yml, which set a few variables to instruct Ansible to conntect to Windows using SSH instead of WinRM. For the sake of simplicity if have entered all variables directly into the playbook.

---
- hosts: windows
  vars:
    ansible_user: "administrator"
    ansible_password: "mypassword"
    ansible_port: 22
    ansible_ssh_common_args: '-o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null'
    ansible_ssh_retries: 3
    ansible_shell_type: powershell
    ansible_become_method: runas
    ansible_become_user: "{{ ansible_user }}"

  tasks:
    - name: test powershell
      win_shell: |
                get-host
      register: result_get_host
      
    - name: display result_get_host
      debug:
        var: result_get_host

Now you can test the inventory file and the playbook.yml using the ansible-playbook command.

ansible-playbook -i inventory playbook.yml