Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lookup inside lookup - ansible

Tags:

ansible

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.

like image 473
Pratik Tambe Avatar asked Sep 05 '18 16:09

Pratik Tambe


People also ask

How to use lookup in Ansible?

You can activate a custom lookup by either dropping it into a lookup_plugins directory adjacent to your play, inside the plugins/lookup/ directory of a collection you have installed, inside a standalone role, or in one of the lookup directory sources configured in ansible. cfg.

What is With_fileglob?

with_fileglob matches all files in a single directory, non-recursively, that match a pattern. It calls Python's glob library. (plus a warning about relative paths with roles).

What does Set_fact do in Ansible?

This module allows setting new variables. Variables are set on a host-by-host basis just like facts discovered by the setup module. These variables will be available to subsequent plays during an ansible-playbook run.

What is Hostvars Ansible?

With hostvars , you can access variables defined for any host in the play, at any point in a playbook. You can access Ansible facts using the hostvars variable too, but only after you have gathered (or cached) facts.


Video Answer


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' ) }}"
like image 86
techraf Avatar answered Oct 24 '22 08:10

techraf