24

Ansible version 2.1

I have an inventory file hosts

[nodes]
host1
host2
...

And a simple playbook site.yml

---
- hosts: all
  tasks:
    - include: tasks/main.yml

If I just start the play,

ansible-playbook -i hosts site.yml -vvvv

I get this error for all hosts,

ESTABLISH SSH CONNECTION FOR USER: None
fatal: [host1]: UNREACHABLE! => {"changed": false, "msg": "Failed to connect to the host via ssh.", "unreachable": true}
...

However, reading Ansible Inventory doc, I added ansible_user to the hosts file,

[nodes]
host1    ansible_user=root
host2    ansible_user=root
...

This solves the SSH CONNECTION UNREACHABLE error. However, do I have to add ansible_user=root next to all the hosts? Or is there a simpler way to do this?

kenorb
  • 24,736
  • 27
  • 129
  • 199
Howard Lee
  • 986
  • 4
  • 8
  • 14

3 Answers3

28

Check the example/default ansible.cfg file, and you'll find this under [defaults]:

# default user to use for playbooks if user is not specified
# (/usr/bin/ansible will use current user as default)
#remote_user = root

Uncomment remote_user and set the user to what you want to log in as.

Where does Ansible get ansible.cfg? The same file explains:

# nearly all parameters can be overridden in ansible-playbook 
# or with command line flags. ansible will read ANSIBLE_CONFIG,
# ansible.cfg in the current working directory, .ansible.cfg in
# the home directory or /etc/ansible/ansible.cfg, whichever it
# finds first
rrauenza
  • 215
  • 2
  • 7
Deltik
  • 19,353
  • 17
  • 73
  • 114
  • Thanks @Deltik, would you be able to answer [this one](http://superuser.com/questions/1081619/where-to-store-variables-in-ansible) as well? – Howard Lee May 27 '16 at 20:28
  • @HowardLee: Your [other question](http://superuser.com/q/1081619/83694) is primarily opinion-based and not a good fit for Super User. – Deltik May 27 '16 at 20:54
20

Another way is to use --user to define remote ssh user. Type ansible-playbook --help to read more. This is my typical command:

ansible-playbook -i hosts site.yml --user <user> --ask-pass -vvvv

--ask-pass will prompt to enter password for --user

Howard Lee
  • 986
  • 4
  • 8
  • 14
12

In addition to modifying the ansible.cfg, u can also define variables for 'all' group or other groups

https://docs.ansible.com/ansible/latest/user_guide/intro_inventory.html#group-variables

[all:vars]
ansible_user = root
ansible_port = 22
ChuenChih Siu
  • 121
  • 1
  • 3