Needs some explaining. Don't understand why ansible is trying to ssh to host

Hi All,

I am new to Ansible and I am trying to understand something.

I have a simple playbook which will read a csv and display its contents.
But for some reason ansible is trying to ssh into the machine.

Here is my playbook:

---

- name: create list from csv
  hosts: localhost
  gather_facts: no
  tasks:
    - name: Read CSV
      read_csv:
        path: vlans.csv
      register: vlans
      delegate_to: localhost
    - name: Display CSV Data
      debug:
        var: vlans.dict
    - name: Iterate over CSV data
      debug:
        msg: "this is your ID:{{ item.0 }} , and this is the name:{{ item.1 }}"
      with_items: "{{ vlans.dict }}"

the ansible.cfg is empty.
and I am using the command like this

ansible-playbook -i hosts.ini ./test.yml

The output is like this:

PLAY [create list from csv] ***************************************************************************************************************************************

TASK [Read CSV] ***************************************************************************************************************************************************
fatal: [localhost]: UNREACHABLE! => {"changed": false, "msg": "Failed to connect to the host via ssh: ssh: connect to host 127.0.0.1 port 22: Connection refused", "unreachable": true}

PLAY RECAP ********************************************************************************************************************************************************
localhost                  : ok=0    changed=0    unreachable=1    failed=0    skipped=0    rescued=0    ignored=0   

host.ini contents:
localhost ansible_host=127.0.0.1

and insights are appreciated…

You need to set ansible_connection to local see the documentation here, add it to your inventory, I use a YAML inventory for cases this:

---
all:
  children:
    localhosts:
      hosts:
        localhost:
          ansible_connection: local
...
3 Likes

I guess hosts.ini contains an explicit definition for localhost without setting ansible_connection to local.

3 Likes

Ah, I only saw that now - yes, that’s the reason. You’re telling ansible that localhost is a host ansible should connect to by SSHing to 127.0.0.1. So ansible does that for you :slight_smile:

Either remove localhost from hosts.ini, or set ansible_collection=local, like this:

localhost ansible_host=127.0.0.1 ansible_connection=local
3 Likes

Ah, I see.

Thanks everyone for explaining!

2 Likes

FYI, if localhost is not defined in the inventory, Implicit ‘localhost’ is used.
In this case also, no ssh connection is made to localhost.

1 Like