diaryfolio
diaryfolio

Reputation: 625

Ansible: How to create variables from a lookup file

We have many csv files and contain lookup data for various configurations.

#eg of lookup file csv
hostname,ip,country,type,port
atlanta1,1.2.3.4,US,ui,8080
toronto1,1.2.3.5,CA,ui,8080
toronto2,1.2.3.9,CA,db,8000
another3,1.2.3.6,UK,db,8000

We need to populate complex & concatenated variables which then needs to be used in other playbooks,

# Eg. concatenated variables  http:{{hostname}}:{{port}} from above lookup csv file
ui_cluster = http://atlanta1:8080;http://toronto1:8080
db_cluster = http://atlanta1:8000;http://toronto1:8000

.. And finally the concatenated variables are used in final playbooks

#configurations in final customer template
my_build_script_UIcluster= {{ui_cluster}}
my_build_script_DBcluster= {{db_cluster}}

I want to use such variables which are created from above lookup to be used within the templates. How to do this or best approach for this?

Upvotes: 2

Views: 3926

Answers (2)

Kim
Kim

Reputation: 1684

The include_csv module https://github.com/mkouhei/ansible-role-includecsv sounds like what you're looking for.

Upvotes: 2

Max
Max

Reputation: 1002

You can use the jinja2 csv lookup filter:

The csvfile lookup reads the contents of a file in CSV (comma-separated value) format. The lookup looks for the row where the first column matches keyname, and returns the value in the second column, unless a different column is specified.

(from the official documentation)

The lookup filter returns an array where each line is represented by a key value object. You can use the jinja2 map filter to create a list of one key's value:

Applies a filter on a sequence of objects or looks up an attribute. This is useful when dealing with lists of objects but you are really only interested in a certain value of it.

(from the official documentation)

This should be everything you need altough not a copy and paste answer.

Upvotes: 1

Related Questions