delegate_to localhost tries to connect to WinRM

I need a role with some tasks for remote windows server and some tasks for localhost.

A sample like this fails with

UNREACHABLE! => {“changed”: false, “msg”: “plaintext: HTTPConnectionPool(host=‘localhost’, port=5985): Max retries exceeded with url: /wsman (Caused by NewConnectionError(‘<requests.packages.urllib3.connection.HTTPConnection object at 0x335e5d0>: Failed to establish a new connection: [Errno 111] Connection refused’,))”, “unreachable”: true}

The command I use is as below and Ansible version is 2.3.1.0.

/usr/bin/ansible-playbook temp.yml --extra-vars=“ansible_user=Administrator” --extra-vars=“ansible_password=xxxxxx” --extra-vars=“ansible_port=5985” --extra-vars=“ansible_connection=winrm” -i /home/ansible_hosts -v

temp.yml

I could be wrong here but I believe this is related to variable precedence. Ansible thinks that it has to use winrm to connect to the localhost since extra vars always wins. Try moving all of the connection details to either host_vars/10.x.x.x or group_vars/windows.yml.

http://docs.ansible.com/ansible/latest/playbooks_variables.html#variable-precedence-where-should-i-put-a-variable
http://docs.ansible.com/ansible/latest/intro_windows.html#inventory

I think the above is right -e has highest precedence, which is why setting host level (or group vars) is the right place for specifying windows connection parameters, (as it appears in the windows documentation page).