Programster's Blog

Tutorials focusing on Linux, programming, and open-source

The Ansible Hosts File

The hosts file categorizes servers into groups for our playbooks. For example, it may be useful to create a group for all of the apt based servers (ubuntu/debian etc), called apt-servers for a playbook that wishes to update apt-based servers. A server can belong to any number of groups and a group is simply defined by putting square brackets around the name for the group, before then listing the various servers' IP addresses or hostnames on subsequent lines like so:

[apt-servers]
server1.programster.org
server2.programster.org
server3.programster.org

[group2]
server2.programster.org
server4.programster.org

Specify SSH Keys

If your ansible server needs to use different SSH keys to connect to the various servers, then you will also need to specify the key on the relevant line:

[amazon-linux-servers]
site1.programster.org ansible_ssh_private_key_file=/home/admin/key1.pem
site2.programster.org ansible_ssh_private_key_file=/home/admin/key2.pem
site3.programster.org ansible_ssh_private_key_file=/home/admin/key3.pem

Specify SSH PORT

If the remote server needs to be connected on a port other than 22, you can specify it after the hostname with a colon. The example below connects on port 2222.

[amazon-linux-servers]
site1.programster.org:2222

File Location

The file may be found in different places depending on how you installed ansible. If you installed through the in-built package management system or a PPA, then the location is probably:

/etc/ansible/hosts

However, I have found that when I installed through PIP on Debian a long time ago, it was at:

$HOME/ansible/ansible_hosts
Last updated: 8th January 2023
First published: 16th August 2018