How to Add Hosts to Your Ansible Inventory

Every server you manage with Ansible needs to be added to your Inventory.yml file. Your Ansible inventory organizes these remote hosts into groups for easier configuration within your playbooks.

Below we cover how to add hosts to your Ansible inventory, sample groups, and testing an inventory connection.

Manage your Ansible inventory with our reliable Cloud VPS Hosting.

Edit Your Ansible Inventory.yml

  1. Log into SSH
  2. Navigate to your Ansible directory
  3. Edit the inventory.yml file: nano inventory.yml
  4. Copy both code blocks below within your inventory as needed: Ctrl + V

Sample Inventory.yml

The all group is the first group and includes all hosts listed within your inventory. The vars indicator allows global default variables for using the group. The variables in the example below state to connect to remote hosts via SSH as user root. The ansible_connection can be set to any Ansible connection plugin.

all:
  vars:
    ansible_connection: ssh
    ansible_user: root

Other groups can follow the format below. Keep in mind, there are other ways to build your Ansible inventory with groups and variables. Hosts can be defined as a domain or server IP address.

Only one host is required for a playbook to run.

group-1:
  hosts:
    domain-1.tld:
      example-var-1: # variable affects domain-1.tld only
    domain-2.tld:
  vars:
    example-var-2: # variable affects all hosts within group

Test Your Inventory

After editing your inventory file, test your Ansible connection to your remote host: ansible -m ping [host/group] -i inventory.yml

The results should resemble the following:

[Any warnings will be listed first]
domain.com | SUCCESS => {
   "ansible_facts": {
       "discovered_interpreter_python": "/usr/local/bin/python [version]"
   },
   "changed": false,
   "ping": "pong"
}

Learn more about IT automation in our Ansible Education Channel.

Was this article helpful? Let us know!