Verifying the Inventory Configuration
Now that we've configured our custom inventory file, let's verify that Ansible is using it correctly and explore some commands to work with the inventory.
Checking the Inventory with ansible-inventory
The ansible-inventory
command allows us to view and validate our inventory configuration:
cd ~/project/ansible
ansible-inventory --list
This will display the inventory in JSON format:
{
"_meta": {
"hostvars": {
"localhost": {
"ansible_connection": "local"
}
}
},
"all": {
"children": ["dbservers", "local", "ungrouped", "webservers"]
},
"dbservers": {
"hosts": ["db1.example.com", "db2.example.com"]
},
"local": {
"hosts": ["localhost"]
},
"webservers": {
"hosts": ["web1.example.com", "web2.example.com"]
}
}
For a more readable format, we can use the --graph
option:
ansible-inventory --graph
This will show the inventory in a tree-like structure:
@all:
|--@dbservers:
| |--db1.example.com
| |--db2.example.com
|--@local:
| |--localhost
|--@ungrouped:
|--@webservers:
| |--web1.example.com
| |--web2.example.com
Testing the Connection to Local Host
Let's run a simple ping command to verify that we can communicate with the local host:
ansible local -m ping
You should see output similar to:
localhost | SUCCESS => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python3"
},
"changed": false,
"ping": "pong"
}
Running a Simple Command on Hosts
We can also run a command on our hosts using the ansible
command. Since our example hosts don't actually exist, let's target only the local host:
ansible local -a "uname -a"
This will execute the uname -a
command on the local host and show output similar to:
localhost | CHANGED | rc=0 >>
Linux ubuntu 5.15.0-1033-aws #37-Ubuntu SMP Wed Aug 16 07:38:46 UTC 2023 x86_64 x86_64 x86_64 GNU/Linux
This confirms that Ansible is correctly using our custom inventory file and can execute commands on the hosts defined in it.