Inventory File Basics
Ansible needs to know what machines you're going to be managing. We put this information in an inventory file so that Ansible has all the information it needs to connect and perform operations on our machines.
It doesn't matter if you use a file or a directory of multiple files (as your machine count grows). It will all be figured out intelligently and is a great way to segment certain environments as we'll see later.
Inventory File Basics
Create a new file, you can name it whatever you like, but traditionally it's named “inventory”. Inside, put the following one line and save it.
What just happened? We listed one machine, the local computer you're reading this on (localhost), and no other machines or additional information.
Recall from Your First Command that we had this inventory information inline, but now we moved the contents to a file, and pass the path to the file instead of typing the content ("localhost,") manually.
ansible all -i "localhost," -m debug -a "msg='Hello Ansible'"
ansible all -i ./inventory -m debug -a "msg='Hello Ansible'"
Adding More to the Inventory File
So let's go back to the inventory file. We have “localhost” in there now, but it could just as easily be our local machine's IP address, usually “127.0.0.1” on Unix systems. Additionally, it could the be IP address of any machine you like, whether it's you local computer, one on your local network (LAN), or the IP address of a remote server on the Internet cloud.
Adding Connection Information
Chances are you have to connect to an external machine (via SSH) using a specific user name. Different machines run different operating systems and even if the operating systems are the same, they could be configured differently. There's a lot of “different” that could go on. So, we'll need to provide this user information in the inventory file to ensure we can connect. Here's a revised inventory file (the “#” character indicates a comment and anything after it is ignored).
# Target Local Computer localhost # Also Targets Local Computer # But uses the IP instead of "localhost" 127.0.0.1 # Target a computer on our LAN by using its IP 192.168.0.10 # Target the same computer on our LAN by its IP # But let's add a specific username to connect as 192.168.0.10 ansible_ssh_user=myuser # Target a different computer by its IP # with a custom username for the initial connection and # SSH running on port 2222 (instead of the default of 22) 10.10.0.42 ansible_ssh_user=ubuntu ansible_ssh_port=2222
While we could add password information for the connection here in our inventory file, but passwords should be secret. Because this Ansible code is likely to be in a version control system (VCS) like git, we won't put any password information in the inventory file. Instead, we'll provide the password upon running the commands and move to SSH authentication instead of passwords in the future.