rabejens
rabejens

Reputation: 8132

How to do CSV lookups in ansible where the key comes from a variable?

So ansible has the possibility of looking up things from a CSV file, the example on their web page is:

- debug: msg="The atomic number of Lithium is {{ lookup('csvfile', 'Li file=elements.csv delimiter=,') }}"
- debug: msg="The atomic mass of Lithium is {{ lookup('csvfile', 'Li file=elements.csv delimiter=, col=2') }}"

Now, my CSV file contains a mapping of hostnames to a number, like this:

HOST,ID
foo,0
bar,1

Now, when I adapt this to:

- debug: msg="My ID is {{ lookup('csvfile', '{{ inventory_hostname }} file=my.csv delimiter=,') }}"

I get the error:

Failed to template msg="My ID is {{ lookup('csvfile', '{{ inventory_hostname }} file=my.csv delimiter=,') }}": need more than 1 value to unpack

How do I do this right?

Upvotes: 1

Views: 2752

Answers (1)

r-m-n
r-m-n

Reputation: 15100

use the string formatting

- debug: msg="My ID is {{ lookup('csvfile', '{} file=my.csv delimiter=,'.format(inventory_hostname)) }}"

Upvotes: 4

Related Questions