Lookup inside lookup - ansible

Viewed 3802

I am trying to use the lookup plugin to lookup the environment variable from inside a lookup function that looks up a file.

So the file name is _hosts.txt and i want the lookup function to replace the ENV with the passed environment variable.

I looked up at the ansible documentation for lookup and still couldnt figure out the error.

Here is the code block:

- name: "Update the /etc/hosts file"
  blockinfile:
   block: "{{ lookup('file', ' + lookup('env', 'ENV') +_hosts.txt') }}"
   dest: "/etc/hosts"
   backup: yes

Output:

FAILED! => {"msg": "template error while templating string: expected token ',', got 'env'. String: {{ lookup('file', ' + lookup('env', 'ENV') +_hosts.txt') }}"}

I know its a syntax issue but just cant figure out what it is.

1 Answers

Use a helper variable:

- name: "Update the /etc/hosts file"
  blockinfile:
    block: "{{ lookup('file', filename) }}"
  vars:
    filename: "{{ lookup('env', 'ENV') }}_hosts.txt"

or you can write it in one line:

block: "{{ lookup('file', lookup('env', 'ENV') + '_hosts.txt' ) }}"
Related