Ansible Lookups
In most of the organizations, there is a huge amount of configuration data or server details being stored in the different sources having formats like .csv, txt or INI, etc. In Ansible, using lookup plugins, we can query data from these external resources. These sources can be local files or some external datastores. The data fetched by these resources is then evaluated by Ansible plugins and returned using Ansible templating systems and made available in a defined format.
Using lookups
Suppose you want to provide a list of insensitive passwords for a list of dummy servers in an inventory file. You can pass these passwords through a .csv file as a key-value pair.
Consider below inventory file without password details:
webserver1 ansible_host=192.168.25.15
sqlserver1 ansible_host=192.168.25.16
[webservers]
webserver1
[databaseservers]
sqlserver1
[web_database_servers]
webserver1
sqlserver1
Lookups for CSV
Store the password details in .csv format file as follows:
Hostname,Password
webserver1,password
sqlserver1,password
Password for webserver1 is password and for sqlserver1 is also password.
The hostname and passwords are being separated using "," (.csv format)
Now to use the lookup file in our playbook, add below line:
ansible_ssh_pass: "{{ lookup('<file_name>','<path_of_lookup_file>') }}"
- name: Test Connectivity
hosts: webserver1
vars:
ansible_ssh_pass: "{{ lookup('csvfile', 'webserver1 file=credentials.csv delimiter=,') }}"
tasks:
- name: create a dummy file on webserver
command: touch /tmp/csv_lookups.txt
Running the above playbook:
Verifying the same on webserver1:
The csv_lookups.txt file has been created.
Lookups For INI format
Similarly, you can also provide the credentials lookup file in INI format as below:
[webserver1]
password=password
[sqlserver1]
password=password
And to reference this in your playbook as below:
- name: "First Play"
hosts: webserver1
vars:
ansible_ssh_pass: "{{ lookup('ini', 'password section=webserver1 file=credentials.ini') }}"
tasks:
- name: create a dummy file on webserver
command: touch /tmp/lookups_ini.txt
As we saw that Ansible has the lookup utility which can be used across many technologies. But one has to be very careful with the syntax to get the desired result.
Also, please refer to the official documentation for each lookup plugin before using a plugin.